text
stringlengths
54
60.6k
<commit_before>#include <QString> #include <coreplugin/icore.h> #include "Settings.h" #include "Constants.h" using namespace QtcCppcheck::Constants; using namespace QtcCppcheck::Internal; Settings::Settings(bool autoLoad) : checkOnBuild_ (false), checkOnSave_ (false), checkOnProjectChange_ (false), checkOnFileAdd_ (false), checkUnused_ (false), checkInconclusive_ (false), showBinaryOutput_ (false), showId_ (false), popupOnError_ (false), popupOnWarning_ (false) { if (autoLoad) { load (); } } void Settings::save() { Q_ASSERT (Core::ICore::settings () != NULL); QSettings& settings = *(Core::ICore::settings ()); settings.beginGroup (QLatin1String (SETTINGS_GROUP)); settings.setValue (QLatin1String (SETTINGS_BINARY_FILE), binaryFile_); settings.setValue (QLatin1String (SETTINGS_CHECK_ON_BUILD), checkOnBuild_); settings.setValue (QLatin1String (SETTINGS_CHECK_ON_SAVE), checkOnSave_); settings.setValue (QLatin1String (SETTINGS_CHECK_ON_PROJECT_CHANGE), checkOnProjectChange_); settings.setValue (QLatin1String (SETTINGS_CHECK_ON_FILE_ADD), checkOnFileAdd_); settings.setValue (QLatin1String (SETTINGS_CHECK_UNUSED), checkUnused_); settings.setValue (QLatin1String (SETTINGS_CHECK_INCONCLUSIVE), checkInconclusive_); settings.setValue (QLatin1String (SETTINGS_CUSTOM_PARAMS), customParameters_); settings.setValue (QLatin1String (SETTINGS_IGNORE_PATTERNS), ignorePatterns_.join (",")); settings.setValue (QLatin1String (SETTINGS_SHOW_OUTPUT), showBinaryOutput_); settings.setValue (QLatin1String (SETTINGS_SHOW_ID), showId_); settings.setValue (QLatin1String (SETTINGS_POPUP_ON_ERROR), popupOnError_); settings.setValue (QLatin1String (SETTINGS_POPUP_ON_WARNING), popupOnWarning_); settings.endGroup (); } void Settings::load() { Q_ASSERT (Core::ICore::settings () != NULL); QSettings& settings = *(Core::ICore::settings ()); settings.beginGroup (QLatin1String (SETTINGS_GROUP)); binaryFile_ = settings.value (QLatin1String (SETTINGS_BINARY_FILE), QString ()).toString (); checkOnBuild_ = settings.value (QLatin1String (SETTINGS_CHECK_ON_BUILD), false).toBool (); checkOnSave_ = settings.value (QLatin1String (SETTINGS_CHECK_ON_SAVE), false).toBool (); checkOnProjectChange_ = settings.value (QLatin1String (SETTINGS_CHECK_ON_PROJECT_CHANGE), false).toBool (); checkOnFileAdd_ = settings.value (QLatin1String (SETTINGS_CHECK_ON_FILE_ADD), false).toBool (); checkUnused_ = settings.value (QLatin1String (SETTINGS_CHECK_UNUSED), false).toBool (); checkInconclusive_ = settings.value (QLatin1String (SETTINGS_CHECK_INCONCLUSIVE), false).toBool (); customParameters_ = settings.value (QLatin1String (SETTINGS_CUSTOM_PARAMS), QString ()).toString (); ignorePatterns_ = settings.value (QLatin1String (SETTINGS_IGNORE_PATTERNS), QString ()).toString ().split (",", QString::SkipEmptyParts); showBinaryOutput_ = settings.value (QLatin1String (SETTINGS_SHOW_OUTPUT), false).toBool (); showId_ = settings.value (QLatin1String (SETTINGS_SHOW_ID), false).toBool (); popupOnError_ = settings.value (QLatin1String (SETTINGS_POPUP_ON_ERROR), true).toBool (); popupOnWarning_ = settings.value (QLatin1String (SETTINGS_POPUP_ON_WARNING), true).toBool (); settings.endGroup (); } QString Settings::binaryFile() const { return binaryFile_; } void Settings::setBinaryFile(const QString &binaryFile) { binaryFile_ = binaryFile; } bool Settings::checkOnBuild() const { return checkOnBuild_; } void Settings::setCheckOnBuild(bool checkOnBuild) { checkOnBuild_ = checkOnBuild; } bool Settings::checkInconclusive() const { return checkInconclusive_; } void Settings::setCheckInconclusive(bool checkInconclusive) { checkInconclusive_ = checkInconclusive; } QString Settings::customParameters() const { return customParameters_; } void Settings::setCustomParameters(const QString &customParameters) { customParameters_ = customParameters; } bool Settings::showBinaryOutput() const { return showBinaryOutput_; } void Settings::setShowBinaryOutput(bool showBinaryOutput) { showBinaryOutput_ = showBinaryOutput; } bool Settings::showId() const { return showId_; } void Settings::setShowId(bool showId) { showId_ = showId; } bool Settings::popupOnError() const { return popupOnError_; } void Settings::setPopupOnError(bool popupOnError) { popupOnError_ = popupOnError; } bool Settings::popupOnWarning() const { return popupOnWarning_; } void Settings::setPopupOnWarning(bool popupOnWarning) { popupOnWarning_ = popupOnWarning; } QStringList Settings::ignorePatterns() const { return ignorePatterns_; } void Settings::setIgnorePatterns(const QStringList &ignorePatterns) { ignorePatterns_ = ignorePatterns; for (auto& i: ignorePatterns_) { i = i.trimmed () ; } } bool Settings::checkOnProjectChange() const { return checkOnProjectChange_; } void Settings::setCheckOnProjectChange(bool checkOnProjectChange) { checkOnProjectChange_ = checkOnProjectChange; } bool Settings::checkOnFileAdd() const { return checkOnFileAdd_; } void Settings::setCheckOnFileAdd(bool checkOnFileAdd) { checkOnFileAdd_ = checkOnFileAdd; } bool Settings::checkUnused() const { return checkUnused_; } void Settings::setCheckUnused(bool checkUnused) { checkUnused_ = checkUnused; } bool Settings::checkOnSave() const { return checkOnSave_; } void Settings::setCheckOnSave(bool checkOnSave) { checkOnSave_ = checkOnSave; } <commit_msg>Auto-detect cppcheck in default installation paths<commit_after>#include <QString> #include <utils/hostosinfo.h> #include <utils/fileutils.h> #include <coreplugin/icore.h> #include "Settings.h" #include "Constants.h" using namespace QtcCppcheck::Constants; using namespace QtcCppcheck::Internal; Settings::Settings(bool autoLoad) : checkOnBuild_ (false), checkOnSave_ (false), checkOnProjectChange_ (false), checkOnFileAdd_ (false), checkUnused_ (false), checkInconclusive_ (false), showBinaryOutput_ (false), showId_ (false), popupOnError_ (false), popupOnWarning_ (false) { if (autoLoad) { load (); } } void Settings::save() { Q_ASSERT (Core::ICore::settings () != NULL); QSettings& settings = *(Core::ICore::settings ()); settings.beginGroup (QLatin1String (SETTINGS_GROUP)); settings.setValue (QLatin1String (SETTINGS_BINARY_FILE), binaryFile_); settings.setValue (QLatin1String (SETTINGS_CHECK_ON_BUILD), checkOnBuild_); settings.setValue (QLatin1String (SETTINGS_CHECK_ON_SAVE), checkOnSave_); settings.setValue (QLatin1String (SETTINGS_CHECK_ON_PROJECT_CHANGE), checkOnProjectChange_); settings.setValue (QLatin1String (SETTINGS_CHECK_ON_FILE_ADD), checkOnFileAdd_); settings.setValue (QLatin1String (SETTINGS_CHECK_UNUSED), checkUnused_); settings.setValue (QLatin1String (SETTINGS_CHECK_INCONCLUSIVE), checkInconclusive_); settings.setValue (QLatin1String (SETTINGS_CUSTOM_PARAMS), customParameters_); settings.setValue (QLatin1String (SETTINGS_IGNORE_PATTERNS), ignorePatterns_.join (",")); settings.setValue (QLatin1String (SETTINGS_SHOW_OUTPUT), showBinaryOutput_); settings.setValue (QLatin1String (SETTINGS_SHOW_ID), showId_); settings.setValue (QLatin1String (SETTINGS_POPUP_ON_ERROR), popupOnError_); settings.setValue (QLatin1String (SETTINGS_POPUP_ON_WARNING), popupOnWarning_); settings.endGroup (); } static QString defaultBinary() { QString res; if (Utils::HostOsInfo::isWindowsHost()) { res = Utils::FileName::fromUserInput(QLatin1String(qgetenv("ProgramFiles"))) .appendPath("Cppcheck/cppcheck.exe").toString(); } else { res = "/usr/bin/cppcheck"; } return QFile::exists(res) ? res : QString(); } void Settings::load() { Q_ASSERT (Core::ICore::settings () != NULL); QSettings& settings = *(Core::ICore::settings ()); settings.beginGroup (QLatin1String (SETTINGS_GROUP)); binaryFile_ = settings.value (QLatin1String (SETTINGS_BINARY_FILE), QString ()).toString (); checkOnBuild_ = settings.value (QLatin1String (SETTINGS_CHECK_ON_BUILD), false).toBool (); checkOnSave_ = settings.value (QLatin1String (SETTINGS_CHECK_ON_SAVE), false).toBool (); checkOnProjectChange_ = settings.value (QLatin1String (SETTINGS_CHECK_ON_PROJECT_CHANGE), false).toBool (); checkOnFileAdd_ = settings.value (QLatin1String (SETTINGS_CHECK_ON_FILE_ADD), false).toBool (); checkUnused_ = settings.value (QLatin1String (SETTINGS_CHECK_UNUSED), false).toBool (); checkInconclusive_ = settings.value (QLatin1String (SETTINGS_CHECK_INCONCLUSIVE), false).toBool (); customParameters_ = settings.value (QLatin1String (SETTINGS_CUSTOM_PARAMS), QString ()).toString (); ignorePatterns_ = settings.value (QLatin1String (SETTINGS_IGNORE_PATTERNS), QString ()).toString ().split (",", QString::SkipEmptyParts); showBinaryOutput_ = settings.value (QLatin1String (SETTINGS_SHOW_OUTPUT), false).toBool (); showId_ = settings.value (QLatin1String (SETTINGS_SHOW_ID), false).toBool (); popupOnError_ = settings.value (QLatin1String (SETTINGS_POPUP_ON_ERROR), true).toBool (); popupOnWarning_ = settings.value (QLatin1String (SETTINGS_POPUP_ON_WARNING), true).toBool (); settings.endGroup (); if (binaryFile_.isEmpty()) binaryFile_ = defaultBinary(); } QString Settings::binaryFile() const { return binaryFile_; } void Settings::setBinaryFile(const QString &binaryFile) { binaryFile_ = binaryFile; } bool Settings::checkOnBuild() const { return checkOnBuild_; } void Settings::setCheckOnBuild(bool checkOnBuild) { checkOnBuild_ = checkOnBuild; } bool Settings::checkInconclusive() const { return checkInconclusive_; } void Settings::setCheckInconclusive(bool checkInconclusive) { checkInconclusive_ = checkInconclusive; } QString Settings::customParameters() const { return customParameters_; } void Settings::setCustomParameters(const QString &customParameters) { customParameters_ = customParameters; } bool Settings::showBinaryOutput() const { return showBinaryOutput_; } void Settings::setShowBinaryOutput(bool showBinaryOutput) { showBinaryOutput_ = showBinaryOutput; } bool Settings::showId() const { return showId_; } void Settings::setShowId(bool showId) { showId_ = showId; } bool Settings::popupOnError() const { return popupOnError_; } void Settings::setPopupOnError(bool popupOnError) { popupOnError_ = popupOnError; } bool Settings::popupOnWarning() const { return popupOnWarning_; } void Settings::setPopupOnWarning(bool popupOnWarning) { popupOnWarning_ = popupOnWarning; } QStringList Settings::ignorePatterns() const { return ignorePatterns_; } void Settings::setIgnorePatterns(const QStringList &ignorePatterns) { ignorePatterns_ = ignorePatterns; for (auto& i: ignorePatterns_) { i = i.trimmed () ; } } bool Settings::checkOnProjectChange() const { return checkOnProjectChange_; } void Settings::setCheckOnProjectChange(bool checkOnProjectChange) { checkOnProjectChange_ = checkOnProjectChange; } bool Settings::checkOnFileAdd() const { return checkOnFileAdd_; } void Settings::setCheckOnFileAdd(bool checkOnFileAdd) { checkOnFileAdd_ = checkOnFileAdd; } bool Settings::checkUnused() const { return checkUnused_; } void Settings::setCheckUnused(bool checkUnused) { checkUnused_ = checkUnused; } bool Settings::checkOnSave() const { return checkOnSave_; } void Settings::setCheckOnSave(bool checkOnSave) { checkOnSave_ = checkOnSave; } <|endoftext|>
<commit_before>// // This file contains the class InputDialog. // An InputDialog object prompts for an input string using a simple // dialog box. The InputDialog class is also a good example of how // to use the ROOT GUI classes via the interpreter. Since interpreted // classes can not call virtual functions via base class pointers, all // GUI objects are used by composition instead of by inheritance. // // This file contains also some utility functions that use // the InputDialog class to either get a string, integer or // floating point number. There are also two functions showing // how to use the file open and save dialogs. The utility functions are: // // const char *OpenFileDialog() // const char *SaveFileDialog() // const char *GetStringDialog(const char *prompt, const char *defval) // Int_t GetIntegerDialog(const char *prompt, Int_t defval) // Float_t GetFloatDialog(const char *prompt, Float_t defval) // // To use the InputDialog class and the utility functions you just // have to load the Dialogs.C file as follows: // .L Dialogs.C // // Now you can use them like: // { // const char *file = OpenFileDialog(); // Int_t run = GetIntegerDialog("Give run number:", 0); // Int_t event = GetIntegerDialog("Give event number:", 0); // printf("analyse run %d, event %d from file %s\n", run ,event, file); // } // /////////////////////////////////////////////////////////////////////////// // // // Input Dialog Widget // // // /////////////////////////////////////////////////////////////////////////// class InputDialog { private: TGTransientFrame *fDialog; // transient frame, main dialog window TGTextEntry *fTE; // text entry widget containing TList *fWidgets; // keep track of widgets to be deleted in dtor char *fRetStr; // address to store return string public: InputDialog(const char *prompt, const char *defval, char *retstr); ~InputDialog(); void ProcessMessage(Long_t msg, Long_t parm1, Long_t parm2); }; InputDialog::~InputDialog() { // Cleanup dialog. fWidgets->Delete(); delete fWidgets; delete fTE; delete fDialog; } InputDialog::InputDialog(const char *prompt, const char *defval, char *retstr) { // Create simple input dialog. fWidgets = new TList; TGWindow *main = gClient->GetRoot(); fDialog = new TGTransientFrame(main, main, 10, 10); // command to be executed by buttons and text entry widget char cmd[128]; sprintf(cmd, "{long r__ptr=0x%lx; ((InputDialog*)r__ptr)->ProcessMessage($MSG,$PARM1,$PARM2);}", (Long_t)this); // create prompt label and textentry widget TGLabel *label = new TGLabel(fDialog, prompt); fWidgets->Add(label); TGTextBuffer *tbuf = new TGTextBuffer(256); //will be deleted by TGtextEntry tbuf->AddText(0, defval); fTE = new TGTextEntry(fDialog, tbuf); fTE->Resize(260, fTE->GetDefaultHeight()); fTE->SetCommand(cmd); TGLayoutHints *l1 = new TGLayoutHints(kLHintsTop | kLHintsLeft, 5, 5, 5, 0); TGLayoutHints *l2 = new TGLayoutHints(kLHintsTop | kLHintsLeft, 5, 5, 5, 5); fWidgets->Add(l1); fWidgets->Add(l2); fDialog->AddFrame(label, l1); fDialog->AddFrame(fTE, l2); // create frame and layout hints for Ok and Cancel buttons TGHorizontalFrame *hf = new TGHorizontalFrame(fDialog, 60, 20, kFixedWidth); TGLayoutHints *l3 = new TGLayoutHints(kLHintsCenterY | kLHintsExpandX, 5, 5, 0, 0); // put hf as last in list to be deleted fWidgets->Add(l3); // create OK and Cancel buttons in their own frame (hf) UInt_t nb = 0, width = 0, height = 0; TGTextButton *b; b = new TGTextButton(hf, "&Ok", cmd, 1); fWidgets->Add(b); b->Associate(fDialog); hf->AddFrame(b, l3); height = b->GetDefaultHeight(); width = TMath::Max(width, b->GetDefaultWidth()); ++nb; b = new TGTextButton(hf, "&Cancel", cmd, 2); fWidgets->Add(b); b->Associate(fDialog); hf->AddFrame(b, l3); height = b->GetDefaultHeight(); width = TMath::Max(width, b->GetDefaultWidth()); ++nb; // place button frame (hf) at the bottom TGLayoutHints *l4 = new TGLayoutHints(kLHintsBottom | kLHintsCenterX, 0, 0, 5, 5); fWidgets->Add(l4); fWidgets->Add(hf); fDialog->AddFrame(hf, l4); // keep buttons centered and with the same width hf->Resize((width + 20) * nb, height); // set dialog title fDialog->SetWindowName("Get Input"); // map all widgets and calculate size of dialog fDialog->MapSubwindows(); width = fDialog->GetDefaultWidth(); height = fDialog->GetDefaultHeight(); fDialog->Resize(width, height); // position relative to the parent window (which is the root window) Window_t wdum; int ax, ay; gVirtualX->TranslateCoordinates(main->GetId(), main->GetId(), (((TGFrame *) main)->GetWidth() - width) >> 1, (((TGFrame *) main)->GetHeight() - height) >> 1, ax, ay, wdum); fDialog->Move(ax, ay); fDialog->SetWMPosition(ax, ay); // make the message box non-resizable fDialog->SetWMSize(width, height); fDialog->SetWMSizeHints(width, height, width, height, 0, 0); fDialog->SetMWMHints(kMWMDecorAll | kMWMDecorResizeH | kMWMDecorMaximize | kMWMDecorMinimize | kMWMDecorMenu, kMWMFuncAll | kMWMFuncResize | kMWMFuncMaximize | kMWMFuncMinimize, kMWMInputModeless); // popup dialog and wait till user replies fDialog->MapWindow(); fRetStr = retstr; gClient->WaitFor(fDialog); } void InputDialog::ProcessMessage(Long_t msg, Long_t parm1, Long_t parm2) { // Handle button and text enter events switch (GET_MSG(msg)) { case kC_COMMAND: switch (GET_SUBMSG(msg)) { case kCM_BUTTON: switch (parm1) { case 1: // here copy the string from text buffer to return variable strcpy(fRetStr, fTE->GetBuffer()->GetString()); delete this; break; case 2: fRetStr[0] = 0; delete this; break; } default: break; } break; case kC_TEXTENTRY: switch (GET_SUBMSG(msg)) { case kTE_ENTER: // here copy the string from text buffer to return variable strcpy(fRetStr, fTE->GetBuffer()->GetString()); delete this; break; default: break; } break; default: break; } } //--- Utility Functions -------------------------------------------------------- const char *OpenFileDialog() { // Prompt for file to be opened. Depending on navigation in // dialog the current working directory can be changed. // The returned file name is always with respect to the // current directory. const char *gOpenAsTypes[] = { "Macro files", "*.C", "ROOT files", "*.root", "PostScript", "*.ps", "Encapsulated PostScript", "*.eps", "Gif files", "*.gif", "All files", "*", 0, 0 }; static TGFileInfo fi; fi.fFileTypes = gOpenAsTypes; new TGFileDialog(gClient->GetRoot(), gClient->GetRoot(), kFDOpen, &fi); return fi.fFilename; } const char *SaveFileDialog() { // Prompt for file to be saved. Depending on navigation in // dialog the current working directory can be changed. // The returned file name is always with respect to the // current directory. const char *gSaveAsTypes[] = { "Macro files", "*.C", "ROOT files", "*.root", "PostScript", "*.ps", "Encapsulated PostScript", "*.eps", "Gif files", "*.gif", "All files", "*", 0, 0 }; static TGFileInfo fi; fi.fFileTypes = gSaveAsTypes; new TGFileDialog(gClient->GetRoot(), gClient->GetRoot(), kFDSave, &fi); return fi.fFilename; } const char *GetStringDialog(const char *prompt, const char *defval) { // Prompt for string. The typed in string is returned. static char answer[128]; new InputDialog(prompt, defval, answer); return answer; } Int_t GetIntegerDialog(const char *prompt, Int_t defval) { // Prompt for integer. The typed in integer is returned. static char answer[32]; char defv[32]; sprintf(defv, "%d", defval); new InputDialog(prompt, defv, answer); return atoi(answer); } Float_t GetFloatDialog(const char *prompt, Float_t defval) { // Prompt for float. The typed in float is returned. static char answer[32]; char defv[32]; sprintf(defv, "%f", defval); new InputDialog(prompt, defv, answer); return atof(answer); } <commit_msg>Fix Jira #ROOT-8404 macro Dialogs.C does not compile and crashes<commit_after>// // This file contains the class InputDialog. // An InputDialog object prompts for an input string using a simple // dialog box. The InputDialog class is also a good example of how // to use the ROOT GUI classes via the interpreter. Since interpreted // classes can not call virtual functions via base class pointers, all // GUI objects are used by composition instead of by inheritance. // // This file contains also some utility functions that use // the InputDialog class to either get a string, integer or // floating point number. There are also two functions showing // how to use the file open and save dialogs. The utility functions are: // // const char *OpenFileDialog() // const char *SaveFileDialog() // const char *GetStringDialog(const char *prompt, const char *defval) // Int_t GetIntegerDialog(const char *prompt, Int_t defval) // Float_t GetFloatDialog(const char *prompt, Float_t defval) // // To use the InputDialog class and the utility functions you just // have to load the Dialogs.C file as follows: // .L Dialogs.C // // Now you can use them like: // { // const char *file = OpenFileDialog(); // Int_t run = GetIntegerDialog("Give run number:", 0); // Int_t event = GetIntegerDialog("Give event number:", 0); // printf("analyse run %d, event %d from file %s\n", run ,event, file); // } // #include "TList.h" #include "TGLabel.h" #include "TGButton.h" #include "TGText.h" #include "TGFileDialog.h" #include "TGTextEntry.h" /////////////////////////////////////////////////////////////////////////// // // // Input Dialog Widget // // // /////////////////////////////////////////////////////////////////////////// class InputDialog { private: TGTransientFrame *fDialog; // transient frame, main dialog window TGTextEntry *fTE; // text entry widget containing char *fRetStr; // address to store return string public: InputDialog(const char *prompt, const char *defval, char *retstr); ~InputDialog(); void ProcessMessage(Long_t msg, Long_t parm1, Long_t parm2); }; InputDialog::~InputDialog() { // Cleanup dialog. fDialog->DeleteWindow(); // cleanup and delete fDialog } InputDialog::InputDialog(const char *prompt, const char *defval, char *retstr) { // Create simple input dialog. const TGWindow *main = gClient->GetRoot(); fDialog = new TGTransientFrame(main, main, 10, 10); fDialog->SetCleanup(kDeepCleanup); // command to be executed by buttons and text entry widget char cmd[128]; sprintf(cmd, "{long r__ptr=0x%lx; ((InputDialog*)r__ptr)->ProcessMessage($MSG,$PARM1,$PARM2);}", (Long_t)this); // create prompt label and textentry widget TGLabel *label = new TGLabel(fDialog, prompt); TGTextBuffer *tbuf = new TGTextBuffer(256); //will be deleted by TGtextEntry tbuf->AddText(0, defval); fTE = new TGTextEntry(fDialog, tbuf); fTE->Resize(260, fTE->GetDefaultHeight()); fTE->SetCommand(cmd); TGLayoutHints *l1 = new TGLayoutHints(kLHintsTop | kLHintsLeft, 5, 5, 5, 0); TGLayoutHints *l2 = new TGLayoutHints(kLHintsTop | kLHintsLeft, 5, 5, 5, 5); fDialog->AddFrame(label, l1); fDialog->AddFrame(fTE, l2); // create frame and layout hints for Ok and Cancel buttons TGHorizontalFrame *hf = new TGHorizontalFrame(fDialog, 60, 20, kFixedWidth); TGLayoutHints *l3 = new TGLayoutHints(kLHintsCenterY | kLHintsExpandX, 5, 5, 0, 0); // create OK and Cancel buttons in their own frame (hf) UInt_t nb = 0, width = 0, height = 0; TGTextButton *b; b = new TGTextButton(hf, "&Ok", cmd, 1); b->Associate(fDialog); hf->AddFrame(b, l3); height = b->GetDefaultHeight(); width = TMath::Max(width, b->GetDefaultWidth()); ++nb; b = new TGTextButton(hf, "&Cancel", cmd, 2); b->Associate(fDialog); hf->AddFrame(b, l3); height = b->GetDefaultHeight(); width = TMath::Max(width, b->GetDefaultWidth()); ++nb; // place button frame (hf) at the bottom TGLayoutHints *l4 = new TGLayoutHints(kLHintsBottom | kLHintsCenterX, 0, 0, 5, 5); fDialog->AddFrame(hf, l4); // keep buttons centered and with the same width hf->Resize((width + 20) * nb, height); // set dialog title fDialog->SetWindowName("Get Input"); // map all widgets and calculate size of dialog fDialog->MapSubwindows(); width = fDialog->GetDefaultWidth(); height = fDialog->GetDefaultHeight(); fDialog->Resize(width, height); // position relative to the parent window (which is the root window) Window_t wdum; int ax, ay; gVirtualX->TranslateCoordinates(main->GetId(), main->GetId(), (((TGFrame *) main)->GetWidth() - width) >> 1, (((TGFrame *) main)->GetHeight() - height) >> 1, ax, ay, wdum); fDialog->Move(ax, ay); fDialog->SetWMPosition(ax, ay); // make the message box non-resizable fDialog->SetWMSize(width, height); fDialog->SetWMSizeHints(width, height, width, height, 0, 0); fDialog->SetMWMHints(kMWMDecorAll | kMWMDecorResizeH | kMWMDecorMaximize | kMWMDecorMinimize | kMWMDecorMenu, kMWMFuncAll | kMWMFuncResize | kMWMFuncMaximize | kMWMFuncMinimize, kMWMInputModeless); // popup dialog and wait till user replies fDialog->MapWindow(); fRetStr = retstr; gClient->WaitFor(fDialog); } void InputDialog::ProcessMessage(Long_t msg, Long_t parm1, Long_t parm2) { // Handle button and text enter events switch (GET_MSG(msg)) { case kC_COMMAND: switch (GET_SUBMSG(msg)) { case kCM_BUTTON: switch (parm1) { case 1: // here copy the string from text buffer to return variable strcpy(fRetStr, fTE->GetBuffer()->GetString()); delete this; break; case 2: fRetStr[0] = 0; delete this; break; } default: break; } break; case kC_TEXTENTRY: switch (GET_SUBMSG(msg)) { case kTE_ENTER: // here copy the string from text buffer to return variable strcpy(fRetStr, fTE->GetBuffer()->GetString()); delete this; break; default: break; } break; default: break; } } //--- Utility Functions -------------------------------------------------------- const char *OpenFileDialog() { // Prompt for file to be opened. Depending on navigation in // dialog the current working directory can be changed. // The returned file name is always with respect to the // current directory. const char *gOpenAsTypes[] = { "Macro files", "*.C", "ROOT files", "*.root", "PostScript", "*.ps", "Encapsulated PostScript", "*.eps", "Gif files", "*.gif", "All files", "*", 0, 0 }; static TGFileInfo fi; fi.fFileTypes = gOpenAsTypes; new TGFileDialog(gClient->GetRoot(), gClient->GetRoot(), kFDOpen, &fi); return fi.fFilename; } const char *SaveFileDialog() { // Prompt for file to be saved. Depending on navigation in // dialog the current working directory can be changed. // The returned file name is always with respect to the // current directory. const char *gSaveAsTypes[] = { "Macro files", "*.C", "ROOT files", "*.root", "PostScript", "*.ps", "Encapsulated PostScript", "*.eps", "Gif files", "*.gif", "All files", "*", 0, 0 }; static TGFileInfo fi; fi.fFileTypes = gSaveAsTypes; new TGFileDialog(gClient->GetRoot(), gClient->GetRoot(), kFDSave, &fi); return fi.fFilename; } const char *GetStringDialog(const char *prompt, const char *defval) { // Prompt for string. The typed in string is returned. static char answer[128]; new InputDialog(prompt, defval, answer); return answer; } Int_t GetIntegerDialog(const char *prompt, Int_t defval) { // Prompt for integer. The typed in integer is returned. static char answer[32]; char defv[32]; sprintf(defv, "%d", defval); new InputDialog(prompt, defv, answer); return atoi(answer); } Float_t GetFloatDialog(const char *prompt, Float_t defval) { // Prompt for float. The typed in float is returned. static char answer[32]; char defv[32]; sprintf(defv, "%f", defval); new InputDialog(prompt, defv, answer); return atof(answer); } <|endoftext|>
<commit_before>/// @file /// @copyright The code is licensed under the BSD License /// <http://opensource.org/licenses/BSD-2-Clause>, /// Copyright (c) 2013-2015 Alexandre Hamez. /// @author Alexandre Hamez #include <map> #include <string> #include <utility> #include <boost/algorithm/string/join.hpp> #include <boost/range/adaptor/map.hpp> #include "support/conf/options.hh" #include "support/conf/pn_format.hh" #include "support/util/paths.hh" namespace pnmc { namespace conf { namespace po = boost::program_options; /*------------------------------------------------------------------------------------------------*/ static const auto pn_input_str = "input"; static const auto format_map = std::map<std::string, pn_format> { std::make_pair("ndr" , pn_format::ndr) , std::make_pair("net" , pn_format::net) , std::make_pair("nupn", pn_format::nupn) , std::make_pair("pnml", pn_format::pnml) }; static const auto possible_format_values = [] { using namespace boost::adaptors; return "Petri net format [" + boost::algorithm::join(format_map | map_keys, "|") + "]"; }(); /*------------------------------------------------------------------------------------------------*/ po::options_description pn_input_options() { po::options_description options{"Petri net file format options"}; options.add_options() (pn_input_str, po::value<std::string>()->default_value("net"), possible_format_values.c_str()); return options; } /*------------------------------------------------------------------------------------------------*/ static pn_format pn_format_from_options(const po::variables_map& vm) { const auto s = vm[pn_input_str].as<std::string>(); const auto search = format_map.find(s); if (search != end(format_map)) { return search->second; } else { throw po::error("Invalid input format " + s); } } /*------------------------------------------------------------------------------------------------*/ parsers::pn_configuration configure_pn_parser(const boost::program_options::variables_map& vm) { parsers::pn_configuration conf; if (vm["input-file"].as<std::string>() != "-") { conf.file = util::in_file(vm["input-file"].as<std::string>()); } conf.file_type = pn_format_from_options(vm); return conf; } /*------------------------------------------------------------------------------------------------*/ /*------------------------------------------------------------------------------------------------*/ static const auto properties_input_str = "properties-file"; po::options_description properties_input_options() { po::options_description options{"Properties file format options"}; options.add_options() (properties_input_str, po::value<std::string>(), "Path to properties file"); return options; } /*------------------------------------------------------------------------------------------------*/ parsers::properties_configuration configure_properties_parser(const boost::program_options::variables_map& vm) { parsers::properties_configuration conf; if (vm.count(properties_input_str)) { conf.file = util::in_file(vm[properties_input_str].as<std::string>()); } return conf; } /*------------------------------------------------------------------------------------------------*/ }} // namespace pnmc::conf <commit_msg>Change --input to --format<commit_after>/// @file /// @copyright The code is licensed under the BSD License /// <http://opensource.org/licenses/BSD-2-Clause>, /// Copyright (c) 2013-2015 Alexandre Hamez. /// @author Alexandre Hamez #include <map> #include <string> #include <utility> #include <boost/algorithm/string/join.hpp> #include <boost/range/adaptor/map.hpp> #include "support/conf/options.hh" #include "support/conf/pn_format.hh" #include "support/util/paths.hh" namespace pnmc { namespace conf { namespace po = boost::program_options; /*------------------------------------------------------------------------------------------------*/ static const auto pn_format_str = "format"; static const auto format_map = std::map<std::string, pn_format> { std::make_pair("ndr" , pn_format::ndr) , std::make_pair("net" , pn_format::net) , std::make_pair("nupn", pn_format::nupn) , std::make_pair("pnml", pn_format::pnml) }; static const auto possible_format_values = [] { using namespace boost::adaptors; return "Petri net format [" + boost::algorithm::join(format_map | map_keys, "|") + "]"; }(); /*------------------------------------------------------------------------------------------------*/ po::options_description pn_input_options() { po::options_description options{"Petri net file format options"}; options.add_options() (pn_format_str, po::value<std::string>()->default_value("net"), possible_format_values.c_str()); return options; } /*------------------------------------------------------------------------------------------------*/ static pn_format pn_format_from_options(const po::variables_map& vm) { const auto s = vm[pn_format_str].as<std::string>(); const auto search = format_map.find(s); if (search != end(format_map)) { return search->second; } else { throw po::error("Invalid input format " + s); } } /*------------------------------------------------------------------------------------------------*/ parsers::pn_configuration configure_pn_parser(const boost::program_options::variables_map& vm) { parsers::pn_configuration conf; if (vm["input-file"].as<std::string>() != "-") { conf.file = util::in_file(vm["input-file"].as<std::string>()); } conf.file_type = pn_format_from_options(vm); return conf; } /*------------------------------------------------------------------------------------------------*/ /*------------------------------------------------------------------------------------------------*/ static const auto properties_input_str = "properties-file"; po::options_description properties_input_options() { po::options_description options{"Properties file format options"}; options.add_options() (properties_input_str, po::value<std::string>(), "Path to properties file"); return options; } /*------------------------------------------------------------------------------------------------*/ parsers::properties_configuration configure_properties_parser(const boost::program_options::variables_map& vm) { parsers::properties_configuration conf; if (vm.count(properties_input_str)) { conf.file = util::in_file(vm[properties_input_str].as<std::string>()); } return conf; } /*------------------------------------------------------------------------------------------------*/ }} // namespace pnmc::conf <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: charmap.hxx,v $ * * $Revision: 1.2 $ * * last change: $Author: vg $ $Date: 2007-04-11 15:40:07 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _SVX_CHARMAP_HXX #define _SVX_CHARMAP_HXX // include --------------------------------------------------------------- #ifndef _SV_CTRL_HXX #include <vcl/ctrl.hxx> #endif #ifndef _SV_METRIC_HXX #include <vcl/metric.hxx> #endif #ifndef _SV_SCRBAR_HXX #include <vcl/scrbar.hxx> #endif #ifndef _BASEDLGS_HXX #include <sfx2/basedlgs.hxx> #endif #include <map> #ifndef _SHL_HXX #include <tools/shl.hxx> //add CHINA001 #endif #ifndef _TOOLS_DEBUG_HXX #include <tools/debug.hxx> //add CHINA001 #endif #ifndef _SV_SOUND_HXX #include <vcl/sound.hxx> //add CHINA001 #endif #ifndef _SV_SVAPP_HXX #include <vcl/svapp.hxx> //add CHINA001 #endif #ifndef _SV_BUTTON_HXX #include <vcl/button.hxx> //add CHINA001 #endif #ifndef _SV_FIXED_HXX #include <vcl/fixed.hxx> //add CHINA001 #endif #ifndef _SV_LSTBOX_HXX #include <vcl/lstbox.hxx> //add CHINA001 #endif #ifndef _SV_EDIT_HXX #include <vcl/edit.hxx> //add CHINA001 #endif #ifndef _SV_METRIC_HXX #include <vcl/metric.hxx> #endif #ifndef INCLUDED_SVXDLLAPI_H #include "svx/svxdllapi.h" #endif class SubsetMap; class SvxCharMapData; // define ---------------------------------------------------------------- #ifdef MAC #define CHARMAP_MAXLEN 28 #define COLUMN_COUNT 28 #define ROW_COUNT 8 #else #define CHARMAP_MAXLEN 32 #define COLUMN_COUNT 16 #define ROW_COUNT 8 #endif namespace svx { struct SvxShowCharSetItem; class SvxShowCharSetVirtualAcc; } // class SvxShowCharSet -------------------------------------------------- class SVX_DLLPUBLIC SvxShowCharSet : public Control { public: SvxShowCharSet( Window* pParent, const ResId& rResId ); ~SvxShowCharSet(); void SetFont( const Font& rFont ); void SelectCharacter( sal_uInt32 cNew, BOOL bFocus = FALSE ); sal_UCS4 GetSelectCharacter() const; Link GetDoubleClickHdl() const { return aDoubleClkHdl; } void SetDoubleClickHdl( const Link& rLink ) { aDoubleClkHdl = rLink; } Link GetSelectHdl() const { return aSelectHdl; } void SetSelectHdl( const Link& rHdl ) { aSelectHdl = rHdl; } Link GetHighlightHdl() const { return aHighHdl; } void SetHighlightHdl( const Link& rHdl ) { aHighHdl = rHdl; } Link GetPreSelectHdl() const { return aHighHdl; } void SetPreSelectHdl( const Link& rHdl ) { aPreSelectHdl = rHdl; } #ifdef _SVX_CHARMAP_CXX_ ::svx::SvxShowCharSetItem* ImplGetItem( int _nPos ); int FirstInView( void) const; int LastInView( void) const; int PixelToMapIndex( const Point&) const; void SelectIndex( int index, BOOL bFocus = FALSE ); void DeSelect(); inline sal_Bool IsSelected(USHORT _nPos) const { return _nPos == nSelectedIndex; } inline USHORT GetSelectIndexId() const { return sal::static_int_cast<USHORT>(nSelectedIndex); } USHORT GetRowPos(USHORT _nPos) const; USHORT GetColumnPos(USHORT _nPos) const; void ImplFireAccessibleEvent( short nEventId, const ::com::sun::star::uno::Any& rOldValue, const ::com::sun::star::uno::Any& rNewValue ); ScrollBar* getScrollBar(); void ReleaseAccessible(); sal_Int32 getMaxCharCount() const; #endif // _SVX_CHARMAP_CXX_ protected: virtual void Paint( const Rectangle& ); virtual void MouseButtonDown( const MouseEvent& rMEvt ); virtual void MouseButtonUp( const MouseEvent& rMEvt ); virtual void MouseMove( const MouseEvent& rMEvt ); virtual void Command( const CommandEvent& rCEvt ); virtual void KeyInput( const KeyEvent& rKEvt ); virtual void GetFocus(); virtual void LoseFocus(); virtual void StateChanged( StateChangedType nStateChange ); virtual void DataChanged( const DataChangedEvent& rDCEvt ); virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible > CreateAccessible(); private: typedef ::std::map<sal_Int32, ::svx::SvxShowCharSetItem*> ItemsMap; ItemsMap m_aItems; Link aDoubleClkHdl; Link aSelectHdl; Link aHighHdl; Link aPreSelectHdl; ::svx::SvxShowCharSetVirtualAcc* m_pAccessible; ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible > m_xAccessible; long nX; long nY; BOOL bDrag; sal_Int32 nSelectedIndex; FontCharMap maFontCharMap; ScrollBar aVscrollSB; Size aOrigSize; Point aOrigPos; private: void DrawChars_Impl( int n1, int n2); void InitSettings( BOOL bForeground, BOOL bBackground); // abstraction layers are: Unicode<->MapIndex<->Pixel Point MapIndexToPixel( int) const; //#if 0 // _SOLAR__PRIVATE DECL_LINK( VscrollHdl, ScrollBar* ); //#endif }; // class SvxShowText ===================================================== class SVX_DLLPUBLIC SvxShowText : public Control { public: SvxShowText( Window* pParent, const ResId& rResId, BOOL bCenter = FALSE ); ~SvxShowText(); void SetFont( const Font& rFont ); void SetText( const String& rText ); protected: virtual void Paint( const Rectangle& ); private: long mnY; BOOL mbCenter; }; class SVX_DLLPUBLIC SvxCharMapData { public: SvxCharMapData( class SfxModalDialog* pDialog, BOOL bOne_ ); void SetCharFont( const Font& rFont ); private: friend class SvxCharacterMap; SfxModalDialog* mpDialog; SvxShowCharSet aShowSet; // Edit aShowText; SvxShowText aShowText; OKButton aOKBtn; CancelButton aCancelBtn; HelpButton aHelpBtn; PushButton aDeleteBtn; FixedText aFontText; ListBox aFontLB; FixedText aSubsetText; ListBox aSubsetLB; FixedText aSymbolText; SvxShowText aShowChar; FixedText aCharCodeText; Font aFont; BOOL bOne; const SubsetMap* pSubsetMap; DECL_LINK( OKHdl, OKButton* ); DECL_LINK( FontSelectHdl, ListBox* ); DECL_LINK( SubsetSelectHdl, ListBox* ); DECL_LINK( CharDoubleClickHdl, Control* pControl ); DECL_LINK( CharSelectHdl, Control* pControl ); DECL_LINK( CharHighlightHdl, Control* pControl ); DECL_LINK( CharPreSelectHdl, Control* pControl ); DECL_LINK( DeleteHdl, PushButton* pBtn ); }; #endif <commit_msg>INTEGRATION: CWS vcl78 (1.2.56); FILE MERGED 2007/05/07 17:48:27 pl 1.2.56.1: #i76832# fix special character dialog<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: charmap.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: obo $ $Date: 2007-06-11 14:23:07 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _SVX_CHARMAP_HXX #define _SVX_CHARMAP_HXX // include --------------------------------------------------------------- #ifndef _SV_CTRL_HXX #include <vcl/ctrl.hxx> #endif #ifndef _SV_METRIC_HXX #include <vcl/metric.hxx> #endif #ifndef _SV_SCRBAR_HXX #include <vcl/scrbar.hxx> #endif #ifndef _BASEDLGS_HXX #include <sfx2/basedlgs.hxx> #endif #include <map> #ifndef _SHL_HXX #include <tools/shl.hxx> //add CHINA001 #endif #ifndef _TOOLS_DEBUG_HXX #include <tools/debug.hxx> //add CHINA001 #endif #ifndef _SV_SOUND_HXX #include <vcl/sound.hxx> //add CHINA001 #endif #ifndef _SV_SVAPP_HXX #include <vcl/svapp.hxx> //add CHINA001 #endif #ifndef _SV_BUTTON_HXX #include <vcl/button.hxx> //add CHINA001 #endif #ifndef _SV_FIXED_HXX #include <vcl/fixed.hxx> //add CHINA001 #endif #ifndef _SV_LSTBOX_HXX #include <vcl/lstbox.hxx> //add CHINA001 #endif #ifndef _SV_EDIT_HXX #include <vcl/edit.hxx> //add CHINA001 #endif #ifndef _SV_METRIC_HXX #include <vcl/metric.hxx> #endif #ifndef INCLUDED_SVXDLLAPI_H #include "svx/svxdllapi.h" #endif class SubsetMap; class SvxCharMapData; // define ---------------------------------------------------------------- #ifdef MAC #define CHARMAP_MAXLEN 28 #define COLUMN_COUNT 28 #define ROW_COUNT 8 #else #define CHARMAP_MAXLEN 32 #define COLUMN_COUNT 16 #define ROW_COUNT 8 #endif namespace svx { struct SvxShowCharSetItem; class SvxShowCharSetVirtualAcc; } // class SvxShowCharSet -------------------------------------------------- class SVX_DLLPUBLIC SvxShowCharSet : public Control { public: SvxShowCharSet( Window* pParent, const ResId& rResId ); ~SvxShowCharSet(); void SetFont( const Font& rFont ); void SelectCharacter( sal_uInt32 cNew, BOOL bFocus = FALSE ); sal_UCS4 GetSelectCharacter() const; Link GetDoubleClickHdl() const { return aDoubleClkHdl; } void SetDoubleClickHdl( const Link& rLink ) { aDoubleClkHdl = rLink; } Link GetSelectHdl() const { return aSelectHdl; } void SetSelectHdl( const Link& rHdl ) { aSelectHdl = rHdl; } Link GetHighlightHdl() const { return aHighHdl; } void SetHighlightHdl( const Link& rHdl ) { aHighHdl = rHdl; } Link GetPreSelectHdl() const { return aHighHdl; } void SetPreSelectHdl( const Link& rHdl ) { aPreSelectHdl = rHdl; } #ifdef _SVX_CHARMAP_CXX_ ::svx::SvxShowCharSetItem* ImplGetItem( int _nPos ); int FirstInView( void) const; int LastInView( void) const; int PixelToMapIndex( const Point&) const; void SelectIndex( int index, BOOL bFocus = FALSE ); void DeSelect(); inline sal_Bool IsSelected(USHORT _nPos) const { return _nPos == nSelectedIndex; } inline USHORT GetSelectIndexId() const { return sal::static_int_cast<USHORT>(nSelectedIndex); } USHORT GetRowPos(USHORT _nPos) const; USHORT GetColumnPos(USHORT _nPos) const; void ImplFireAccessibleEvent( short nEventId, const ::com::sun::star::uno::Any& rOldValue, const ::com::sun::star::uno::Any& rNewValue ); ScrollBar* getScrollBar(); void ReleaseAccessible(); sal_Int32 getMaxCharCount() const; #endif // _SVX_CHARMAP_CXX_ protected: virtual void Paint( const Rectangle& ); virtual void MouseButtonDown( const MouseEvent& rMEvt ); virtual void MouseButtonUp( const MouseEvent& rMEvt ); virtual void MouseMove( const MouseEvent& rMEvt ); virtual void Command( const CommandEvent& rCEvt ); virtual void KeyInput( const KeyEvent& rKEvt ); virtual void GetFocus(); virtual void LoseFocus(); virtual void StateChanged( StateChangedType nStateChange ); virtual void DataChanged( const DataChangedEvent& rDCEvt ); virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible > CreateAccessible(); private: typedef ::std::map<sal_Int32, ::svx::SvxShowCharSetItem*> ItemsMap; ItemsMap m_aItems; Link aDoubleClkHdl; Link aSelectHdl; Link aHighHdl; Link aPreSelectHdl; ::svx::SvxShowCharSetVirtualAcc* m_pAccessible; ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible > m_xAccessible; long nX; long nY; BOOL bDrag; sal_Int32 nSelectedIndex; FontCharMap maFontCharMap; ScrollBar aVscrollSB; Size aOrigSize; Point aOrigPos; private: void DrawChars_Impl( int n1, int n2); void InitSettings( BOOL bForeground, BOOL bBackground); // abstraction layers are: Unicode<->MapIndex<->Pixel Point MapIndexToPixel( int) const; //#if 0 // _SOLAR__PRIVATE DECL_LINK( VscrollHdl, ScrollBar* ); //#endif }; // class SvxShowText ===================================================== class SVX_DLLPUBLIC SvxShowText : public Control { public: SvxShowText( Window* pParent, const ResId& rResId, BOOL bCenter = FALSE ); ~SvxShowText(); void SetFont( const Font& rFont ); void SetText( const String& rText ); protected: virtual void Paint( const Rectangle& ); private: long mnY; BOOL mbCenter; }; class SVX_DLLPUBLIC SvxCharMapData { public: SvxCharMapData( class SfxModalDialog* pDialog, BOOL bOne_, ResMgr* pResContext ); void SetCharFont( const Font& rFont ); private: friend class SvxCharacterMap; SfxModalDialog* mpDialog; SvxShowCharSet aShowSet; // Edit aShowText; SvxShowText aShowText; OKButton aOKBtn; CancelButton aCancelBtn; HelpButton aHelpBtn; PushButton aDeleteBtn; FixedText aFontText; ListBox aFontLB; FixedText aSubsetText; ListBox aSubsetLB; FixedText aSymbolText; SvxShowText aShowChar; FixedText aCharCodeText; Font aFont; BOOL bOne; const SubsetMap* pSubsetMap; DECL_LINK( OKHdl, OKButton* ); DECL_LINK( FontSelectHdl, ListBox* ); DECL_LINK( SubsetSelectHdl, ListBox* ); DECL_LINK( CharDoubleClickHdl, Control* pControl ); DECL_LINK( CharSelectHdl, Control* pControl ); DECL_LINK( CharHighlightHdl, Control* pControl ); DECL_LINK( CharPreSelectHdl, Control* pControl ); DECL_LINK( DeleteHdl, PushButton* pBtn ); }; #endif <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: svdxcgv.hxx,v $ * * $Revision: 1.2 $ * * last change: $Author: vg $ $Date: 2007-04-11 16:29:09 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _SVDXCGV_HXX #define _SVDXCGV_HXX #ifndef _SVDEDXV_HXX #include <svx/svdedxv.hxx> #endif #ifndef _GDIMTF_HXX //autogen #include <vcl/gdimtf.hxx> #endif #ifndef INCLUDED_SVXDLLAPI_H #include "svx/svxdllapi.h" #endif //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////// // // @@@@@ @@ @@ @@@@ @@ @@ @@@@ @@ @@ @@@@ @@@@@ @@ @@ @@ @@@@@ @@ @@ // @@ @@@ @@@ @@ @@ @@ @@ @@ @@ @@@ @@ @@ @@ @@ @@ @@ @@ @@ @@ @@ // @@ @@@@@ @@ @@ @@ @@ @@ @@@@@@ @@ @@ @@ @@ @@ @@ @@ @ @@ // @@@@ @@@ @@ @@@@@@ @@@@@@ @@@@@@ @@ @@@ @@@@ @@@@@ @@ @@@@ @@@@@@@ // @@ @@@@@ @@ @@ @@ @@ @@ @@ @@@ @@ @@ @@ @@@ @@ @@ @@@@@@@ // @@ @@@ @@@ @@ @@ @@ @@ @@ @@ @@ @@ @@ @@ @@ @@@ @@ @@ @@@ @@@ // @@@@@ @@ @@ @@@@ @@ @@ @@ @@ @@ @@ @@@@@ @@@@@ @ @@ @@@@@ @@ @@ // //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////// class SVX_DLLPUBLIC SdrExchangeView: public SdrObjEditView { friend class SdrPageView; protected: void ImpGetPasteObjList(Point& rPos, SdrObjList*& rpLst); void ImpPasteObject(SdrObject* pObj, SdrObjList& rLst, const Point& rCenter, const Size& rSiz, const MapMode& rMap, UINT32 nOptions); BOOL ImpGetPasteLayer(const SdrObjList* pObjList, SdrLayerID& rLayer) const; Point GetPastePos(SdrObjList* pLst, OutputDevice* pOut=NULL); // liefert True, wenn rPt geaendert wurde BOOL ImpLimitToWorkArea(Point& rPt) const; protected: // #i71538# make constructors of SdrView sub-components protected to avoid incomplete incarnations which may get casted to SdrView SdrExchangeView(SdrModel* pModel1, OutputDevice* pOut = 0L); public: // Alle markierten Objekte auf dem angegebenen OutputDevice ausgeben. virtual void DrawMarkedObj(OutputDevice& rOut, const Point& rOfs) const; // Z.B. fuer's Clipboard, Drag&Drop, ... // Alle markierten Objekte in ein Metafile stecken. Z.Zt. noch etwas // buggee (Offset..., Fremdgrafikobjekte (SdrGrafObj), Virtuelle // Objektkopien (SdrVirtObj) mit Ankerpos<>(0,0)). virtual GDIMetaFile GetMarkedObjMetaFile(BOOL bNoVDevIfOneMtfMarked=FALSE) const; // Alle markierten Objekte auf eine Bitmap malen. Diese hat die Farbtiefe // und Aufloesung des Bildschirms. virtual Bitmap GetMarkedObjBitmap(BOOL bNoVDevIfOneBmpMarked=FALSE) const; // Alle markierten Objekte in ein neues Model kopieren. Dieses neue Model // hat dann genau eine Page. Das Flag PageNotValid an diesem Model ist // gesetzt. Daran ist zu erkennen, dass nur die Objekte der Page Gueltikeit // haben, die Page sebst jedoch nicht (Seitengroesse, Raender). Das neue // Model wird auf dem Heap erzeugt und wird an den Aufrufer dieser Methode // uebergeben. Dieser hat es dann spaeter zu entsorgen. // Beim einfuegen der markierten Objekte in die eine Page des neuen Model // findet ein Merging der seitenlokalen Layer statt. Sollte kein Platz mehr // fuer weitere seitenlokale Layer sein, wird den entsprechenden Objekten // der Default-Layer zugewiesen (Layer 0, (dokumentglobaler Standardlayer). virtual SdrModel* GetMarkedObjModel() const; void DrawAllMarked(OutputDevice& rOut, const Point& rOfs) const { DrawMarkedObj(rOut,rOfs); } GDIMetaFile GetAllMarkedMetaFile(BOOL bNoVDevIfOneMtfMarked=FALSE) const { return GetMarkedObjMetaFile(bNoVDevIfOneMtfMarked); } Bitmap GetAllMarkedBitmap(BOOL bNoVDevIfOneBmpMarked=FALSE) const { return GetMarkedObjBitmap(bNoVDevIfOneBmpMarked); } Graphic GetAllMarkedGraphic() const; SdrModel* GetAllMarkedModel() const { return GetMarkedObjModel(); } /** Generate a Graphic for the given draw object in the given model @param pModel Must not be NULL. Denotes the draw model the object is a part of. @param pObj The object (can also be a group object) to retrieve a Graphic for. Must not be NULL. @return a graphical representation of the given object, as it appears on screen (e.g. with rotation, if any, applied). */ static Graphic GetObjGraphic( SdrModel* pModel, SdrObject* pObj ); // Bestimmung des View-Mittelpunktes, z.B. zum Pasten Point GetViewCenter(const OutputDevice* pOut=NULL) const; // Bei allen Paste-Methoden werden die neuen Draw-Objekte markiert. // Wird der Parameter bAddMark auf TRUE gesetzt, so werden die neuen // DrawObjekte zu einer bereits bestehenden Selektion "hinzumarkiert". // Dieser Fall ist fuer Drag&Drop mit mehreren Items gedacht. // Die Methoden mit Point-Parameter fuegen neue Objekte zentriert an // dieser Position ein, die anderen zentriert am 1.OutputDevice der View. // Ist der Parameter pPg gesetzt, werden die Objekte and dieser Seite // eingefuegt. Die Positionierung (rPos bzw. Zentrierung) bezieht sich // dann nichtmehr auf die View sondern auf die Page. // Hinweis: SdrObjList ist Basisklasse von SdrPage. // Die Methoden liefern TRUE, wenn die Objekte erfolgreich erzeugt und // eingefuegt wurden. Bei pLst=FALSE und kein TextEdit aktiv kann man // sich dann auch darauf verlassen, dass diese an der View markiert sind. // Andernfalls erfolgt die Markierung nur, wenn pLst z.Zt. auch an der // View angezeigt wird. // Gueltige Werte fuer nOptions sind SDRINSERT_DONTMARK und // SDRINSERT_ADDMARK (siehe svdedtv.hxx). BOOL Paste(const GDIMetaFile& rMtf, SdrObjList* pLst=NULL, OutputDevice* pOut=NULL, UINT32 nOptions=0) { return Paste(rMtf,GetPastePos(pLst,pOut),pLst,nOptions); } BOOL Paste(const GDIMetaFile& rMtf, const Point& rPos, SdrObjList* pLst=NULL, UINT32 nOptions=0); BOOL Paste(const Bitmap& rBmp, SdrObjList* pLst=NULL, OutputDevice* pOut=NULL, UINT32 nOptions=0) { return Paste(rBmp,GetPastePos(pLst,pOut),pLst,nOptions); } BOOL Paste(const Bitmap& rBmp, const Point& rPos, SdrObjList* pLst=NULL, UINT32 nOptions=0); BOOL Paste(const SdrModel& rMod, SdrObjList* pLst=NULL, OutputDevice* pOut=NULL, UINT32 nOptions=0) { return Paste(rMod,GetPastePos(pLst,pOut),pLst,nOptions); } virtual BOOL Paste(const SdrModel& rMod, const Point& rPos, SdrObjList* pLst=NULL, UINT32 nOptions=0); BOOL Paste(const String& rStr, SdrObjList* pLst=NULL, OutputDevice* pOut=NULL, UINT32 nOptions=0) { return Paste(rStr,GetPastePos(pLst,pOut),pLst,nOptions); } BOOL Paste(const String& rStr, const Point& rPos, SdrObjList* pLst=NULL, UINT32 nOptions=0); // der USHORT eFormat nimmt Werte des enum EETextFormat entgegen BOOL Paste(SvStream& rInput, const String& rBaseURL, USHORT eFormat, SdrObjList* pLst=NULL, OutputDevice* pOut=NULL, UINT32 nOptions=0) { return Paste(rInput,rBaseURL,eFormat,GetPastePos(pLst,pOut),pLst,nOptions); } BOOL Paste(SvStream& rInput, const String& rBaseURL, USHORT eFormat, const Point& rPos, SdrObjList* pLst=NULL, UINT32 nOptions=0); // Feststellen, ob ein bestimmtes Format ueber Drag&Drop bzw. ueber's // Clipboard angenommen werden kann. BOOL IsExchangeFormatSupported(ULONG nFormat) const; BOOL Cut( ULONG nFormat = SDR_ANYFORMAT ); void CutMarked( ULONG nFormat=SDR_ANYFORMAT ); BOOL Yank( ULONG nFormat = SDR_ANYFORMAT ); void YankMarked( ULONG nFormat=SDR_ANYFORMAT ); BOOL Paste( Window* pWin = NULL, ULONG nFormat = SDR_ANYFORMAT ); BOOL PasteClipboard( OutputDevice* pOut = NULL, ULONG nFormat = SDR_ANYFORMAT, UINT32 nOptions = 0 ); }; #endif //_SVDXCGV_HXX <commit_msg>INTEGRATION: CWS changefileheader (1.2.466); FILE MERGED 2008/04/01 12:46:57 thb 1.2.466.2: #i85898# Stripping all external header guards 2008/03/31 14:18:19 rt 1.2.466.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: svdxcgv.hxx,v $ * $Revision: 1.3 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifndef _SVDXCGV_HXX #define _SVDXCGV_HXX #include <svx/svdedxv.hxx> #ifndef _GDIMTF_HXX //autogen #include <vcl/gdimtf.hxx> #endif #include "svx/svxdllapi.h" //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////// // // @@@@@ @@ @@ @@@@ @@ @@ @@@@ @@ @@ @@@@ @@@@@ @@ @@ @@ @@@@@ @@ @@ // @@ @@@ @@@ @@ @@ @@ @@ @@ @@ @@@ @@ @@ @@ @@ @@ @@ @@ @@ @@ @@ // @@ @@@@@ @@ @@ @@ @@ @@ @@@@@@ @@ @@ @@ @@ @@ @@ @@ @ @@ // @@@@ @@@ @@ @@@@@@ @@@@@@ @@@@@@ @@ @@@ @@@@ @@@@@ @@ @@@@ @@@@@@@ // @@ @@@@@ @@ @@ @@ @@ @@ @@ @@@ @@ @@ @@ @@@ @@ @@ @@@@@@@ // @@ @@@ @@@ @@ @@ @@ @@ @@ @@ @@ @@ @@ @@ @@ @@@ @@ @@ @@@ @@@ // @@@@@ @@ @@ @@@@ @@ @@ @@ @@ @@ @@ @@@@@ @@@@@ @ @@ @@@@@ @@ @@ // //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////// class SVX_DLLPUBLIC SdrExchangeView: public SdrObjEditView { friend class SdrPageView; protected: void ImpGetPasteObjList(Point& rPos, SdrObjList*& rpLst); void ImpPasteObject(SdrObject* pObj, SdrObjList& rLst, const Point& rCenter, const Size& rSiz, const MapMode& rMap, UINT32 nOptions); BOOL ImpGetPasteLayer(const SdrObjList* pObjList, SdrLayerID& rLayer) const; Point GetPastePos(SdrObjList* pLst, OutputDevice* pOut=NULL); // liefert True, wenn rPt geaendert wurde BOOL ImpLimitToWorkArea(Point& rPt) const; protected: // #i71538# make constructors of SdrView sub-components protected to avoid incomplete incarnations which may get casted to SdrView SdrExchangeView(SdrModel* pModel1, OutputDevice* pOut = 0L); public: // Alle markierten Objekte auf dem angegebenen OutputDevice ausgeben. virtual void DrawMarkedObj(OutputDevice& rOut, const Point& rOfs) const; // Z.B. fuer's Clipboard, Drag&Drop, ... // Alle markierten Objekte in ein Metafile stecken. Z.Zt. noch etwas // buggee (Offset..., Fremdgrafikobjekte (SdrGrafObj), Virtuelle // Objektkopien (SdrVirtObj) mit Ankerpos<>(0,0)). virtual GDIMetaFile GetMarkedObjMetaFile(BOOL bNoVDevIfOneMtfMarked=FALSE) const; // Alle markierten Objekte auf eine Bitmap malen. Diese hat die Farbtiefe // und Aufloesung des Bildschirms. virtual Bitmap GetMarkedObjBitmap(BOOL bNoVDevIfOneBmpMarked=FALSE) const; // Alle markierten Objekte in ein neues Model kopieren. Dieses neue Model // hat dann genau eine Page. Das Flag PageNotValid an diesem Model ist // gesetzt. Daran ist zu erkennen, dass nur die Objekte der Page Gueltikeit // haben, die Page sebst jedoch nicht (Seitengroesse, Raender). Das neue // Model wird auf dem Heap erzeugt und wird an den Aufrufer dieser Methode // uebergeben. Dieser hat es dann spaeter zu entsorgen. // Beim einfuegen der markierten Objekte in die eine Page des neuen Model // findet ein Merging der seitenlokalen Layer statt. Sollte kein Platz mehr // fuer weitere seitenlokale Layer sein, wird den entsprechenden Objekten // der Default-Layer zugewiesen (Layer 0, (dokumentglobaler Standardlayer). virtual SdrModel* GetMarkedObjModel() const; void DrawAllMarked(OutputDevice& rOut, const Point& rOfs) const { DrawMarkedObj(rOut,rOfs); } GDIMetaFile GetAllMarkedMetaFile(BOOL bNoVDevIfOneMtfMarked=FALSE) const { return GetMarkedObjMetaFile(bNoVDevIfOneMtfMarked); } Bitmap GetAllMarkedBitmap(BOOL bNoVDevIfOneBmpMarked=FALSE) const { return GetMarkedObjBitmap(bNoVDevIfOneBmpMarked); } Graphic GetAllMarkedGraphic() const; SdrModel* GetAllMarkedModel() const { return GetMarkedObjModel(); } /** Generate a Graphic for the given draw object in the given model @param pModel Must not be NULL. Denotes the draw model the object is a part of. @param pObj The object (can also be a group object) to retrieve a Graphic for. Must not be NULL. @return a graphical representation of the given object, as it appears on screen (e.g. with rotation, if any, applied). */ static Graphic GetObjGraphic( SdrModel* pModel, SdrObject* pObj ); // Bestimmung des View-Mittelpunktes, z.B. zum Pasten Point GetViewCenter(const OutputDevice* pOut=NULL) const; // Bei allen Paste-Methoden werden die neuen Draw-Objekte markiert. // Wird der Parameter bAddMark auf TRUE gesetzt, so werden die neuen // DrawObjekte zu einer bereits bestehenden Selektion "hinzumarkiert". // Dieser Fall ist fuer Drag&Drop mit mehreren Items gedacht. // Die Methoden mit Point-Parameter fuegen neue Objekte zentriert an // dieser Position ein, die anderen zentriert am 1.OutputDevice der View. // Ist der Parameter pPg gesetzt, werden die Objekte and dieser Seite // eingefuegt. Die Positionierung (rPos bzw. Zentrierung) bezieht sich // dann nichtmehr auf die View sondern auf die Page. // Hinweis: SdrObjList ist Basisklasse von SdrPage. // Die Methoden liefern TRUE, wenn die Objekte erfolgreich erzeugt und // eingefuegt wurden. Bei pLst=FALSE und kein TextEdit aktiv kann man // sich dann auch darauf verlassen, dass diese an der View markiert sind. // Andernfalls erfolgt die Markierung nur, wenn pLst z.Zt. auch an der // View angezeigt wird. // Gueltige Werte fuer nOptions sind SDRINSERT_DONTMARK und // SDRINSERT_ADDMARK (siehe svdedtv.hxx). BOOL Paste(const GDIMetaFile& rMtf, SdrObjList* pLst=NULL, OutputDevice* pOut=NULL, UINT32 nOptions=0) { return Paste(rMtf,GetPastePos(pLst,pOut),pLst,nOptions); } BOOL Paste(const GDIMetaFile& rMtf, const Point& rPos, SdrObjList* pLst=NULL, UINT32 nOptions=0); BOOL Paste(const Bitmap& rBmp, SdrObjList* pLst=NULL, OutputDevice* pOut=NULL, UINT32 nOptions=0) { return Paste(rBmp,GetPastePos(pLst,pOut),pLst,nOptions); } BOOL Paste(const Bitmap& rBmp, const Point& rPos, SdrObjList* pLst=NULL, UINT32 nOptions=0); BOOL Paste(const SdrModel& rMod, SdrObjList* pLst=NULL, OutputDevice* pOut=NULL, UINT32 nOptions=0) { return Paste(rMod,GetPastePos(pLst,pOut),pLst,nOptions); } virtual BOOL Paste(const SdrModel& rMod, const Point& rPos, SdrObjList* pLst=NULL, UINT32 nOptions=0); BOOL Paste(const String& rStr, SdrObjList* pLst=NULL, OutputDevice* pOut=NULL, UINT32 nOptions=0) { return Paste(rStr,GetPastePos(pLst,pOut),pLst,nOptions); } BOOL Paste(const String& rStr, const Point& rPos, SdrObjList* pLst=NULL, UINT32 nOptions=0); // der USHORT eFormat nimmt Werte des enum EETextFormat entgegen BOOL Paste(SvStream& rInput, const String& rBaseURL, USHORT eFormat, SdrObjList* pLst=NULL, OutputDevice* pOut=NULL, UINT32 nOptions=0) { return Paste(rInput,rBaseURL,eFormat,GetPastePos(pLst,pOut),pLst,nOptions); } BOOL Paste(SvStream& rInput, const String& rBaseURL, USHORT eFormat, const Point& rPos, SdrObjList* pLst=NULL, UINT32 nOptions=0); // Feststellen, ob ein bestimmtes Format ueber Drag&Drop bzw. ueber's // Clipboard angenommen werden kann. BOOL IsExchangeFormatSupported(ULONG nFormat) const; BOOL Cut( ULONG nFormat = SDR_ANYFORMAT ); void CutMarked( ULONG nFormat=SDR_ANYFORMAT ); BOOL Yank( ULONG nFormat = SDR_ANYFORMAT ); void YankMarked( ULONG nFormat=SDR_ANYFORMAT ); BOOL Paste( Window* pWin = NULL, ULONG nFormat = SDR_ANYFORMAT ); BOOL PasteClipboard( OutputDevice* pOut = NULL, ULONG nFormat = SDR_ANYFORMAT, UINT32 nOptions = 0 ); }; #endif //_SVDXCGV_HXX <|endoftext|>
<commit_before>#include <boost/python.hpp> #include <Magick++/Montage.h> using namespace boost::python; void __Montage() { class_< Magick::Montage >("Montage", init< >()) .def("backgroundColor", (void (Magick::Montage::*)(const Magick::Color&)) &Magick::Montage::backgroundColor) .def("backgroundColor", (Magick::Color (Magick::Montage::*)() const) &Magick::Montage::backgroundColor) .def("compose", (void (Magick::Montage::*)(const Magick::CompositeOperator)) &Magick::Montage::compose) .def("compose", (Magick::CompositeOperator (Magick::Montage::*)() const) &Magick::Montage::compose) .def("fileName", (void (Magick::Montage::*)(const std::string&)) &Magick::Montage::fileName) .def("fileName", (std::string (Magick::Montage::*)() const) &Magick::Montage::fileName) .def("fillColor", (void (Magick::Montage::*)(const Magick::Color&)) &Magick::Montage::fillColor) .def("fillColor", (Magick::Color (Magick::Montage::*)() const) &Magick::Montage::fillColor) .def("geometry", (void (Magick::Montage::*)(const Magick::Geometry&)) &Magick::Montage::geometry) .def("geometry", (Magick::Geometry (Magick::Montage::*)() const) &Magick::Montage::geometry) .def("gravity", (void (Magick::Montage::*)(const Magick::GravityType)) &Magick::Montage::gravity) .def("gravity", (Magick::GravityType (Magick::Montage::*)() const) &Magick::Montage::gravity) .def("label", (void (Magick::Montage::*)(const std::string&)) &Magick::Montage::label) .def("label", (std::string (Magick::Montage::*)() const) &Magick::Montage::label) .def("penColor", (void (Magick::Montage::*)(const Magick::Color&)) &Magick::Montage::penColor) .def("penColor", (Magick::Color (Magick::Montage::*)() const) &Magick::Montage::penColor) .def("pointSize", (void (Magick::Montage::*)(unsigned int)) &Magick::Montage::pointSize) .def("pointSize", (unsigned int (Magick::Montage::*)() const) &Magick::Montage::pointSize) .def("shadow", (void (Magick::Montage::*)(const bool)) &Magick::Montage::shadow) .def("shadow", (bool (Magick::Montage::*)() const) &Magick::Montage::shadow) .def("strokeColor", (void (Magick::Montage::*)(const Magick::Color&)) &Magick::Montage::strokeColor) .def("strokeColor", (Magick::Color (Magick::Montage::*)() const) &Magick::Montage::strokeColor) .def("texture", (void (Magick::Montage::*)(const std::string&)) &Magick::Montage::texture) .def("texture", (std::string (Magick::Montage::*)() const) &Magick::Montage::texture) .def("title", (void (Magick::Montage::*)(const std::string&)) &Magick::Montage::title) .def("title", (std::string (Magick::Montage::*)() const) &Magick::Montage::title) .def("transparentColor", (void (Magick::Montage::*)(const Magick::Color&)) &Magick::Montage::transparentColor) .def("transparentColor", (Magick::Color (Magick::Montage::*)() const) &Magick::Montage::transparentColor) ; class_< Magick::MontageFramed >("MontageFramed", init< >()) .def("borderColor", (void (Magick::MontageFramed::*)(const Magick::Color&)) &Magick::MontageFramed::borderColor) .def("borderColor", (Magick::Color (Magick::MontageFramed::*)() const) &Magick::MontageFramed::borderColor) .def("borderWidth", (void (Magick::MontageFramed::*)(unsigned int)) &Magick::MontageFramed::borderWidth) .def("borderWidth", (unsigned int (Magick::MontageFramed::*)() const) &Magick::MontageFramed::borderWidth) .def("frameGeometry", (void (Magick::MontageFramed::*)(const Magick::Geometry&)) &Magick::MontageFramed::geometry) .def("frameGeometry", (Magick::Geometry (Magick::MontageFramed::*)() const) &Magick::MontageFramed::geometry) .def("matteColor", (void (Magick::MontageFramed::*)(const Magick::Color&)) &Magick::MontageFramed::matteColor) .def("matteColor", (Magick::Color (Magick::MontageFramed::*)() const) &Magick::MontageFramed::matteColor) ; } <commit_msg>fixed: Montage.pointSize's in/out parameter for ImageMagick<commit_after>#include <boost/python.hpp> #include <Magick++/Montage.h> using namespace boost::python; void __Montage() { class_< Magick::Montage >("Montage", init< >()) .def("backgroundColor", (void (Magick::Montage::*)(const Magick::Color&)) &Magick::Montage::backgroundColor) .def("backgroundColor", (Magick::Color (Magick::Montage::*)() const) &Magick::Montage::backgroundColor) .def("compose", (void (Magick::Montage::*)(const Magick::CompositeOperator)) &Magick::Montage::compose) .def("compose", (Magick::CompositeOperator (Magick::Montage::*)() const) &Magick::Montage::compose) .def("fileName", (void (Magick::Montage::*)(const std::string&)) &Magick::Montage::fileName) .def("fileName", (std::string (Magick::Montage::*)() const) &Magick::Montage::fileName) .def("fillColor", (void (Magick::Montage::*)(const Magick::Color&)) &Magick::Montage::fillColor) .def("fillColor", (Magick::Color (Magick::Montage::*)() const) &Magick::Montage::fillColor) .def("geometry", (void (Magick::Montage::*)(const Magick::Geometry&)) &Magick::Montage::geometry) .def("geometry", (Magick::Geometry (Magick::Montage::*)() const) &Magick::Montage::geometry) .def("gravity", (void (Magick::Montage::*)(const Magick::GravityType)) &Magick::Montage::gravity) .def("gravity", (Magick::GravityType (Magick::Montage::*)() const) &Magick::Montage::gravity) .def("label", (void (Magick::Montage::*)(const std::string&)) &Magick::Montage::label) .def("label", (std::string (Magick::Montage::*)() const) &Magick::Montage::label) .def("penColor", (void (Magick::Montage::*)(const Magick::Color&)) &Magick::Montage::penColor) .def("penColor", (Magick::Color (Magick::Montage::*)() const) &Magick::Montage::penColor) #ifdef PGMAGICK_LIB_IMAGEMAGICK .def("pointSize", (void (Magick::Montage::*)(size_t)) &Magick::Montage::pointSize) .def("pointSize", (size_t (Magick::Montage::*)() const) &Magick::Montage::pointSize) #else .def("pointSize", (void (Magick::Montage::*)(unsigned int)) &Magick::Montage::pointSize) .def("pointSize", (unsigned int (Magick::Montage::*)() const) &Magick::Montage::pointSize) #endif .def("shadow", (void (Magick::Montage::*)(const bool)) &Magick::Montage::shadow) .def("shadow", (bool (Magick::Montage::*)() const) &Magick::Montage::shadow) .def("strokeColor", (void (Magick::Montage::*)(const Magick::Color&)) &Magick::Montage::strokeColor) .def("strokeColor", (Magick::Color (Magick::Montage::*)() const) &Magick::Montage::strokeColor) .def("texture", (void (Magick::Montage::*)(const std::string&)) &Magick::Montage::texture) .def("texture", (std::string (Magick::Montage::*)() const) &Magick::Montage::texture) .def("title", (void (Magick::Montage::*)(const std::string&)) &Magick::Montage::title) .def("title", (std::string (Magick::Montage::*)() const) &Magick::Montage::title) .def("transparentColor", (void (Magick::Montage::*)(const Magick::Color&)) &Magick::Montage::transparentColor) .def("transparentColor", (Magick::Color (Magick::Montage::*)() const) &Magick::Montage::transparentColor) ; class_< Magick::MontageFramed >("MontageFramed", init< >()) .def("borderColor", (void (Magick::MontageFramed::*)(const Magick::Color&)) &Magick::MontageFramed::borderColor) .def("borderColor", (Magick::Color (Magick::MontageFramed::*)() const) &Magick::MontageFramed::borderColor) .def("borderWidth", (void (Magick::MontageFramed::*)(unsigned int)) &Magick::MontageFramed::borderWidth) .def("borderWidth", (unsigned int (Magick::MontageFramed::*)() const) &Magick::MontageFramed::borderWidth) .def("frameGeometry", (void (Magick::MontageFramed::*)(const Magick::Geometry&)) &Magick::MontageFramed::geometry) .def("frameGeometry", (Magick::Geometry (Magick::MontageFramed::*)() const) &Magick::MontageFramed::geometry) .def("matteColor", (void (Magick::MontageFramed::*)(const Magick::Color&)) &Magick::MontageFramed::matteColor) .def("matteColor", (Magick::Color (Magick::MontageFramed::*)() const) &Magick::MontageFramed::matteColor) ; } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: SwAppletImpl.hxx,v $ * * $Revision: 1.7 $ * * last change: $Author: rt $ $Date: 2005-09-09 01:28:54 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _SW_APPLET_IMPL_HXX #define _SW_APPLET_IMPL_HXX #define SWHTML_OPTTYPE_IGNORE 0 #define SWHTML_OPTTYPE_TAG 1 #define SWHTML_OPTTYPE_PARAM 2 #define SWHTML_OPTTYPE_SIZE 3 #ifndef _COM_SUN_STAR_EMBED_XEMBEDDEDOBJECT_HPP_ #include <com/sun/star/embed/XEmbeddedObject.hpp> #endif #ifndef _STRING_HXX //autogen #include <tools/string.hxx> #endif #ifndef _HTMLKYWD_HXX #include <svtools/htmlkywd.hxx> #endif #ifndef _FRMHTML_HXX //autogen #include <sfx2/frmhtml.hxx> #endif #ifndef _FRMHTMLW_HXX //autogen #include <sfx2/frmhtmlw.hxx> #endif #ifndef _WRKWIN_HXX //autogen #include <vcl/wrkwin.hxx> #endif #include <sot/storage.hxx> #ifndef _SFXITEMSET_HXX #include <svtools/itemset.hxx> #endif #include <svtools/ownlist.hxx> class SfxItemSet; extern sal_Char const SVTOOLS_CONSTASCII_DECL( sHTML_O_hidden, "HIDDEN" ); extern sal_Char const SVTOOLS_CONSTASCII_DECL( sHTML_HIDDEN_false, "FALSE" ); extern sal_Char const SVTOOLS_CONSTASCII_DECL( sHTML_O_archive, "ARCHIVE" ); extern sal_Char const SVTOOLS_CONSTASCII_DECL( sHTML_O_archives, "ARCHIVES" ); extern sal_Char const SVTOOLS_CONSTASCII_DECL( sHTML_O_object, "OBJECT" ); class SwApplet_Impl { com::sun::star::uno::Reference < com::sun::star::embed::XEmbeddedObject > xApplet; SvCommandList aCommandList; // und die szugehorige Command-List SfxItemSet aItemSet; String sAlt; public: static USHORT GetOptionType( const String& rName, BOOL bApplet ); SwApplet_Impl( SfxItemPool& rPool, USHORT nWhich1, USHORT nWhich2 ); SwApplet_Impl( SfxItemSet& rSet ): aItemSet ( rSet) {} ~SwApplet_Impl(); void CreateApplet( const String& rCode, const String& rName, BOOL bMayScript, const String& rCodeBase, const String& rBaseURL ); #ifdef SOLAR_JAVA sal_Bool CreateApplet( const String& rBaseURL ); void AppendParam( const String& rName, const String& rValue ); #endif void FinishApplet(); com::sun::star::uno::Reference < com::sun::star::embed::XEmbeddedObject > GetApplet() { return xApplet; } SfxItemSet& GetItemSet() { return aItemSet; } const String& GetAltText() { return sAlt; } void SetAltText( const String& rAlt ) {sAlt = rAlt;} }; #endif <commit_msg>INTEGRATION: CWS writercorehandoff (1.6.54); FILE MERGED 2005/09/13 11:09:31 tra 1.6.54.2: RESYNC: (1.6-1.7); FILE MERGED 2005/06/07 14:09:35 fme 1.6.54.1: #i50348# General cleanup - removed unused header files, functions, members, declarations etc.<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: SwAppletImpl.hxx,v $ * * $Revision: 1.8 $ * * last change: $Author: hr $ $Date: 2006-08-14 15:14:39 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _SW_APPLET_IMPL_HXX #define _SW_APPLET_IMPL_HXX #define SWHTML_OPTTYPE_IGNORE 0 #define SWHTML_OPTTYPE_TAG 1 #define SWHTML_OPTTYPE_PARAM 2 #define SWHTML_OPTTYPE_SIZE 3 #ifndef _COM_SUN_STAR_EMBED_XEMBEDDEDOBJECT_HPP_ #include <com/sun/star/embed/XEmbeddedObject.hpp> #endif #ifndef _STRING_HXX //autogen #include <tools/string.hxx> #endif #ifndef _HTMLKYWD_HXX #include <svtools/htmlkywd.hxx> #endif #ifndef _FRMHTML_HXX //autogen #include <sfx2/frmhtml.hxx> #endif #ifndef _FRMHTMLW_HXX //autogen #include <sfx2/frmhtmlw.hxx> #endif #ifndef _WRKWIN_HXX //autogen #include <vcl/wrkwin.hxx> #endif #include <sot/storage.hxx> #ifndef _SFXITEMSET_HXX #include <svtools/itemset.hxx> #endif #include <svtools/ownlist.hxx> class SfxItemSet; extern sal_Char const SVTOOLS_CONSTASCII_DECL( sHTML_O_hidden, "HIDDEN" ); extern sal_Char const SVTOOLS_CONSTASCII_DECL( sHTML_HIDDEN_false, "FALSE" ); extern sal_Char const SVTOOLS_CONSTASCII_DECL( sHTML_O_archive, "ARCHIVE" ); extern sal_Char const SVTOOLS_CONSTASCII_DECL( sHTML_O_archives, "ARCHIVES" ); extern sal_Char const SVTOOLS_CONSTASCII_DECL( sHTML_O_object, "OBJECT" ); class SwApplet_Impl { com::sun::star::uno::Reference < com::sun::star::embed::XEmbeddedObject > xApplet; SvCommandList aCommandList; // und die szugehorige Command-List SfxItemSet aItemSet; String sAlt; public: static USHORT GetOptionType( const String& rName, BOOL bApplet ); SwApplet_Impl( SfxItemPool& rPool, USHORT nWhich1, USHORT nWhich2 ); SwApplet_Impl( SfxItemSet& rSet ): aItemSet ( rSet) {} ~SwApplet_Impl(); void CreateApplet( const String& rCode, const String& rName, BOOL bMayScript, const String& rCodeBase, const String& rBaseURL ); #ifdef SOLAR_JAVA sal_Bool CreateApplet( const String& rBaseURL ); void AppendParam( const String& rName, const String& rValue ); #endif void FinishApplet(); com::sun::star::uno::Reference < com::sun::star::embed::XEmbeddedObject > GetApplet() { return xApplet; } SfxItemSet& GetItemSet() { return aItemSet; } const String& GetAltText() { return sAlt; } void SetAltText( const String& rAlt ) {sAlt = rAlt;} }; #endif <|endoftext|>
<commit_before> #include <gtest/gtest.h> #include <aerial_autonomy/common/conversions.h> #include <aerial_autonomy/controller_connectors/mpc_controller_quad_connector.h> #include <aerial_autonomy/controller_connectors/visual_servoing_reference_connector.h> #include <aerial_autonomy/controllers/ddp_quad_mpc_controller.h> #include <aerial_autonomy/controllers/quad_particle_reference_controller.h> #include <aerial_autonomy/estimators/thrust_gain_estimator.h> #include <aerial_autonomy/tests/test_utils.h> #include <aerial_autonomy/trackers/simple_tracker.h> #include <chrono> #include <quad_simulator_parser/quad_simulator.h> #include <thread> /** * @brief Namespace for UAV Simulator Hardware */ using namespace quad_simulator; using namespace test_utils; class VisualServoingReferenceConnectorTests : public ::testing::Test { public: using VisualServoingReferenceConnectorT = VisualServoingReferenceConnector<Eigen::VectorXd, Eigen::VectorXd, MPCControllerQuadConnector>; VisualServoingReferenceConnectorTests() : tracking_offset_transform_( tf::createQuaternionFromRPY(0, M_PI / 3, M_PI / 2), tf::Vector3(0, 0, 0)), thrust_gain_estimator_(0.18), tol_(0.5) { // Drone settings drone_hardware_.usePerfectTime(); drone_hardware_.set_delay_send_time(0.02); // Config mpc_config_ = createQuadMPCConfig(); tf::Transform camera_transform = tf::Transform::getIdentity(); simple_tracker_.reset(new SimpleTracker(drone_hardware_, camera_transform)); auto duration = std::chrono::milliseconds(20); // Low-level: mpc_controller_.reset(new DDPQuadMPCController(mpc_config_, duration)); quad_mpc_connector_.reset(new MPCControllerQuadConnector( drone_hardware_, *mpc_controller_, thrust_gain_estimator_)); // High level reference_generator_.reset( new QuadParticleReferenceController(particle_reference_config_)); visual_servoing_connector_.reset(new VisualServoingReferenceConnectorT( *simple_tracker_, drone_hardware_, *reference_generator_, *quad_mpc_connector_, camera_transform, tracking_offset_transform_)); } static void SetUpTestCase() { // Configure logging LogConfig log_config; log_config.set_directory("/tmp/data"); Log::instance().configure(log_config); DataStreamConfig data_config; data_config.set_stream_id("visual_servoing_reference_connector"); Log::instance().addDataStream(data_config); data_config.set_stream_id("quad_mpc_state_estimator"); Log::instance().addDataStream(data_config); data_config.set_stream_id("ddp_quad_mpc_controller"); Log::instance().addDataStream(data_config); data_config.set_stream_id("thrust_gain_estimator"); Log::instance().addDataStream(data_config); data_config.set_stream_id("tracking_vector_estimator"); Log::instance().addDataStream(data_config); } void runUntilConvergence(const tf::Transform &tracked_pose, const PositionYaw &goal_relative_pose) { simple_tracker_->setTargetPoseGlobalFrame(tracked_pose); simple_tracker_->setTrackingIsValid(true); tf::Transform gravity_aligned_tracked_pose = tracked_pose * tracking_offset_transform_; double roll, pitch, yaw; gravity_aligned_tracked_pose.getBasis().getRPY(roll, pitch, yaw); gravity_aligned_tracked_pose.getBasis().setRPY(0, 0, yaw); // Fly quadrotor which sets the altitude to 0.5 drone_hardware_.setBatteryPercent(60); drone_hardware_.takeoff(); // Set goal tf::Transform goal_relative_pose_tf; conversions::positionYawToTf(goal_relative_pose, goal_relative_pose_tf); visual_servoing_connector_->setGoal(goal_relative_pose); visual_servoing_connector_->initialize(); quad_mpc_connector_->initialize(); // Run controller until inactive auto runController = [&]() { visual_servoing_connector_->run(); quad_mpc_connector_->run(); return quad_mpc_connector_->getStatus() == ControllerStatus::Active; }; ASSERT_FALSE(test_utils::waitUntilFalse()(runController, std::chrono::seconds(200), std::chrono::milliseconds(0))); // Check position is the goal position parsernode::common::quaddata sensor_data; drone_hardware_.getquaddata(sensor_data); tf::Transform quad_transform( tf::createQuaternionFromRPY(0, 0, sensor_data.rpydata.z), tf::Vector3(sensor_data.localpos.x, sensor_data.localpos.y, sensor_data.localpos.z)); ASSERT_TF_NEAR(quad_transform, gravity_aligned_tracked_pose * goal_relative_pose_tf, tol_); ASSERT_EQ(quad_mpc_connector_->getStatus(), ControllerStatus::Completed); ASSERT_NEAR(thrust_gain_estimator_.getThrustGain(), 0.16, 2e-2); } QuadSimulator drone_hardware_; std::unique_ptr<SimpleTracker> simple_tracker_; std::unique_ptr<QuadParticleReferenceController> reference_generator_; std::unique_ptr<VisualServoingReferenceConnectorT> visual_servoing_connector_; std::unique_ptr<DDPQuadMPCController> mpc_controller_; std::unique_ptr<MPCControllerQuadConnector> quad_mpc_connector_; tf::Transform tracking_offset_transform_; ThrustGainEstimator thrust_gain_estimator_; QuadMPCControllerConfig mpc_config_; ParticleReferenceConfig particle_reference_config_; double tol_; }; TEST_F(VisualServoingReferenceConnectorTests, Constructor) {} TEST_F(VisualServoingReferenceConnectorTests, InitializationTest) { // ASSERT_EQ(quad_mpc_connector_->getGoal(), nullptr); tf::Transform tracker_pose; tracker_pose.setIdentity(); tracker_pose.setOrigin(tf::Vector3(1, 1, 1)); simple_tracker_->setTargetPoseGlobalFrame(tracker_pose); simple_tracker_->setTrackingIsValid(true); visual_servoing_connector_->setGoal(PositionYaw()); visual_servoing_connector_->initialize(); auto reference = quad_mpc_connector_->getGoal(); auto state_control = reference->atTime(20); Eigen::VectorXd goal = state_control.first; ASSERT_VEC_NEAR(tracker_pose.getOrigin(), tf::Vector3(goal[0], goal[1], goal[2]), 1e-3); ASSERT_NEAR(goal[3], 0, 1e-2); ASSERT_NEAR(goal[4], 0, 1e-2); ASSERT_NEAR(goal[5], M_PI / 2.0, 1e-2); } TEST_F(VisualServoingReferenceConnectorTests, CriticalRun) { visual_servoing_connector_->setGoal(PositionYaw()); // make tracking invalid: simple_tracker_->setTrackingIsValid(false); // Run connector visual_servoing_connector_->run(); ASSERT_EQ(visual_servoing_connector_->getStatus(), ControllerStatus::Critical); } TEST_F(VisualServoingReferenceConnectorTests, RunUntilConvergence) { // set tracking goal tf::Transform tracked_pose(tf::createQuaternionFromRPY(0, 0, -0.1), tf::Vector3(2, -0.5, 0.5)); PositionYaw goal_relative_pose(1, 0, 0, 0.5); runUntilConvergence(tracked_pose, goal_relative_pose); } int main(int argc, char **argv) { testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } <commit_msg>Add fixed test<commit_after> #include <gtest/gtest.h> #include <aerial_autonomy/common/conversions.h> #include <aerial_autonomy/controller_connectors/mpc_controller_quad_connector.h> #include <aerial_autonomy/controller_connectors/visual_servoing_reference_connector.h> #include <aerial_autonomy/controllers/ddp_quad_mpc_controller.h> #include <aerial_autonomy/controllers/quad_particle_reference_controller.h> #include <aerial_autonomy/estimators/thrust_gain_estimator.h> #include <aerial_autonomy/tests/test_utils.h> #include <aerial_autonomy/trackers/simple_tracker.h> #include <chrono> #include <quad_simulator_parser/quad_simulator.h> #include <thread> /** * @brief Namespace for UAV Simulator Hardware */ using namespace quad_simulator; using namespace test_utils; class VisualServoingReferenceConnectorTests : public ::testing::Test { public: using VisualServoingReferenceConnectorT = VisualServoingReferenceConnector<Eigen::VectorXd, Eigen::VectorXd, MPCControllerQuadConnector>; VisualServoingReferenceConnectorTests() : tracking_offset_transform_( tf::createQuaternionFromRPY(0, M_PI / 3, M_PI / 2), tf::Vector3(0, 0, 0)), thrust_gain_estimator_(0.18), tol_(0.5) { // Drone settings drone_hardware_.usePerfectTime(); drone_hardware_.set_delay_send_time(0.02); // Config mpc_config_ = createQuadMPCConfig(); tf::Transform camera_transform = tf::Transform::getIdentity(); simple_tracker_.reset(new SimpleTracker(drone_hardware_, camera_transform)); auto duration = std::chrono::milliseconds(20); // Low-level: mpc_controller_.reset(new DDPQuadMPCController(mpc_config_, duration)); quad_mpc_connector_.reset(new MPCControllerQuadConnector( drone_hardware_, *mpc_controller_, thrust_gain_estimator_)); // High level reference_generator_.reset( new QuadParticleReferenceController(particle_reference_config_)); visual_servoing_connector_.reset(new VisualServoingReferenceConnectorT( *simple_tracker_, drone_hardware_, *reference_generator_, *quad_mpc_connector_, camera_transform, tracking_offset_transform_)); } static void SetUpTestCase() { // Configure logging LogConfig log_config; log_config.set_directory("/tmp/data"); Log::instance().configure(log_config); DataStreamConfig data_config; data_config.set_stream_id("visual_servoing_reference_connector"); Log::instance().addDataStream(data_config); data_config.set_stream_id("quad_mpc_state_estimator"); Log::instance().addDataStream(data_config); data_config.set_stream_id("ddp_quad_mpc_controller"); Log::instance().addDataStream(data_config); data_config.set_stream_id("thrust_gain_estimator"); Log::instance().addDataStream(data_config); data_config.set_stream_id("tracking_vector_estimator"); Log::instance().addDataStream(data_config); } void runUntilConvergence(const tf::Transform &tracked_pose, const PositionYaw &goal_relative_pose) { simple_tracker_->setTargetPoseGlobalFrame(tracked_pose); simple_tracker_->setTrackingIsValid(true); tf::Transform gravity_aligned_tracked_pose = tracked_pose * tracking_offset_transform_; double roll, pitch, yaw; gravity_aligned_tracked_pose.getBasis().getRPY(roll, pitch, yaw); gravity_aligned_tracked_pose.getBasis().setRPY(0, 0, yaw); // Fly quadrotor which sets the altitude to 0.5 drone_hardware_.setBatteryPercent(60); drone_hardware_.takeoff(); // Set goal tf::Transform goal_relative_pose_tf; conversions::positionYawToTf(goal_relative_pose, goal_relative_pose_tf); visual_servoing_connector_->setGoal(goal_relative_pose); visual_servoing_connector_->initialize(); quad_mpc_connector_->initialize(); // Run controller until inactive auto runController = [&]() { visual_servoing_connector_->run(); quad_mpc_connector_->run(); return quad_mpc_connector_->getStatus() == ControllerStatus::Active; }; ASSERT_FALSE(test_utils::waitUntilFalse()(runController, std::chrono::seconds(200), std::chrono::milliseconds(0))); // Check position is the goal position parsernode::common::quaddata sensor_data; drone_hardware_.getquaddata(sensor_data); tf::Transform quad_transform( tf::createQuaternionFromRPY(0, 0, sensor_data.rpydata.z), tf::Vector3(sensor_data.localpos.x, sensor_data.localpos.y, sensor_data.localpos.z)); ASSERT_TF_NEAR(quad_transform, gravity_aligned_tracked_pose * goal_relative_pose_tf, tol_); ASSERT_EQ(quad_mpc_connector_->getStatus(), ControllerStatus::Completed); ASSERT_NEAR(thrust_gain_estimator_.getThrustGain(), 0.16, 2e-2); } QuadSimulator drone_hardware_; std::unique_ptr<SimpleTracker> simple_tracker_; std::unique_ptr<QuadParticleReferenceController> reference_generator_; std::unique_ptr<VisualServoingReferenceConnectorT> visual_servoing_connector_; std::unique_ptr<DDPQuadMPCController> mpc_controller_; std::unique_ptr<MPCControllerQuadConnector> quad_mpc_connector_; tf::Transform tracking_offset_transform_; ThrustGainEstimator thrust_gain_estimator_; QuadMPCControllerConfig mpc_config_; ParticleReferenceConfig particle_reference_config_; double tol_; }; TEST_F(VisualServoingReferenceConnectorTests, Constructor) {} TEST_F(VisualServoingReferenceConnectorTests, InitializationTest) { // ASSERT_EQ(quad_mpc_connector_->getGoal(), nullptr); tf::Transform tracker_pose; tracker_pose.setIdentity(); tracker_pose.setOrigin(tf::Vector3(1, 1, 1)); simple_tracker_->setTargetPoseGlobalFrame(tracker_pose); simple_tracker_->setTrackingIsValid(true); visual_servoing_connector_->setGoal(PositionYaw()); visual_servoing_connector_->initialize(); auto reference = quad_mpc_connector_->getGoal(); auto state_control = reference->atTime(20); Eigen::VectorXd goal = state_control.first; ASSERT_VEC_NEAR(tracker_pose.getOrigin(), tf::Vector3(goal[0], goal[1], goal[2]), 1e-3); ASSERT_NEAR(goal[3], 0, 1e-2); ASSERT_NEAR(goal[4], 0, 1e-2); ASSERT_NEAR(goal[5], M_PI / 2.0, 1e-2); } TEST_F(VisualServoingReferenceConnectorTests, CriticalRun) { visual_servoing_connector_->setGoal(PositionYaw()); // make tracking invalid: simple_tracker_->setTrackingIsValid(false); // Run connector visual_servoing_connector_->run(); ASSERT_EQ(visual_servoing_connector_->getStatus(), ControllerStatus::Critical); } TEST_F(VisualServoingReferenceConnectorTests, RunUntilConvergence) { // set tracking goal tf::Transform tracked_pose(tf::createQuaternionFromRPY(0, 0, 0.5), tf::Vector3(1, -0.1, 0.5)); PositionYaw goal_relative_pose(1, 0, 0, 0.5); runUntilConvergence(tracked_pose, goal_relative_pose); } TEST_F(VisualServoingReferenceConnectorTests, RunUntilConvergenceNonZeroRollPitch) { // set tracking goal tf::Transform tracked_pose(tf::createQuaternionFromRPY(0.1, -0.1, 0.2), tf::Vector3(1, -0.05, 0.5)); PositionYaw goal_relative_pose(1, 0, 0, 0.5); runUntilConvergence(tracked_pose, goal_relative_pose); } int main(int argc, char **argv) { testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } <|endoftext|>
<commit_before>#include "iApp.h" #include "bbcConfig.h" #include "Poco/DateTimeParser.h" string iApp::app_name = "iApp"; string iApp::app_version = "1.0.0"; // Archive (compress) logs that are 1MB #define IAPP_DEF_LOG_SIZE_ARCH_KB_MAX 1024 using namespace bbc::utils; iApp::iApp(string _app_name, string _app_version, bool _log_to_file, bool _archive_logs) { if(!Config::instance()->load_success){ ofLogError("Config XML failed to load") << Config::data_file_path; }else{ ofLogNotice("Config XML loaded!") << Config::data_file_path; } auto_hide_cursor = true; cursor_visible = true; keep_cursor_hidden = false; // a lock header_logged = false; cursor_duration_ms = 3000; if(_app_name != "") app_name = _app_name; if(_app_version != "") app_version = _app_version; log_to_file = _log_to_file; archive_logs = _archive_logs; if(CONFIG_GET("log", "to_file", false)) { if(!log_to_file) { // not already setup log_to_file = true; logSetup(CONFIG_GET("log", "append", true)); logHeader(); // relog header so it gets to file } }else{ logSetup(); logHeader(); } ofSetLogLevel((ofLogLevel)CONFIG_GET("log", "level", (int)OF_LOG_NOTICE)); if(Config::instance()->attributeExists("config:window", "fps")) { int fps = CONFIG_GET("window", "fps", 60); ofSetFrameRate(fps); ofLogNotice("iApp set") << "fps=" << fps; } bool vs = CONFIG_GET("window", "vertical_sync", true); ofSetVerticalSync(vs); ofLogNotice("iApp set") << "vertical_sync=" << vs; // NOTE: to get full fps, dont specify fps and set vertical_sync="0" if(CONFIG_GET("window", "fullscreen", true)){ ofToggleFullscreen(); } cursor_timer = ofGetElapsedTimeMillis() + cursor_duration_ms; if(CONFIG_GET("mouse", "hide", false)) { // override auto hide cursor auto_hide_cursor = false; hideCursor(true); }else{ // showCursor(); // work around 0.8.4 bug: https://github.com/openframeworks/openFrameworks/issues/3052#issuecomment-63941074 } auto_shutdown = CONFIG_GET("shutdown", "enabled", false); if(auto_shutdown) { // override auto hide cursor string time_str = CONFIG_GET("shutdown", "time", "20:20"); ofLogNotice("auto_shutdown setting up with time") << time_str; Poco::LocalDateTime now; int time_zone_dif = now.tzd(); Poco::DateTime t = Poco::DateTimeParser::parse("%H:%M:%S", time_str, time_zone_dif); Poco::LocalDateTime next(now.year(), now.month(), now.day(), t.hour(), t.minute(), t.second()); if(next < now) { ofLogNotice("Shutdown time already elapsed for today making it for tomorrow"); // Add a day Poco::Timespan dif(0, 24, 0, 0, 0); shutdown_time = next + dif; }else{ shutdown_time = next; } } } void iApp::setup() { ofBaseApp::setup(); ofLogNotice("iApp:setup"); // NOT SURE THIS WILL WORK? } void iApp::draw(ofEventArgs & args) { ofBaseApp::draw(args); } void iApp::update(ofEventArgs& args) { ofBaseApp::update(args); if(auto_hide_cursor) cursorCheck(); if(keep_cursor_hidden) hideCursor(); if(auto_shutdown) { Poco::LocalDateTime now; if( now > shutdown_time && canAutoShutdownNow() ) { ofLogWarning("iApp: AUTO SHUTDOWN was scheduled for now. Terminating app."); ofExit(); } } } bool iApp::canAutoShutdownNow() { return true; } void iApp::cursorCheck() { // cout << "check cursor " << ofGetElapsedTimeMillis() << endl; if(cursor_visible) { if(ofGetElapsedTimeMillis() >= cursor_timer) { // its been still long enough to auto hide it hideCursor(); // cout << " hideCursor " << ofGetElapsedTimeMillis() << endl; // cursor_visible = false; } } } void iApp::toggleCursor() { if(cursor_visible) { hideCursor(); }else{ showCursor(); } } void iApp::hideCursor(bool permanent) { // ofLogNotice("iApp::hideCursor"); // Cursor show and hide not working on mac in 0.8.0 : using workaroud from http://forum.openframeworks.cc/t/ofhidecursor-not-working-on-osx-10-8-v0-8-0/13379/3 // Is working in 0.8.1 so do a OF compile check here //#ifdef __APPLE__ // CGDisplayHideCursor(NULL); // #else ofHideCursor(); // #endif cursor_visible = false; if(permanent) keep_cursor_hidden = true; } void iApp::showCursor() { ofLogNotice("iApp::showCursor"); //#ifdef __APPLE__ // CGDisplayShowCursor(NULL); // #else ofShowCursor(); //#endif cursor_visible = true; if(keep_cursor_hidden) keep_cursor_hidden = false; } void iApp::cursorUpdate() { // reset the timer that was counting down to when it restarts // cout << "cursorUpdate " << ofGetElapsedTimeMillis() << endl; if(!cursor_visible) { // >> why?? // cursor_visible = true; showCursor(); } cursor_timer = ofGetElapsedTimeMillis() + cursor_duration_ms; // reset timer hid it after 3 seconds of no movement } //------------------------------------------------------------------------------------------------------ void iApp::keyPressed(ofKeyEventArgs & key) { ofBaseApp::keyPressed(key); } void iApp::keyReleased(ofKeyEventArgs & key) { ofBaseApp::keyReleased(key); } //------------------------------------------------------------------------------------------------------ void iApp::mouseMoved( ofMouseEventArgs & mouse ) { ofBaseApp::mouseMoved(mouse); if(auto_hide_cursor) cursorUpdate(); } void iApp::mouseDragged( ofMouseEventArgs & mouse ) { ofBaseApp::mouseDragged(mouse); if(auto_hide_cursor) cursorUpdate(); } void iApp::mousePressed( ofMouseEventArgs & mouse ) { ofBaseApp::mousePressed(mouse); if(auto_hide_cursor) cursorUpdate(); } void iApp::mouseReleased( ofMouseEventArgs & mouse ) { ofBaseApp::mouseReleased(mouse); } //------------------------------------------------------------------------------------------------------ void iApp::windowResized(ofResizeEventArgs & resize) { ofBaseApp::windowResized(resize); } void iApp::dragEvent(ofDragInfo dragInfo) { ofBaseApp::dragEvent(dragInfo); } void iApp::gotMessage(ofMessage msg){ ofBaseApp::gotMessage(msg); } void iApp::exit(ofEventArgs & args) { ofBaseApp::exit(args); logFooter(); ofLogToConsole(); // reset logging to file } //------------------------------------------------------------------------------------------------------ void iApp::drawCalibration(int alpha) { /* Draw a screen calibration graphic, useful for projection calibration, */ ofPushStyle(); float sw = 2.0f; ofSetLineWidth(sw); float w = ofGetWidth(); float h = ofGetHeight(); float cx = w / 2.0; float cy = h / 2.0; float hsw = sw / 2.0; ofSetCircleResolution(36); ofSetColor(255, alpha); ofNoFill(); // border ofRectMode(OF_RECTMODE_CORNER); ofDrawRectangle(hsw, hsw, w-sw, h-sw); // diagonal lines ofDrawLine(hsw, hsw, w+hsw, h-hsw); ofDrawLine(-hsw, h-hsw, w-hsw, hsw); // centre lines ofDrawLine(cx, 0, cx, h); ofDrawLine(0, cy, w, cy); // horizontal 1/4 lines ofDrawLine(0, h/4, w, h/4); ofDrawLine(0, h-h/4, w, h-h/4); // Draw centre rect & circle ofRectMode(OF_RECTMODE_CENTER); float dim = min(w, h) * .66f; ofDrawEllipse(cx, cy, dim, dim); ofSetLineWidth(1.0f); // Draw circles at the sides int n = 8; float mini_rad = h / n; float y; for(int i = 0; i<n-1; i++) { y = (mini_rad)+(i*mini_rad); int c = i % 4; switch(c) { case 0: ofSetColor(255, alpha); break; case 1: ofSetColor(255,0,0, alpha); break; case 2: ofSetColor(0,255,0, alpha); break; case 3: ofSetColor(0,0,255, alpha); break; } ofDrawEllipse(0, y, mini_rad, mini_rad); // LHS ofDrawEllipse(w, y, mini_rad, mini_rad); // RHS } // Draw more comprehensive grid // do this at the ratio of the screen? // TODO: make the ratio dynamic too reading getWidth and getHeight float wc = 16.0f; float hc = 9.0f; float grid_x = w / wc; float grid_y = h / hc; ofSetColor(255, alpha); // vertical lines for(int col = 1; col < wc; col++) { int gx = round(col * grid_x); ofDrawLine(gx, 0, gx, h); } // horizontal lines for(int row = 1; row < hc; row++) { int gy = round(row * grid_y); ofDrawLine(0, gy, w, gy); } ofPopStyle(); } //----------------------------------------------------------------------------- void iApp::logSetup(bool appending) { if(log_to_file) { string log_name = app_name + ".log"; if(archive_logs) { ofFile f("logs/" + log_name); if(f.exists()) { uint64_t sz_kb = f.getSize() / 1024; if(sz_kb >= IAPP_DEF_LOG_SIZE_ARCH_KB_MAX) { ofFile parent_dir(f.getEnclosingDirectory()); #if defined(TARGET_OSX) string zip_cmd = "gzip '" + f.getAbsolutePath() + "'"; ofLogNotice("ARCHIVING LOG with") << zip_cmd; string zip_result = ofSystem(zip_cmd); ofLogNotice("zip_result") << zip_result; string rename_cmd = "mv '" + f.getAbsolutePath() + ".gz' '" + parent_dir.getAbsolutePath() + "/" + ofGetTimestampString("%Y-%m-%d-%H-%M-%S") + "_" + app_name + ".log.gz'"; ofLogNotice("RENAMING LOG ARCHIVE with") << rename_cmd; string rename_result = ofSystem(rename_cmd); ofLogNotice("rename_result") << rename_result; #endif #if defined(TARGET_WIN32) // TODO: Win could use: win7 cmd option: http://superuser.com/questions/110991/can-you-zip-a-file-from-the-command-prompt-using-only-windows-built-in-capabili #endif } } } ofLogToFile("logs/" + log_name, appending); } int level = CONFIG_GET("log", "level", 1); // VERBOSE = 0 NOTICE = 1 WARNING = 2 ERROR = 3 FATAL_ERROR = 4 SILENT = 5 if(level >= 0 && level <= (int)OF_LOG_SILENT) { ofSetLogLevel( (ofLogLevel)level ); } } void iApp::logHeader() { ofLogNotice(""); ofLogNotice("--------------------------------------"); ofLogNotice("--- START ") << app_name << " app v" << app_version << " @ " << ofGetTimestampString("%H:%M:%S %d-%m-%Y"); ofLogNotice("--- ") << "oF:" << OF_VERSION_MAJOR << "." << OF_VERSION_MINOR << "." << OF_VERSION_PATCH << ", platform:" << ofGetTargetPlatform(); // TODO: log OS version and name + opengl properties, free gpu memory? ofLogNotice("--------------------------------------"); header_logged = true; } void iApp::logFooter() { ofLogNotice("--------------------------------------"); ofLogNotice("--- STOP ") << app_name << " app v" << app_version << " @ " << ofGetTimestampString("%H:%M:%S %d-%m-%Y"); ofLogNotice("--------------------------------------"); } //----------------------------------------------------------------------------- <commit_msg>log to file refactor, adding win 10 file archiving<commit_after>#include "iApp.h" #include "bbcConfig.h" #include "Poco/DateTimeParser.h" string iApp::app_name = "iApp"; string iApp::app_version = "1.0.0"; // Archive (compress) logs that are 1MB #define IAPP_DEF_LOG_SIZE_ARCH_KB_MAX 1024 using namespace bbc::utils; iApp::iApp(string _app_name, string _app_version, bool _log_to_file, bool _archive_logs) { if(!Config::instance()->load_success){ ofLogError("Config XML failed to load") << Config::data_file_path; }else{ ofLogNotice("Config XML loaded!") << Config::data_file_path; } auto_hide_cursor = true; cursor_visible = true; keep_cursor_hidden = false; // a lock header_logged = false; cursor_duration_ms = 3000; if(_app_name != "") app_name = _app_name; if(_app_version != "") app_version = _app_version; log_to_file = _log_to_file; archive_logs = _archive_logs; if(CONFIG_GET("log", "to_file", false)) { if(!log_to_file) { // not already setup log_to_file = true; logSetup(CONFIG_GET("log", "append", true)); logHeader(); // relog header so it gets to file } }else{ logSetup(); logHeader(); } ofSetLogLevel((ofLogLevel)CONFIG_GET("log", "level", (int)OF_LOG_NOTICE)); if(Config::instance()->attributeExists("config:window", "fps")) { int fps = CONFIG_GET("window", "fps", 60); ofSetFrameRate(fps); ofLogNotice("iApp set") << "fps=" << fps; } bool vs = CONFIG_GET("window", "vertical_sync", true); ofSetVerticalSync(vs); ofLogNotice("iApp set") << "vertical_sync=" << vs; // NOTE: to get full fps, dont specify fps and set vertical_sync="0" if(CONFIG_GET("window", "fullscreen", true)){ ofToggleFullscreen(); } cursor_timer = ofGetElapsedTimeMillis() + cursor_duration_ms; if(CONFIG_GET("mouse", "hide", false)) { // override auto hide cursor auto_hide_cursor = false; hideCursor(true); }else{ // showCursor(); // work around 0.8.4 bug: https://github.com/openframeworks/openFrameworks/issues/3052#issuecomment-63941074 } auto_shutdown = CONFIG_GET("shutdown", "enabled", false); if(auto_shutdown) { // override auto hide cursor string time_str = CONFIG_GET("shutdown", "time", "20:20"); ofLogNotice("auto_shutdown setting up with time") << time_str; Poco::LocalDateTime now; int time_zone_dif = now.tzd(); Poco::DateTime t = Poco::DateTimeParser::parse("%H:%M:%S", time_str, time_zone_dif); Poco::LocalDateTime next(now.year(), now.month(), now.day(), t.hour(), t.minute(), t.second()); if(next < now) { ofLogNotice("Shutdown time already elapsed for today making it for tomorrow"); // Add a day Poco::Timespan dif(0, 24, 0, 0, 0); shutdown_time = next + dif; }else{ shutdown_time = next; } } } void iApp::setup() { ofBaseApp::setup(); ofLogNotice("iApp:setup"); // NOT SURE THIS WILL WORK? } void iApp::draw(ofEventArgs & args) { ofBaseApp::draw(args); } void iApp::update(ofEventArgs& args) { ofBaseApp::update(args); if(auto_hide_cursor) cursorCheck(); if(keep_cursor_hidden) hideCursor(); if(auto_shutdown) { Poco::LocalDateTime now; if( now > shutdown_time && canAutoShutdownNow() ) { ofLogWarning("iApp: AUTO SHUTDOWN was scheduled for now. Terminating app."); ofExit(); } } } bool iApp::canAutoShutdownNow() { return true; } void iApp::cursorCheck() { // cout << "check cursor " << ofGetElapsedTimeMillis() << endl; if(cursor_visible) { if(ofGetElapsedTimeMillis() >= cursor_timer) { // its been still long enough to auto hide it hideCursor(); // cout << " hideCursor " << ofGetElapsedTimeMillis() << endl; // cursor_visible = false; } } } void iApp::toggleCursor() { if(cursor_visible) { hideCursor(); }else{ showCursor(); } } void iApp::hideCursor(bool permanent) { // ofLogNotice("iApp::hideCursor"); // Cursor show and hide not working on mac in 0.8.0 : using workaroud from http://forum.openframeworks.cc/t/ofhidecursor-not-working-on-osx-10-8-v0-8-0/13379/3 // Is working in 0.8.1 so do a OF compile check here //#ifdef __APPLE__ // CGDisplayHideCursor(NULL); // #else ofHideCursor(); // #endif cursor_visible = false; if(permanent) keep_cursor_hidden = true; } void iApp::showCursor() { ofLogNotice("iApp::showCursor"); //#ifdef __APPLE__ // CGDisplayShowCursor(NULL); // #else ofShowCursor(); //#endif cursor_visible = true; if(keep_cursor_hidden) keep_cursor_hidden = false; } void iApp::cursorUpdate() { // reset the timer that was counting down to when it restarts // cout << "cursorUpdate " << ofGetElapsedTimeMillis() << endl; if(!cursor_visible) { // >> why?? // cursor_visible = true; showCursor(); } cursor_timer = ofGetElapsedTimeMillis() + cursor_duration_ms; // reset timer hid it after 3 seconds of no movement } //------------------------------------------------------------------------------------------------------ void iApp::keyPressed(ofKeyEventArgs & key) { ofBaseApp::keyPressed(key); } void iApp::keyReleased(ofKeyEventArgs & key) { ofBaseApp::keyReleased(key); } //------------------------------------------------------------------------------------------------------ void iApp::mouseMoved( ofMouseEventArgs & mouse ) { ofBaseApp::mouseMoved(mouse); if(auto_hide_cursor) cursorUpdate(); } void iApp::mouseDragged( ofMouseEventArgs & mouse ) { ofBaseApp::mouseDragged(mouse); if(auto_hide_cursor) cursorUpdate(); } void iApp::mousePressed( ofMouseEventArgs & mouse ) { ofBaseApp::mousePressed(mouse); if(auto_hide_cursor) cursorUpdate(); } void iApp::mouseReleased( ofMouseEventArgs & mouse ) { ofBaseApp::mouseReleased(mouse); } //------------------------------------------------------------------------------------------------------ void iApp::windowResized(ofResizeEventArgs & resize) { ofBaseApp::windowResized(resize); } void iApp::dragEvent(ofDragInfo dragInfo) { ofBaseApp::dragEvent(dragInfo); } void iApp::gotMessage(ofMessage msg){ ofBaseApp::gotMessage(msg); } void iApp::exit(ofEventArgs & args) { ofBaseApp::exit(args); logFooter(); ofLogToConsole(); // reset logging to file } //------------------------------------------------------------------------------------------------------ void iApp::drawCalibration(int alpha) { /* Draw a screen calibration graphic, useful for projection calibration, */ ofPushStyle(); float sw = 2.0f; ofSetLineWidth(sw); float w = ofGetWidth(); float h = ofGetHeight(); float cx = w / 2.0; float cy = h / 2.0; float hsw = sw / 2.0; ofSetCircleResolution(36); ofSetColor(255, alpha); ofNoFill(); // border ofRectMode(OF_RECTMODE_CORNER); ofDrawRectangle(hsw, hsw, w-sw, h-sw); // diagonal lines ofDrawLine(hsw, hsw, w+hsw, h-hsw); ofDrawLine(-hsw, h-hsw, w-hsw, hsw); // centre lines ofDrawLine(cx, 0, cx, h); ofDrawLine(0, cy, w, cy); // horizontal 1/4 lines ofDrawLine(0, h/4, w, h/4); ofDrawLine(0, h-h/4, w, h-h/4); // Draw centre rect & circle ofRectMode(OF_RECTMODE_CENTER); float dim = min(w, h) * .66f; ofDrawEllipse(cx, cy, dim, dim); ofSetLineWidth(1.0f); // Draw circles at the sides int n = 8; float mini_rad = h / n; float y; for(int i = 0; i<n-1; i++) { y = (mini_rad)+(i*mini_rad); int c = i % 4; switch(c) { case 0: ofSetColor(255, alpha); break; case 1: ofSetColor(255,0,0, alpha); break; case 2: ofSetColor(0,255,0, alpha); break; case 3: ofSetColor(0,0,255, alpha); break; } ofDrawEllipse(0, y, mini_rad, mini_rad); // LHS ofDrawEllipse(w, y, mini_rad, mini_rad); // RHS } // Draw more comprehensive grid // do this at the ratio of the screen? // TODO: make the ratio dynamic too reading getWidth and getHeight float wc = 16.0f; float hc = 9.0f; float grid_x = w / wc; float grid_y = h / hc; ofSetColor(255, alpha); // vertical lines for(int col = 1; col < wc; col++) { int gx = round(col * grid_x); ofDrawLine(gx, 0, gx, h); } // horizontal lines for(int row = 1; row < hc; row++) { int gy = round(row * grid_y); ofDrawLine(0, gy, w, gy); } ofPopStyle(); } //----------------------------------------------------------------------------- void iApp::logSetup(bool appending) { if(log_to_file) { string log_name = app_name + ".log"; if(archive_logs) { ofFile log_file("logs/" + log_name); if(log_file.exists()) { uint64_t sz_kb = log_file.getSize() / 1024; if(sz_kb >= IAPP_DEF_LOG_SIZE_ARCH_KB_MAX) { ofFile parent_dir(log_file.getEnclosingDirectory()); #if defined(TARGET_OSX) string zip_cmd = "gzip '" + log_file.getAbsolutePath() + "'"; ofLogNotice("ARCHIVING LOG with") << zip_cmd; string zip_result = ofSystem(zip_cmd); ofLogNotice("zip_result") << zip_result; string rename_cmd = "mv '" + log_file.getAbsolutePath() + ".gz' '" + parent_dir.getAbsolutePath() + "/" + ofGetTimestampString("%Y-%m-%d-%H-%M-%S") + "_" + app_name + ".log.gz'"; ofLogNotice("RENAMING LOG ARCHIVE with") << rename_cmd; string rename_result = ofSystem(rename_cmd); ofLogNotice("rename_result") << rename_result; #endif #if defined(TARGET_WIN32) // TODO: Win7 could use: http://superuser.com/questions/110991/can-you-zip-a-file-from-the-command-prompt-using-only-windows-built-in-capabili // Assume windows 10, which comes with tar.exe // https://superuser.com/questions/201371/create-zip-folder-from-the-command-line-windows // tar.exe -a -c -f out.zip in.txt // string input_path = log_file.getAbsolutePath(); stringstream output; output << parent_dir.getAbsolutePath() << "\\" << ofGetTimestampString("%Y-%m-%d-%H-%M-%S") << "_" << app_name << ".log.zip"; string output_path = output.str(); ofLogToConsole(); string zip_cmd = "tar.exe -acf \"" + output_path + "\" \"" + input_path + "\""; // Note: This will currently have the fullpath to the log inside the zip // TODO: fix this above // e.g, tar.exe -cvzf "E:\userfiles\Documents\........\bin\data\logs\2020-06-27-10-32-28_APPNAME.log.zip" "E:\userfiles\Documents\........\bin\data\logs\APPNAME.log" ofLogNotice("ARCHIVING LOG with") << zip_cmd; string zip_result = ofSystem(zip_cmd); // ofLogNotice("zip_result") << zip_result; // remove the original log file (f bool success = log_file.remove(); ofLogNotice("Existing log file removed") << success; #endif } } } string log_path = "logs/" + log_name; ofLogToConsole(); ofLogNotice(app_name) << "Logging output to file:" << log_path; ofLogToFile(log_path, appending); } int level = CONFIG_GET("log", "level", 1); // VERBOSE = 0 NOTICE = 1 WARNING = 2 ERROR = 3 FATAL_ERROR = 4 SILENT = 5 if(level >= 0 && level <= (int)OF_LOG_SILENT) { ofSetLogLevel( (ofLogLevel)level ); } } void iApp::logHeader() { ofLogNotice(""); ofLogNotice("--------------------------------------"); ofLogNotice("--- START ") << app_name << " app v" << app_version << " @ " << ofGetTimestampString("%H:%M:%S %d-%m-%Y"); ofLogNotice("--- ") << "oF:" << OF_VERSION_MAJOR << "." << OF_VERSION_MINOR << "." << OF_VERSION_PATCH << ", platform:" << ofGetTargetPlatform(); // TODO: log OS version and name + opengl properties, free gpu memory? ofLogNotice("--------------------------------------"); header_logged = true; } void iApp::logFooter() { ofLogNotice("--------------------------------------"); ofLogNotice("--- STOP ") << app_name << " app v" << app_version << " @ " << ofGetTimestampString("%H:%M:%S %d-%m-%Y"); ofLogNotice("--------------------------------------"); } //----------------------------------------------------------------------------- <|endoftext|>
<commit_before>/* =========================================================================== * The MIT License (MIT) * * Copyright (c) 2016 Jedidiah Buck McCready <jbuckmccready@gmail.com> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * ===========================================================================*/ #include "Models/modelsrepo.h" #include "QmlHelpers/systemintegrator.h" #include <QApplication> #include <QHash> #include <QObject> #include <QQmlApplicationEngine> #include <QQmlContext> #include <QtQml> int main(int argc, char *argv[]) { QApplication app(argc, argv); using namespace staticpendulum; qmlRegisterType<SystemIntegrator>("QmlHelpers", 1, 0, "SystemIntegrator"); qmlRegisterSingletonType<ModelsRepo>("ModelsRepo", 1, 0, "ModelsRepo", &ModelsRepo::qmlInstance); QQmlApplicationEngine engine; // Add import path to resolve Qml modules, note: using qrc path engine.addImportPath("qrc:/Qml/"); engine.rootContext()->setContextProperty("applicationDirPath", qApp->applicationDirPath()); engine.load(QUrl(QLatin1String("qrc:/Qml/Main/Main.qml"))); return app.exec(); } <commit_msg>force use of basic QSG render loop for smoother rendering when resizing the main window<commit_after>/* =========================================================================== * The MIT License (MIT) * * Copyright (c) 2016 Jedidiah Buck McCready <jbuckmccready@gmail.com> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * ===========================================================================*/ #include "Models/modelsrepo.h" #include "QmlHelpers/systemintegrator.h" #include <QApplication> #include <QHash> #include <QObject> #include <QQmlApplicationEngine> #include <QQmlContext> #include <QtQml> int main(int argc, char *argv[]) { // Smoother rendering when resizing the window using the basic render loop // see: http://doc.qt.io/qt-5/qtquick-visualcanvas-scenegraph.html // for details of how it works qputenv("QSG_RENDER_LOOP", "basic"); QApplication app(argc, argv); using namespace staticpendulum; qmlRegisterType<SystemIntegrator>("QmlHelpers", 1, 0, "SystemIntegrator"); qmlRegisterSingletonType<ModelsRepo>("ModelsRepo", 1, 0, "ModelsRepo", &ModelsRepo::qmlInstance); QQmlApplicationEngine engine; // Add import path to resolve Qml modules, note: using qrc path engine.addImportPath("qrc:/Qml/"); engine.rootContext()->setContextProperty("applicationDirPath", qApp->applicationDirPath()); engine.load(QUrl(QLatin1String("qrc:/Qml/Main/Main.qml"))); return app.exec(); } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: bootstrap.hxx,v $ * * $Revision: 1.12 $ * * last change: $Author: jb $ $Date: 2001-04-05 14:31:45 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef CONFIGMGR_BOOTSTRAP_HXX_ #define CONFIGMGR_BOOTSTRAP_HXX_ #ifndef _COM_SUN_STAR_UNO_REFERENCE_HXX_ #include <com/sun/star/uno/Reference.hxx> #endif #ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_ #include <com/sun/star/uno/Sequence.hxx> #endif #ifndef _COM_SUN_STAR_UNO_ANY_HXX_ #include <com/sun/star/uno/Any.hxx> #endif #ifndef _COM_SUN_STAR_LANG_ILLEGALARGUMENTEXCEPTION_HPP_ #include <com/sun/star/lang/IllegalArgumentException.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_ #include <com/sun/star/lang/XMultiServiceFactory.hpp> #endif #ifndef _RTL_USTRING_HXX_ #include <rtl/ustring.hxx> #endif #ifndef _COMPHELPER_STLTYPES_HXX_ #include <comphelper/stl_types.hxx> #endif namespace osl { class Profile; } namespace configmgr { class IConfigSession; // =================================================================================== #define PORTAL_SESSION_IDENTIFIER "portal" #define REMOTE_SESSION_IDENTIFIER "remote" #define LOCAL_SESSION_IDENTIFIER "local" #define SETUP_SESSION_IDENTIFIER "setup" #define PLUGIN_SESSION_IDENTIFIER "plugin" // =================================================================================== // = ConnectionSettings // =================================================================================== class ConnectionSettings { public: enum SETTING_ORIGIN { SO_SREGISTRY, SO_OVERRIDE, SO_FALLBACK, SO_UNKNOWN }; protected: // ine single setting struct Setting { ::com::sun::star::uno::Any aValue; SETTING_ORIGIN eOrigin; Setting() : eOrigin(SO_UNKNOWN) { } Setting(const ::rtl::OUString& _rValue, SETTING_ORIGIN _eOrigin) : aValue(::com::sun::star::uno::makeAny(_rValue)), eOrigin(_eOrigin) { } Setting(const sal_Int32 _nValue, SETTING_ORIGIN _eOrigin) : aValue(::com::sun::star::uno::makeAny(_nValue)), eOrigin(_eOrigin) { } Setting(const ::com::sun::star::uno::Any& _rValue, SETTING_ORIGIN _eOrigin) : aValue(_rValue), eOrigin(_eOrigin) { } }; DECLARE_STL_USTRINGACCESS_MAP( Setting, SettingsImpl ); SettingsImpl m_aImpl; ::osl::Profile* m_pSRegistry; sal_Bool m_bFoundRegistry; public: /// default ctor ConnectionSettings(); /// dtor ~ConnectionSettings(); /// copy ctor ConnectionSettings(const ConnectionSettings& _rSource); /** construct a settings object. <p>The runtime overrides given will be merged with the settings found in a sversion.ini (sversionrc), if any. The former overrule the latter</p> */ ConnectionSettings(const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& _rRuntimeOverrides ); /// merge the given overrides into a new ConnectionSettings object ConnectionSettings& mergeOverrides(const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& _rOverrides); /// merge the given overrides into the object itself ConnectionSettings createMergedSettings(const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& _rOverrides) const { return ConnectionSettings(*this).mergeOverrides(_rOverrides); } // check setting existence sal_Bool hasRegistry() const { return m_bFoundRegistry; } sal_Bool hasUser() const; sal_Bool hasPassword() const; sal_Bool hasLocale() const; sal_Bool hasAsyncSetting() const; sal_Bool hasServer() const; sal_Bool hasPort() const; sal_Bool hasTimeout() const; sal_Bool hasService() const; sal_Bool isLocalSession() const; sal_Bool isRemoteSession() const; sal_Bool isValidSourcePath() const; sal_Bool isValidUpdatePath() const; // get a special setting ::rtl::OUString getSessionType() const; ::rtl::OUString getUser() const; ::rtl::OUString getPassword() const; ::rtl::OUString getLocale() const; ::rtl::OUString getSourcePath() const; ::rtl::OUString getUpdatePath() const; ::rtl::OUString getServer() const; ::rtl::OUString getService() const; sal_Int32 getPort() const; sal_Int32 getTimeout() const; sal_Bool getAsyncSetting() const; // make sure this behaves as a user session void setUserSession(); void setUserSession(const ::rtl::OUString& _rRemoteServiceName); // make sure this behaves as an administrative session void setAdminSession(); void setAdminSession(const ::rtl::OUString& _rRemoteServiceName); // set a new session type. Must be one of the *_SESSION_IDENTIFIER defines void setSessionType(const ::rtl::OUString& _rSessionIdentifier); // set a desired service, only necessary in remote environments sal_Bool isServiceRequired() const; void setService(const ::rtl::OUString& _rService); // set this to a wildcard locale void setAnyLocale(); IConfigSession* ConnectionSettings::createConnection( ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > const& _rxServiceMgr) const; protected: void construct(const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& _rOverrides); // transfer runtime overwrites into m_aImpl. Existent settings will be overwritten. void implTranslate(const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& _rOverrides) throw (::com::sun::star::lang::IllegalArgumentException); /** normalize a path setting, delete it if the value could not be normalized @return <TRUE/> if the setting exists and is a valid path */ sal_Bool implNormalizePathSetting(const sal_Char* _pSetting); // translate old settings, which exist for compatiblity only, into new ones void implTranslateCompatibilitySettings(); // if we do not already have the given config path setting, ensure that it exists (calculated relative to a given path) void ensureConfigPath(const sal_Char* _pSetting, const ::rtl::OUString& _rBasePath, const sal_Char* _pRelative); sal_Bool haveSetting(const sal_Char* _pName) const; void putSetting(const sal_Char* _pName, const Setting& _rSetting); void clearSetting(const sal_Char* _pName); ::rtl::OUString getStringSetting(const sal_Char* _pName) const; sal_Int32 getIntSetting(const sal_Char* _pName) const; sal_Bool getBoolSetting(const sal_Char* _pName) const; Setting getSetting(const sal_Char* _pName) const; Setting getMaybeSetting(const sal_Char* _pName) const; ::rtl::OUString getProfileStringItem(const sal_Char* _pSection, const sal_Char* _pKey); sal_Int32 getProfileIntItem(const sal_Char* _pSection, const sal_Char* _pKey); private: // ensures that m_aImpl contains a session type // to be called from within construct only void implDetermineSessionType(); // collect settings from the sregistry, put them into m_aImpl, if not overruled by runtime settings void implCollectSRegistrySetting(); // clear items which are not relevant because of the session type origin void clearIrrelevantItems(); }; } #endif // CONFIGMGR_BOOTSTRAP_HXX_ <commit_msg>#81412# Cleaned up bootstrap settings handling; Added error recognition of bootstrap handling; Added new parameter 'reinitialize'<commit_after>/************************************************************************* * * $RCSfile: bootstrap.hxx,v $ * * $Revision: 1.13 $ * * last change: $Author: jb $ $Date: 2001-05-18 16:13:30 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef CONFIGMGR_BOOTSTRAP_HXX_ #define CONFIGMGR_BOOTSTRAP_HXX_ #ifndef _COM_SUN_STAR_UNO_REFERENCE_HXX_ #include <com/sun/star/uno/Reference.hxx> #endif #ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_ #include <com/sun/star/uno/Sequence.hxx> #endif #ifndef _COM_SUN_STAR_UNO_ANY_HXX_ #include <com/sun/star/uno/Any.hxx> #endif #ifndef _COM_SUN_STAR_LANG_ILLEGALARGUMENTEXCEPTION_HPP_ #include <com/sun/star/lang/IllegalArgumentException.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_ #include <com/sun/star/lang/XMultiServiceFactory.hpp> #endif #ifndef _RTL_USTRING_HXX_ #include <rtl/ustring.hxx> #endif #include <map> namespace osl { class Profile; } namespace configmgr { class IConfigSession; // =================================================================================== namespace uno = ::com::sun::star::uno; namespace lang = ::com::sun::star::lang; using ::rtl::OUString; using ::rtl::OString; // =================================================================================== #define PORTAL_SESSION_IDENTIFIER "portal" #define REMOTE_SESSION_IDENTIFIER "remote" #define LOCAL_SESSION_IDENTIFIER "local" #define SETUP_SESSION_IDENTIFIER "setup" #define PLUGIN_SESSION_IDENTIFIER "plugin" // =================================================================================== enum BootstrapResult { BOOTSTRAP_DATA_OK = 0, MISSING_BOOTSTRAP_FILE, INVALID_BOOTSTRAP_DATA, INVALID_INSTALLATION, BOOTSTRAP_FAILURE }; // =================================================================================== extern OUString getBootstrapErrorMessage( BootstrapResult rc ); extern void raiseBootstrapException( BootstrapResult rc, OUString const& sURL, uno::Reference< uno::XInterface > xContext ); extern void raiseBootstrapException( class BootstrapSettings const& rBootstrapData, uno::Reference< uno::XInterface > xContext ); // =================================================================================== // = Settings // =================================================================================== class Settings { public: enum Origin { SO_UNKNOWN, SO_FALLBACK, SO_INIFILE, SO_OVERRIDE, SO_DEFAULT, SO_ADJUSTMENT, SO_MANUAL }; typedef OString Name; // a single setting struct Setting { uno::Any aValue; Origin eOrigin; Setting() : aValue(), eOrigin(SO_UNKNOWN) { } Setting(const OUString& _rValue, Origin _eOrigin) : aValue(uno::makeAny(_rValue)), eOrigin(_eOrigin) { } Setting(const sal_Int32 _nValue, Origin _eOrigin) : aValue(uno::makeAny(_nValue)), eOrigin(_eOrigin) { } Setting(const uno::Any& _rValue, Origin _eOrigin) : aValue(_rValue), eOrigin(_eOrigin) { } uno::Any value() const { return aValue; } Origin origin() const { return eOrigin; }; }; protected: typedef std::map< Name, Setting > SettingsImpl; SettingsImpl m_aImpl; public: typedef SettingsImpl::const_iterator Iterator; public: /// default ctor Settings(); /** construct a settings object containing the given overrides */ Settings(const uno::Sequence< uno::Any >& _rOverrides, Origin _eOrigin = SO_OVERRIDE); /// merge the given overrides into the object itself void mergeOverrides(const Settings& _rOverrides); // add settings void override(const uno::Sequence< uno::Any >& _rOverrides, Origin _eOrigin = SO_OVERRIDE); // check setting existence sal_Bool haveSetting(Name const& _pName) const; void putSetting(Name const& _pName, const Setting& _rSetting); void clearSetting(Name const& _pName); OUString getStringSetting(Name const& _pName) const; sal_Int32 getIntSetting(Name const& _pName) const; sal_Bool getBoolSetting(Name const& _pName) const; Setting getSetting(Name const& _pName) const; Setting getMaybeSetting(Name const& _pName) const; Iterator begin() const { return m_aImpl.begin(); } Iterator end() const { return m_aImpl.end(); } void swap(Settings& _rOther) { m_aImpl.swap(_rOther.m_aImpl); } private: // transfer runtime overwrites into m_aImpl. Existent settings will be overwritten. void implTranslate(const uno::Sequence< uno::Any >& _rOverrides, Origin _eOrigin) throw (lang::IllegalArgumentException); }; class ConnectionSettings { Settings m_aSettings; ConnectionSettings() : m_aSettings() {}; public: static BootstrapResult findInifile(OUString& _rsInifile); static ConnectionSettings bootstrap(BootstrapResult& rc, OUString& _rsInifile); ConnectionSettings(const uno::Sequence< uno::Any >& _rOverrides, Settings::Origin _eOrigin = Settings::SO_OVERRIDE); /// merge the given overrides into the object itself void mergeOverrides(const Settings& _rOverrides); /// merge the given overrides into the object itself void mergeOverrides(const ConnectionSettings& _rOverrides) { mergeOverrides(_rOverrides.m_aSettings); } void loadFromInifile(osl::Profile & rProfile, Settings::Origin _eOrigin = Settings::SO_INIFILE); void fillFromInifile(osl::Profile & rProfile, Settings::Origin _eOrigin = Settings::SO_INIFILE); bool validate(); bool isComplete() const; bool isComplete(OUString const& aSessionType) const; sal_Bool isSessionTypeKnown() const; sal_Bool hasUser() const; sal_Bool hasPassword() const; sal_Bool hasLocale() const; sal_Bool hasAsyncSetting() const; sal_Bool hasServer() const; sal_Bool hasPort() const; sal_Bool hasTimeout() const; sal_Bool hasService() const; sal_Bool isPlugin() const; sal_Bool isLocalSession() const; sal_Bool isRemoteSession() const; sal_Bool isSourcePathValid() const; sal_Bool isUpdatePathValid() const; sal_Bool hasReinitializeFlag() const; // get a special setting OUString getSessionType() const; OUString getUser() const; OUString getPassword() const; OUString getLocale() const; sal_Bool getAsyncSetting() const; OUString getSourcePath() const; OUString getUpdatePath() const; sal_Bool getReinitializeFlag() const; OUString getServer() const; OUString getService() const; sal_Int32 getPort() const; sal_Int32 getTimeout() const; // make sure this behaves as a user session void setUserSession(); void setUserSession(const OUString& _rRemoteServiceName); // make sure this behaves as an administrative session void setAdminSession(); void setAdminSession(const OUString& _rRemoteServiceName); // set a new session type. Must be one of the *_SESSION_IDENTIFIER defines void setSessionType(const OUString& _rSessionIdentifier, Settings::Origin _eOrigin /*= SO_MANUAL*/); // set a desired service, only necessary in remote environments sal_Bool isServiceRequired() const; void setService(const OUString& _rService, Settings::Origin _eOrigin /*= SO_MANUAL*/); // set this to a wildcard locale void setAnyLocale(Settings::Origin _eOrigin /*= SO_MANUAL*/); IConfigSession* createConnection( uno::Reference< lang::XMultiServiceFactory > const& _rxServiceMgr) const; void swap(ConnectionSettings& _rOther) { m_aSettings.swap(_rOther.m_aSettings); } protected: bool checkSettings() const; /** @return <TRUE/> if the setting exists and is a valid path */ sal_Bool isValidPathSetting(Settings::Name const& _pSetting) const; sal_Bool implPutPathSetting(Settings::Name const& _pSetting, OUString const& _sSystemPath, Settings::Origin _eOrigin); // translate old settings, which exist for compatiblity only, into new ones void implTranslateCompatibilitySettings(); // if we do not already have the given config path setting, ensure that it exists (calculated relative to a given path) sal_Bool ensureConfigPath(Settings::Name const& _pSetting, const OUString& _rBasePath, const sal_Char* _pRelative = NULL); // if we do not already have path settings, ensure that they exists (in an office install) void implAdjustToInstallation(const OUString& _rOfficeInstallPath, const OUString& _rUserInstallPath); private: // collect settings from the sregistry, put them into m_aSettings void implCollectSRegistrySetting(osl::Profile & rProfile, Settings::Origin _eOrigin); static OUString getProfileStringItem(osl::Profile & rProfile, OString const& _pSection, OString const& _pKey, rtl_TextEncoding _nEncoding); static sal_Int32 getProfileIntItem(osl::Profile & rProfile, OString const& _pSection, OString const& _pKey); // ensures that m_aImpl contains a session type void implDetermineSessionType(); // clear items which are not relevant because of the session type origin void implClearIrrelevantItems(); // convenience wrappers for Settings members public: sal_Bool haveSetting(Settings::Name const& _pName) const { return m_aSettings.haveSetting(_pName); } Settings::Setting getSetting(Settings::Name const& _pName) const { return m_aSettings.getSetting(_pName); } // private convenience wrappers for Settings members private: void putSetting(Settings::Name const& _pName, const Settings::Setting& _rSetting) { m_aSettings.putSetting(_pName,_rSetting); } void clearSetting(Settings::Name const& _pName) { m_aSettings.clearSetting(_pName); } }; /* sal_Bool hasRegistry() const { return m_bFoundRegistry; } ::osl::Profile* m_pSRegistry; sal_Bool m_bFoundRegistry; */ class BootstrapSettings { public: OUString url; BootstrapResult status; // order dependency - settings must be last ConnectionSettings settings; BootstrapSettings(); bool hasBootstrapData() const; }; } #endif // CONFIGMGR_BOOTSTRAP_HXX_ <|endoftext|>
<commit_before>#include "bitstream.h" #include <complex> #include "wdsp/wdsp.h" #include "filters.h" #define FS 250000.0 #define FC_0 57000.0 #define IBUFLEN 4096 #define OBUFLEN 128 #define BITBUFLEN 1024 namespace redsea { int sign(double a) { return (a >= 0 ? 1 : 0); } BitStream::BitStream() : tot_errs_(2), reading_frame_(0), counter_(0), subcarr_freq_(FC_0), bit_buffer_(BITBUFLEN), mixer_phi_(0), clock_offset_(0), is_eof_(false), subcarr_lopass_fir_(wdsp::FIR(4000.0 / FS, 127)), subcarr_baseband_(IBUFLEN) { } void BitStream::deltaBit(int b) { bit_buffer_.append(b ^ dbit_); dbit_ = b; } void BitStream::biphase(double acc) { if (sign(acc) != sign(prev_acc_)) { tot_errs_[counter_ % 2] ++; } if (counter_ % 2 == reading_frame_) { deltaBit(sign(acc + prev_acc_)); } if (counter_ == 0) { if (tot_errs_[1 - reading_frame_] < tot_errs_[reading_frame_]) { reading_frame_ = 1 - reading_frame_; } tot_errs_[0] = 0; tot_errs_[1] = 0; } prev_acc_ = acc; counter_ = (counter_ + 1) % 800; } void BitStream::demodulateMoreBits() { int16_t sample[IBUFLEN]; int bytesread = fread(sample, sizeof(int16_t), IBUFLEN, stdin); if (bytesread < IBUFLEN) { is_eof_ = true; return; } for (int i = 0; i < bytesread; i++) { /* Subcarrier downmix & phase recovery */ mixer_phi_ += 2 * M_PI * subcarr_freq_ * (1.0/FS); subcarr_baseband_.appendOverlapFiltered(wdsp::mix(sample[i] / 32768.0, mixer_phi_), subcarr_lopass_fir_); double pll_beta = 16e-3; /* Decimate band-limited signal */ if (numsamples_ % 8 == 0) { std::complex<double> sc_sample = subcarr_baseband_.at(0); subcarr_baseband_.forward(8); double phi1 = arg(sc_sample); if (phi1 >= M_PI_2) { phi1 -= M_PI; } else if (phi1 <= -M_PI_2) { phi1 += M_PI; } mixer_phi_ -= pll_beta * phi1; subcarr_freq_ -= .5 * pll_beta * phi1; /* 1187.5 Hz clock */ double clock_phi = mixer_phi_ / 48.0 + clock_offset_; double lo_clock = (fmod(clock_phi, 2*M_PI) < M_PI ? 1 : -1); /* Clock phase recovery */ if (sign(prev_bb_) != sign(real(sc_sample))) { double d_cphi = fmod(clock_phi, M_PI); if (d_cphi >= M_PI_2) d_cphi -= M_PI; clock_offset_ -= 0.005 * d_cphi; } /* biphase symbol integrate & dump */ acc_ += real(sc_sample) * lo_clock; if (sign(lo_clock) != sign(prevclock_)) { biphase(acc_); acc_ = 0; } prevclock_ = lo_clock; prev_bb_ = real(sc_sample); } numsamples_ ++; } } int BitStream::getNextBit() { while (bit_buffer_.getFillCount() < 1 && !isEOF()) demodulateMoreBits(); return bit_buffer_.getNext(); } bool BitStream::isEOF() const { return is_eof_; } } // namespace redsea <commit_msg>dbg print pll freq<commit_after>#include "bitstream.h" #include <complex> #include "wdsp/wdsp.h" #include "filters.h" #define FS 250000.0 #define FC_0 57000.0 #define IBUFLEN 4096 #define OBUFLEN 128 #define BITBUFLEN 1024 namespace redsea { int sign(double a) { return (a >= 0 ? 1 : 0); } BitStream::BitStream() : tot_errs_(2), reading_frame_(0), counter_(0), subcarr_freq_(FC_0), bit_buffer_(BITBUFLEN), mixer_phi_(0), clock_offset_(0), is_eof_(false), subcarr_lopass_fir_(wdsp::FIR(4000.0 / FS, 127)), subcarr_baseband_(IBUFLEN) { } void BitStream::deltaBit(int b) { bit_buffer_.append(b ^ dbit_); dbit_ = b; } void BitStream::biphase(double acc) { if (sign(acc) != sign(prev_acc_)) { tot_errs_[counter_ % 2] ++; } if (counter_ % 2 == reading_frame_) { deltaBit(sign(acc + prev_acc_)); } if (counter_ == 0) { if (tot_errs_[1 - reading_frame_] < tot_errs_[reading_frame_]) { reading_frame_ = 1 - reading_frame_; } tot_errs_[0] = 0; tot_errs_[1] = 0; } prev_acc_ = acc; counter_ = (counter_ + 1) % 800; } void BitStream::demodulateMoreBits() { int16_t sample[IBUFLEN]; int bytesread = fread(sample, sizeof(int16_t), IBUFLEN, stdin); if (bytesread < IBUFLEN) { is_eof_ = true; return; } for (int i = 0; i < bytesread; i++) { /* Subcarrier downmix & phase recovery */ mixer_phi_ += 2 * M_PI * subcarr_freq_ * (1.0/FS); subcarr_baseband_.appendOverlapFiltered(wdsp::mix(sample[i] / 32768.0, mixer_phi_), subcarr_lopass_fir_); double pll_beta = 16e-3; /* Decimate band-limited signal */ if (numsamples_ % 8 == 0) { std::complex<double> sc_sample = subcarr_baseband_.at(0); subcarr_baseband_.forward(8); double phi1 = arg(sc_sample); if (phi1 >= M_PI_2) { phi1 -= M_PI; } else if (phi1 <= -M_PI_2) { phi1 += M_PI; } mixer_phi_ -= pll_beta * phi1; subcarr_freq_ -= .5 * pll_beta * phi1; /* 1187.5 Hz clock */ double clock_phi = mixer_phi_ / 48.0 + clock_offset_; double lo_clock = (fmod(clock_phi, 2*M_PI) < M_PI ? 1 : -1); /* Clock phase recovery */ if (sign(prev_bb_) != sign(real(sc_sample))) { double d_cphi = fmod(clock_phi, M_PI); if (d_cphi >= M_PI_2) d_cphi -= M_PI; clock_offset_ -= 0.005 * d_cphi; } /* biphase symbol integrate & dump */ acc_ += real(sc_sample) * lo_clock; if (sign(lo_clock) != sign(prevclock_)) { biphase(acc_); acc_ = 0; } prevclock_ = lo_clock; prev_bb_ = real(sc_sample); } if (numsamples_ % 1000000 == 0) printf(":%.2f Hz\n", subcarr_freq_); numsamples_ ++; } } int BitStream::getNextBit() { while (bit_buffer_.getFillCount() < 1 && !isEOF()) demodulateMoreBits(); return bit_buffer_.getNext(); } bool BitStream::isEOF() const { return is_eof_; } } // namespace redsea <|endoftext|>
<commit_before>/* В программе ввести и инициализировать массив структур, каждая из которых описывает материальную точку. Элементы структурного типа: координаты и массы частиц, а также расстояния от центра масс до всех точек набора. Окончание ввода - ннулевое значение массы точки. Общая масса системы точек M = sum_{i} m_i, где под m_i обозначена масса отдельных точек. Координаты центра масс: x_c = sum_{i} (x_i * m_i) / M, y_c = sum_{i} (y_i * m_i) / M, z_c = sum_{i} (z_i * m_i) / M (x_i, y_i, z_i) - координаты отдельных точек. Расстояние до центра масс определяется как: r_i = sqrt( (x_i - x_c)^2 + (y_i - y_c)^2 + (z_i - z_c)^2 ) Версия для С++, но с использованием realloc / free для выделение памяти под массив простых структур. */ #include <iostream> #include <cstdlib> #include <clocale> // установка вывода русских букв в командную строку (больше нужна для Windows OS) #include <cmath> using namespace std; struct MassPoint { double coord[3]; double mass; }; struct PointSet { struct MassPoint m_point; double distance; }; int main(int argc, char *argv[]) { setlocale(LC_ALL, "RUS"); int i, count = 0; double rx, ry, rz; PointSet mass_center = { {0., 0., 0., 0.}, 0. }; PointSet next_point; PointSet *p_array = nullptr; cout << "Введите точки (порядок ввода: масса, координата x, координата y, координата z).\nПоставьте 0 в качестве массы для прекращения задания точек" << endl; while ( true ) { cout << "Точка номер " << (count + 1) << endl << "\tмасса: "; cin >> next_point.m_point.mass; if ( next_point.m_point.mass < 0.0000000001 ) break; cout << "\tкоординаты (3 значения через пробел): "; cin >> next_point.m_point.coord[0] >> next_point.m_point.coord[1] >> next_point.m_point.coord[2]; count++; p_array = (struct PointSet *) realloc(p_array, count * sizeof(struct PointSet)); if (p_array == nullptr) { cerr << "Проблема с выделением дополнительно памяти\n"; return -1; } p_array[count - 1] = next_point; mass_center.m_point.mass += next_point.m_point.mass; mass_center.m_point.coord[0] += next_point.m_point.coord[0] * next_point.m_point.mass; mass_center.m_point.coord[1] += next_point.m_point.coord[1] * next_point.m_point.mass; mass_center.m_point.coord[2] += next_point.m_point.coord[2] * next_point.m_point.mass; } mass_center.m_point.coord[0] /= mass_center.m_point.mass; mass_center.m_point.coord[1] /= mass_center.m_point.mass; mass_center.m_point.coord[2] /= mass_center.m_point.mass; cout << "Итоги." << endl; cout << "Центр масс: " << endl; cout << "\tмасса = " << mass_center.m_point.mass << ", координаты = {" << mass_center.m_point.coord[0] << ", " << mass_center.m_point.coord[1] << ", " << mass_center.m_point.coord[2] << "}" << endl; cout << "\nВведённые точки:" << endl; for (i = 0; i < count; i++) { rx = p_array[i].m_point.coord[0] - mass_center.m_point.coord[0]; ry = p_array[i].m_point.coord[1] - mass_center.m_point.coord[1]; rz = p_array[i].m_point.coord[2] - mass_center.m_point.coord[2]; p_array[i].distance = sqrt(rx*rx + ry*ry + rz*rz); cout << "Точка номер " << i + 1 << ", координаты: {" << p_array[i].m_point.coord[0] << ", " << p_array[i].m_point.coord[1] << ", " << p_array[i].m_point.coord[2] << "}\n\tмасса = " << p_array[i].m_point.mass << ", расстояние до ц.м. = " << p_array[i].distance << endl; } free(p_array); return 0; } <commit_msg>Another style for 9_1.cpp programm<commit_after>/* В программе ввести и инициализировать массив структур, каждая из которых описывает материальную точку. Элементы структурного типа: координаты и массы частиц, а также расстояния от центра масс до всех точек набора. Окончание ввода - ннулевое значение массы точки. Общая масса системы точек M = sum_{i} m_i, где под m_i обозначена масса отдельных точек. Координаты центра масс: x_c = sum_{i} (x_i * m_i) / M, y_c = sum_{i} (y_i * m_i) / M, z_c = sum_{i} (z_i * m_i) / M (x_i, y_i, z_i) - координаты отдельных точек. Расстояние до центра масс определяется как: r_i = sqrt( (x_i - x_c)^2 + (y_i - y_c)^2 + (z_i - z_c)^2 ) Версия для С++, но с использованием realloc / free для выделение памяти под массив простых структур. */ #include <iostream> #include <cstdlib> #include <clocale> // установка вывода русских букв в командную строку (больше нужна для Windows OS) #include <cmath> using namespace std; struct MassPoint { double coord[3]; double mass; }; struct PointSet { struct MassPoint m_point; double distance; }; int main(int argc, char *argv[]) { setlocale(LC_ALL, "RUS"); int i, count = 0; double rx, ry, rz; PointSet mass_center = { {0., 0., 0., 0.}, 0. }; PointSet next_point; PointSet *p_array = nullptr; cout << "Введите точки (порядок ввода: масса, координата x, координата y, координата z).\nПоставьте 0 в качестве массы для прекращения задания точек" << endl; while ( true ) { cout << "Точка номер " << (count + 1) << endl << "\tмасса: "; cin >> next_point.m_point.mass; if ( next_point.m_point.mass < 0.0000000001 ) break; cout << "\tкоординаты (3 значения через пробел): "; cin >> next_point.m_point.coord[0] >> next_point.m_point.coord[1] >> next_point.m_point.coord[2]; ++count; p_array = (PointSet *) realloc(p_array, count * sizeof(PointSet)); if (p_array == nullptr) { cerr << "Проблема с выделением дополнительной памяти\n"; return -1; } p_array[count - 1] = next_point; mass_center.m_point.mass += next_point.m_point.mass; mass_center.m_point.coord[0] += next_point.m_point.coord[0] * next_point.m_point.mass; mass_center.m_point.coord[1] += next_point.m_point.coord[1] * next_point.m_point.mass; mass_center.m_point.coord[2] += next_point.m_point.coord[2] * next_point.m_point.mass; } mass_center.m_point.coord[0] /= mass_center.m_point.mass; mass_center.m_point.coord[1] /= mass_center.m_point.mass; mass_center.m_point.coord[2] /= mass_center.m_point.mass; cout << "Итоги." << endl; cout << "Центр масс: " << endl; cout << "\tмасса = " << mass_center.m_point.mass << ", координаты = {" << mass_center.m_point.coord[0] << ", " << mass_center.m_point.coord[1] << ", " << mass_center.m_point.coord[2] << "}" << endl; cout << "\nВведённые точки:" << endl; for (i = 0; i < count; i++) { rx = p_array[i].m_point.coord[0] - mass_center.m_point.coord[0]; ry = p_array[i].m_point.coord[1] - mass_center.m_point.coord[1]; rz = p_array[i].m_point.coord[2] - mass_center.m_point.coord[2]; p_array[i].distance = sqrt(rx*rx + ry*ry + rz*rz); cout << "Точка номер " << i + 1 << ", координаты: {" << p_array[i].m_point.coord[0] << ", " << p_array[i].m_point.coord[1] << ", " << p_array[i].m_point.coord[2] << "}\n\tмасса = " << p_array[i].m_point.mass << ", расстояние до ц.м. = " << p_array[i].distance << endl; } free(p_array); return 0; } <|endoftext|>
<commit_before>/* * Software License Agreement (BSD License) * * Point Cloud Library (PCL) - www.pointclouds.org * Copyright (c) 2009-2012, Willow Garage, Inc. * Copyright (c) 2012-, Open Perception, Inc. * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of the copyright holder(s) nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * $Id: test_filters.cpp 7683 2012-10-23 02:49:03Z rusu $ * */ #include <gtest/gtest.h> #include <pcl/point_types.h> #include <pcl/io/pcd_io.h> #include <pcl/features/normal_3d.h> #include <pcl/filters/covariance_sampling.h> #include <pcl/filters/normal_space.h> #include <pcl/common/transforms.h> #include <pcl/common/eigen.h> using namespace pcl; PointCloud<PointXYZ>::Ptr cloud_walls (new PointCloud<PointXYZ> ()), cloud_turtle (new PointCloud<PointXYZ> ()); PointCloud<PointNormal>::Ptr cloud_walls_normals (new PointCloud<PointNormal> ()), cloud_turtle_normals (new PointCloud<PointNormal> ()); ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// TEST (CovarianceSampling, Filters) { CovarianceSampling<PointNormal, PointNormal> covariance_sampling; covariance_sampling.setInputCloud (cloud_walls_normals); covariance_sampling.setNormals (cloud_walls_normals); covariance_sampling.setNumberOfSamples (static_cast<unsigned int> (cloud_walls_normals->size ()) / 4); double cond_num_walls = covariance_sampling.computeConditionNumber (); EXPECT_NEAR (cond_num_walls, 19.3518, 0.5); IndicesPtr walls_indices (new std::vector<int> ()); covariance_sampling.filter (*walls_indices); covariance_sampling.setIndices (walls_indices); double cond_num_walls_sampled = covariance_sampling.computeConditionNumber (); EXPECT_NEAR (cond_num_walls_sampled, 4.0298, 0.5); EXPECT_EQ ((*walls_indices)[0], 316); EXPECT_EQ ((*walls_indices)[walls_indices->size () / 4], 3208); EXPECT_EQ ((*walls_indices)[walls_indices->size () / 2], 2546); EXPECT_EQ ((*walls_indices)[walls_indices->size () * 3 / 4], 1886); EXPECT_EQ ((*walls_indices)[walls_indices->size () - 1], 321); covariance_sampling.setInputCloud (cloud_turtle_normals); covariance_sampling.setNormals (cloud_turtle_normals); covariance_sampling.setIndices (IndicesPtr ()); covariance_sampling.setNumberOfSamples (static_cast<unsigned int> (cloud_turtle_normals->size ()) / 8); double cond_num_turtle = covariance_sampling.computeConditionNumber (); EXPECT_NEAR (cond_num_turtle, 20661.7663, 0.5); IndicesPtr turtle_indices (new std::vector<int> ()); covariance_sampling.filter (*turtle_indices); covariance_sampling.setIndices (turtle_indices); double cond_num_turtle_sampled = covariance_sampling.computeConditionNumber (); EXPECT_NEAR (cond_num_turtle_sampled, 5795.5057, 0.5); EXPECT_EQ ((*turtle_indices)[0], 80344); EXPECT_EQ ((*turtle_indices)[turtle_indices->size () / 4], 145982); EXPECT_EQ ((*turtle_indices)[turtle_indices->size () / 2], 104557); EXPECT_EQ ((*turtle_indices)[turtle_indices->size () * 3 / 4], 41512); EXPECT_EQ ((*turtle_indices)[turtle_indices->size () - 1], 136885); } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// TEST (NormalSpaceSampling, Filters) { NormalSpaceSampling<PointNormal, PointNormal> normal_space_sampling; normal_space_sampling.setInputCloud (cloud_walls_normals); normal_space_sampling.setNormals (cloud_walls_normals); normal_space_sampling.setBins (16, 16, 16); normal_space_sampling.setSeed (0); normal_space_sampling.setSample (static_cast<unsigned int> (cloud_walls_normals->size ()) / 4); IndicesPtr walls_indices (new std::vector<int> ()); normal_space_sampling.filter (*walls_indices); CovarianceSampling<PointNormal, PointNormal> covariance_sampling; covariance_sampling.setInputCloud (cloud_walls_normals); covariance_sampling.setNormals (cloud_walls_normals); covariance_sampling.setIndices (walls_indices); covariance_sampling.setNumberOfSamples (0); double cond_num_walls_sampled = covariance_sampling.computeConditionNumber (); EXPECT_NEAR (cond_num_walls_sampled, 7.8289, 0.5); EXPECT_EQ ((*walls_indices)[0], 2472); EXPECT_EQ ((*walls_indices)[walls_indices->size () / 4], 2854); EXPECT_EQ ((*walls_indices)[walls_indices->size () / 2], 1566); EXPECT_EQ ((*walls_indices)[walls_indices->size () * 3 / 4], 2981); EXPECT_EQ ((*walls_indices)[walls_indices->size () - 1], 2577); } /* ---[ */ int main (int argc, char** argv) { // Load two standard PCD files from disk if (argc < 3) { std::cerr << "No test files given. Please download `sac_plane_test.pcd` and 'cturtle.pcd' and pass them path to the test." << std::endl; return (-1); } // Load in the point clouds io::loadPCDFile (argv[1], *cloud_walls); io::loadPCDFile (argv[2], *cloud_turtle); // Compute the normals for each cloud, and then clean them up of any NaN values NormalEstimation<PointXYZ,PointNormal> ne; ne.setInputCloud (cloud_walls); ne.setRadiusSearch (0.02); ne.compute (*cloud_walls_normals); copyPointCloud (*cloud_walls, *cloud_walls_normals); std::vector<int> aux_indices; removeNaNFromPointCloud (*cloud_walls_normals, *cloud_walls_normals, aux_indices); removeNaNNormalsFromPointCloud (*cloud_walls_normals, *cloud_walls_normals, aux_indices); ne = NormalEstimation<PointXYZ, PointNormal> (); ne.setInputCloud (cloud_turtle); ne.setKSearch (5); ne.compute (*cloud_turtle_normals); copyPointCloud (*cloud_turtle, *cloud_turtle_normals); removeNaNFromPointCloud (*cloud_turtle_normals, *cloud_turtle_normals, aux_indices); removeNaNNormalsFromPointCloud (*cloud_turtle_normals, *cloud_turtle_normals, aux_indices); testing::InitGoogleTest (&argc, argv); return (RUN_ALL_TESTS ()); } /* ]--- */ <commit_msg>changed unit test values<commit_after>/* * Software License Agreement (BSD License) * * Point Cloud Library (PCL) - www.pointclouds.org * Copyright (c) 2009-2012, Willow Garage, Inc. * Copyright (c) 2012-, Open Perception, Inc. * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of the copyright holder(s) nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * $Id: test_filters.cpp 7683 2012-10-23 02:49:03Z rusu $ * */ #include <gtest/gtest.h> #include <pcl/point_types.h> #include <pcl/io/pcd_io.h> #include <pcl/features/normal_3d.h> #include <pcl/filters/covariance_sampling.h> #include <pcl/filters/normal_space.h> #include <pcl/common/transforms.h> #include <pcl/common/eigen.h> using namespace pcl; PointCloud<PointXYZ>::Ptr cloud_walls (new PointCloud<PointXYZ> ()), cloud_turtle (new PointCloud<PointXYZ> ()); PointCloud<PointNormal>::Ptr cloud_walls_normals (new PointCloud<PointNormal> ()), cloud_turtle_normals (new PointCloud<PointNormal> ()); ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// TEST (CovarianceSampling, Filters) { CovarianceSampling<PointNormal, PointNormal> covariance_sampling; covariance_sampling.setInputCloud (cloud_walls_normals); covariance_sampling.setNormals (cloud_walls_normals); covariance_sampling.setNumberOfSamples (static_cast<unsigned int> (cloud_walls_normals->size ()) / 4); double cond_num_walls = covariance_sampling.computeConditionNumber (); EXPECT_NEAR (cond_num_walls, 20.8774, 0.5); IndicesPtr walls_indices (new std::vector<int> ()); covariance_sampling.filter (*walls_indices); covariance_sampling.setIndices (walls_indices); double cond_num_walls_sampled = covariance_sampling.computeConditionNumber (); EXPECT_NEAR (cond_num_walls_sampled, 4.0298, 0.5); EXPECT_EQ ((*walls_indices)[0], 315); EXPECT_EQ ((*walls_indices)[walls_indices->size () / 4], 275); EXPECT_EQ ((*walls_indices)[walls_indices->size () / 2], 1846); EXPECT_EQ ((*walls_indices)[walls_indices->size () * 3 / 4], 1241); EXPECT_EQ ((*walls_indices)[walls_indices->size () - 1], 2632); covariance_sampling.setInputCloud (cloud_turtle_normals); covariance_sampling.setNormals (cloud_turtle_normals); covariance_sampling.setIndices (IndicesPtr ()); covariance_sampling.setNumberOfSamples (static_cast<unsigned int> (cloud_turtle_normals->size ()) / 8); double cond_num_turtle = covariance_sampling.computeConditionNumber (); EXPECT_NEAR (cond_num_turtle, 20661.7663, 0.5); IndicesPtr turtle_indices (new std::vector<int> ()); covariance_sampling.filter (*turtle_indices); covariance_sampling.setIndices (turtle_indices); double cond_num_turtle_sampled = covariance_sampling.computeConditionNumber (); EXPECT_NEAR (cond_num_turtle_sampled, 5795.5057, 0.5); EXPECT_EQ ((*turtle_indices)[0], 80344); EXPECT_EQ ((*turtle_indices)[turtle_indices->size () / 4], 145982); EXPECT_EQ ((*turtle_indices)[turtle_indices->size () / 2], 104557); EXPECT_EQ ((*turtle_indices)[turtle_indices->size () * 3 / 4], 41512); EXPECT_EQ ((*turtle_indices)[turtle_indices->size () - 1], 136885); } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// TEST (NormalSpaceSampling, Filters) { NormalSpaceSampling<PointNormal, PointNormal> normal_space_sampling; normal_space_sampling.setInputCloud (cloud_walls_normals); normal_space_sampling.setNormals (cloud_walls_normals); normal_space_sampling.setBins (16, 16, 16); normal_space_sampling.setSeed (0); normal_space_sampling.setSample (static_cast<unsigned int> (cloud_walls_normals->size ()) / 4); IndicesPtr walls_indices (new std::vector<int> ()); normal_space_sampling.filter (*walls_indices); CovarianceSampling<PointNormal, PointNormal> covariance_sampling; covariance_sampling.setInputCloud (cloud_walls_normals); covariance_sampling.setNormals (cloud_walls_normals); covariance_sampling.setIndices (walls_indices); covariance_sampling.setNumberOfSamples (0); double cond_num_walls_sampled = covariance_sampling.computeConditionNumber (); EXPECT_NEAR (cond_num_walls_sampled, 9.0989, 0.5); EXPECT_EQ ((*walls_indices)[0], 2432); EXPECT_EQ ((*walls_indices)[walls_indices->size () / 4], 1947); EXPECT_EQ ((*walls_indices)[walls_indices->size () / 2], 3148); EXPECT_EQ ((*walls_indices)[walls_indices->size () * 3 / 4], 2443); EXPECT_EQ ((*walls_indices)[walls_indices->size () - 1], 2396); } /* ---[ */ int main (int argc, char** argv) { // Load two standard PCD files from disk if (argc < 3) { std::cerr << "No test files given. Please download `sac_plane_test.pcd` and 'cturtle.pcd' and pass them path to the test." << std::endl; return (-1); } // Load in the point clouds io::loadPCDFile (argv[1], *cloud_walls); io::loadPCDFile (argv[2], *cloud_turtle); // Compute the normals for each cloud, and then clean them up of any NaN values NormalEstimation<PointXYZ,PointNormal> ne; ne.setInputCloud (cloud_walls); ne.setRadiusSearch (0.02); ne.compute (*cloud_walls_normals); copyPointCloud (*cloud_walls, *cloud_walls_normals); std::vector<int> aux_indices; removeNaNFromPointCloud (*cloud_walls_normals, *cloud_walls_normals, aux_indices); removeNaNNormalsFromPointCloud (*cloud_walls_normals, *cloud_walls_normals, aux_indices); ne = NormalEstimation<PointXYZ, PointNormal> (); ne.setInputCloud (cloud_turtle); ne.setKSearch (5); ne.compute (*cloud_turtle_normals); copyPointCloud (*cloud_turtle, *cloud_turtle_normals); removeNaNFromPointCloud (*cloud_turtle_normals, *cloud_turtle_normals, aux_indices); removeNaNNormalsFromPointCloud (*cloud_turtle_normals, *cloud_turtle_normals, aux_indices); testing::InitGoogleTest (&argc, argv); return (RUN_ALL_TESTS ()); } /* ]--- */ <|endoftext|>
<commit_before>/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/perception/fusion/lib/data_fusion/type_fusion/dst_type_fusion/dst_type_fusion.h" #include <algorithm> #include <functional> #include <map> #include <string> #include <vector> #include "boost/format.hpp" #include "gtest/gtest.h" #include "modules/perception/fusion/base/sensor_data_manager.h" #include "modules/perception/fusion/common/camera_util.h" namespace apollo { namespace perception { namespace fusion { TEST(DstTypeFusionTest, test_update_with_measurement) { FLAGS_work_root = "/apollo/modules/perception/testdata/" "fusion/dst_type_fusion"; FLAGS_obs_sensor_intrinsic_path = "/apollo/modules/perception/testdata/" "fusion/dst_type_fusion/params"; FLAGS_obs_sensor_meta_path = "./data/sensor_meta.pt"; common::SensorManager *sensor_manager = lib::Singleton<common::SensorManager>::get_instance(); EXPECT_TRUE(sensor_manager != nullptr); EXPECT_TRUE(sensor_manager->Init()); std::cout << "start init dst app\n"; bool flag = DstTypeFusion::Init(); EXPECT_TRUE(flag); // create a track base::ObjectPtr base_lidar_object_ptr(new base::Object()); base_lidar_object_ptr->type = base::ObjectType::VEHICLE; base_lidar_object_ptr->type_probs.resize( static_cast<size_t>(base::ObjectType::MAX_OBJECT_TYPE), 0.0); base_lidar_object_ptr->type_probs = std::vector<float>( static_cast<size_t>(base::ObjectType::MAX_OBJECT_TYPE), 0.1); base_lidar_object_ptr ->type_probs[static_cast<size_t>(base::ObjectType::VEHICLE)] = 0.6; base::FramePtr lidar_frame_ptr(new base::Frame()); lidar_frame_ptr->sensor_info.name = "velodyne_64"; lidar_frame_ptr->sensor_info.type = base::SensorType::VELODYNE_64; SensorPtr lidar_sensor_ptr(new Sensor(lidar_frame_ptr->sensor_info)); lidar_sensor_ptr->AddFrame(lidar_frame_ptr); SensorFramePtr lidar_sensor_frame_ptr(new SensorFrame()); lidar_sensor_frame_ptr->Initialize(lidar_frame_ptr, lidar_sensor_ptr->GetSensorId(), lidar_sensor_ptr->GetSensorType()); SensorObjectPtr lidar_sensor_object_ptr( new SensorObject(base_lidar_object_ptr, lidar_sensor_frame_ptr)); TrackPtr track(new Track()); EXPECT_TRUE(DstTypeFusion::Init()); EXPECT_TRUE(track->Initialize(lidar_sensor_object_ptr)); DstTypeFusion type_fusion(track); CHECK_EQ(static_cast<size_t>(track->GetFusedObject()->GetBaseObject()->type), static_cast<size_t>(base::ObjectType::UNKNOWN)); // create a camera measurement base::ObjectPtr base_camera_object_ptr(new base::Object()); base_camera_object_ptr->type = base::ObjectType::PEDESTRIAN; base_camera_object_ptr->type_probs.resize( static_cast<size_t>(base::ObjectType::MAX_OBJECT_TYPE)); base_camera_object_ptr->type_probs = std::vector<float>( static_cast<size_t>(base::ObjectType::MAX_OBJECT_TYPE), 0.1); base_camera_object_ptr ->type_probs[static_cast<size_t>(base::ObjectType::PEDESTRIAN)] = 0.4; base::FramePtr camera_frame_ptr(new base::Frame()); camera_frame_ptr->sensor_info.type = base::SensorType::MONOCULAR_CAMERA; SensorPtr camera_sensor_ptr(new Sensor(camera_frame_ptr->sensor_info)); camera_sensor_ptr->AddFrame(camera_frame_ptr); SensorFramePtr camera_sensor_frame_ptr(new SensorFrame()); camera_sensor_frame_ptr->Initialize(camera_frame_ptr, camera_sensor_ptr->GetSensorId(), camera_sensor_ptr->GetSensorType()); SensorObjectPtr camera_sensor_object_ptr( new SensorObject(base_camera_object_ptr, camera_sensor_frame_ptr)); // camera not supported camera_frame_ptr->sensor_info.name = "camera_test"; type_fusion.UpdateWithMeasurement(camera_sensor_object_ptr, 0.0); CHECK_EQ(static_cast<size_t>(track->GetFusedObject()->GetBaseObject()->type), static_cast<size_t>(base::ObjectType::UNKNOWN)); camera_frame_ptr->sensor_info.name = "camera_smartereye"; SensorFramePtr camera_sensor_frame_normal(new SensorFrame()); SensorPtr camera_sensor_ptr1(new Sensor(camera_frame_ptr->sensor_info)); camera_sensor_ptr1->AddFrame(camera_frame_ptr); camera_sensor_frame_normal->Initialize(camera_frame_ptr, camera_sensor_ptr->GetSensorId(), camera_sensor_ptr->GetSensorType()); SensorObjectPtr camera_sensor_object_ptr1( new SensorObject(base_camera_object_ptr, camera_sensor_frame_normal)); // update with measurment type_fusion.UpdateWithMeasurement(camera_sensor_object_ptr1, 0.0); // std::cout<< "fused dst: " << type_fusion.PrintFusedDst(); CHECK_EQ(static_cast<size_t>(track->GetFusedObject()->GetBaseObject()->type), static_cast<size_t>(base::ObjectType::PEDESTRIAN)); // update more times type_fusion.UpdateWithMeasurement(camera_sensor_object_ptr1, 0.0); type_fusion.UpdateWithMeasurement(camera_sensor_object_ptr1, 0.0); CHECK_EQ(static_cast<size_t>(track->GetFusedObject()->GetBaseObject()->type), static_cast<size_t>(base::ObjectType::PEDESTRIAN)); } TEST(DstTypeFusionTest, test_update_without_measurement) { FLAGS_work_root = "/apollo/modules/perception/testdata/" "fusion/dst_type_fusion"; FLAGS_obs_sensor_intrinsic_path = "/apollo/modules/perception/testdata/" "fusion/dst_type_fusion/params"; FLAGS_obs_sensor_meta_path = "./conf/sensor_meta.config"; common::SensorManager *sensor_manager = lib::Singleton<common::SensorManager>::get_instance(); EXPECT_TRUE(sensor_manager != nullptr); EXPECT_TRUE(sensor_manager->Init()); std::cout << "start init dst app\n"; bool flag = DstTypeFusion::Init(); EXPECT_TRUE(flag); base::SensorInfo radar_front_info; EXPECT_TRUE(sensor_manager->GetSensorInfo("radar", &radar_front_info)); SensorPtr radar_front_sensor(new Sensor(radar_front_info)); // radar front frame base::ObjectPtr base_obj(new base::Object()); base::FramePtr base_frame(new base::Frame()); base_obj->center = Eigen::Vector3d(2.3, 2.3, 0.0); base_obj->anchor_point = base_obj->center; base_obj->velocity = Eigen::Vector3f(5, 0, 0); base_obj->direction = Eigen::Vector3f(1, 0, 0); base_obj->radar_supplement.range = 10; base_obj->radar_supplement.angle = 10; base_frame->objects.emplace_back(base_obj); base_frame->sensor_info = radar_front_info; SensorFramePtr radar_frame(new SensorFrame()); radar_frame->Initialize(base_frame, radar_front_sensor->GetSensorId(), radar_front_sensor->GetSensorType()); // create a lidar track base::ObjectPtr base_lidar_object_ptr(new base::Object()); base_lidar_object_ptr->type = base::ObjectType::VEHICLE; base_lidar_object_ptr->type_probs.resize( static_cast<size_t>(base::ObjectType::MAX_OBJECT_TYPE), 0.0); base_lidar_object_ptr->type_probs = std::vector<float>( static_cast<size_t>(base::ObjectType::MAX_OBJECT_TYPE), 0.1); base_lidar_object_ptr ->type_probs[static_cast<size_t>(base::ObjectType::VEHICLE)] = 0.6; base_lidar_object_ptr->center = Eigen::Vector3d(0, 0, 10); base::FramePtr lidar_frame_ptr(new base::Frame()); lidar_frame_ptr->sensor_info.name = "velodyne_64"; lidar_frame_ptr->sensor_info.type = base::SensorType::VELODYNE_64; SensorPtr lidar_sensor_ptr(new Sensor(lidar_frame_ptr->sensor_info)); lidar_sensor_ptr->AddFrame(lidar_frame_ptr); SensorFramePtr lidar_sensor_frame_ptr(new SensorFrame()); lidar_sensor_frame_ptr->Initialize(lidar_frame_ptr, lidar_sensor_ptr->GetSensorId(), lidar_sensor_ptr->GetSensorType()); SensorObjectPtr lidar_sensor_object_ptr( new SensorObject(base_lidar_object_ptr, lidar_sensor_frame_ptr)); TrackPtr track1(new Track()); EXPECT_TRUE(track1->Initialize(lidar_sensor_object_ptr)); EXPECT_TRUE(DstTypeFusion::Init()); DstTypeFusion type_fusion1(track1); CHECK_EQ(static_cast<size_t>(track1->GetFusedObject()->GetBaseObject()->type), static_cast<size_t>(base::ObjectType::UNKNOWN)); base::FramePtr camera_frame_ptr(new base::Frame()); camera_frame_ptr->sensor_info.name = "camera_smartereye"; camera_frame_ptr->sensor_info.type = base::SensorType::MONOCULAR_CAMERA; camera_frame_ptr->timestamp = 151192277.124567989; Eigen::Affine3d pose(Eigen::Affine3d::Identity()); camera_frame_ptr->sensor2world_pose = pose; SensorPtr camera_sensor_ptr(new Sensor(camera_frame_ptr->sensor_info)); camera_sensor_ptr->AddFrame(camera_frame_ptr); SensorDataManager *sensor_date_manager = lib::Singleton<SensorDataManager>::get_instance(); sensor_date_manager->AddSensorMeasurements(camera_frame_ptr); // update without measurment std::string sensor_id = "camera_smartereye"; // std::cout<< "fused dst: " << type_fusion1.PrintFusedDst(); type_fusion1.UpdateWithoutMeasurement("velodyne_64", 151192277.124567989, 151192277.124567989, 0.9); CHECK_EQ(static_cast<size_t>(track1->GetFusedObject()->GetBaseObject()->type), static_cast<size_t>(base::ObjectType::UNKNOWN)); type_fusion1.UpdateWithoutMeasurement(sensor_id, 151192277.124567989, 151192277.124567989, 0.9); CHECK_EQ(static_cast<size_t>(track1->GetFusedObject()->GetBaseObject()->type), static_cast<size_t>(base::ObjectType::UNKNOWN)); type_fusion1.UpdateWithoutMeasurement("camera_test", 151192277.124567989, 151192277.124567989, 0.9); CHECK_EQ(static_cast<size_t>(track1->GetFusedObject()->GetBaseObject()->type), static_cast<size_t>(base::ObjectType::UNKNOWN)); // update more times type_fusion1.UpdateWithoutMeasurement(sensor_id, 151192277.124567989, 151192277.124567989, 0.0); type_fusion1.UpdateWithoutMeasurement(sensor_id, 151192277.124567989, 151192277.124567989, 0.0); type_fusion1.UpdateWithoutMeasurement(sensor_id, 0, 0, 0.0); CHECK_EQ(static_cast<size_t>(track1->GetFusedObject()->GetBaseObject()->type), static_cast<size_t>(base::ObjectType::UNKNOWN)); TrackPtr track2(new Track()); track2->Initialize(radar_frame->GetForegroundObjects()[0]); DstTypeFusion type_fusion_2(track2); type_fusion_2.UpdateWithoutMeasurement(sensor_id, 151192277.124567989, 151192277.124567989, 0.0); CHECK_EQ(static_cast<size_t>(track1->GetFusedObject()->GetBaseObject()->type), static_cast<size_t>(base::ObjectType::UNKNOWN)); base::ObjectPtr base_camera_object_ptr(new base::Object()); SensorFramePtr camera_sensor_frame_ptr(new SensorFrame()); camera_sensor_frame_ptr->Initialize(camera_frame_ptr, camera_sensor_ptr->GetSensorId(), camera_sensor_ptr->GetSensorType()); SensorObjectPtr camera_sensor_object_ptr( new SensorObject(base_camera_object_ptr, camera_sensor_frame_ptr)); TrackPtr track3(new Track()); track3->Initialize(camera_sensor_object_ptr); DstTypeFusion type_fusion_3(track3); type_fusion_3.UpdateWithoutMeasurement(sensor_id, 151192277.124567989, 151192277.124567989, 0.0); CHECK_EQ(static_cast<size_t>(track3->GetFusedObject()->GetBaseObject()->type), static_cast<size_t>(base::ObjectType::UNKNOWN)); } } // namespace fusion } // namespace perception } // namespace apollo <commit_msg>Fixed test failure after 54314083e16c41082a81520ec44c7aaae44989c7.<commit_after>/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/perception/fusion/lib/data_fusion/type_fusion/dst_type_fusion/dst_type_fusion.h" #include <algorithm> #include <functional> #include <map> #include <string> #include <vector> #include "boost/format.hpp" #include "gtest/gtest.h" #include "modules/perception/fusion/base/sensor_data_manager.h" #include "modules/perception/fusion/common/camera_util.h" namespace apollo { namespace perception { namespace fusion { TEST(DstTypeFusionTest, test_update_with_measurement) { FLAGS_work_root = "/apollo/modules/perception/testdata/" "fusion/dst_type_fusion"; FLAGS_obs_sensor_intrinsic_path = "/apollo/modules/perception/testdata/" "fusion/dst_type_fusion/params"; FLAGS_obs_sensor_meta_path = "./data/sensor_meta.pt"; common::SensorManager *sensor_manager = lib::Singleton<common::SensorManager>::get_instance(); EXPECT_TRUE(sensor_manager != nullptr); EXPECT_TRUE(sensor_manager->Init()); std::cout << "start init dst app\n"; bool flag = DstTypeFusion::Init(); EXPECT_TRUE(flag); // create a track base::ObjectPtr base_lidar_object_ptr(new base::Object()); base_lidar_object_ptr->type = base::ObjectType::VEHICLE; base_lidar_object_ptr->type_probs.resize( static_cast<size_t>(base::ObjectType::MAX_OBJECT_TYPE), 0.0); base_lidar_object_ptr->type_probs = std::vector<float>( static_cast<size_t>(base::ObjectType::MAX_OBJECT_TYPE), 0.1); base_lidar_object_ptr ->type_probs[static_cast<size_t>(base::ObjectType::VEHICLE)] = 0.6; base::FramePtr lidar_frame_ptr(new base::Frame()); lidar_frame_ptr->sensor_info.name = "velodyne_64"; lidar_frame_ptr->sensor_info.type = base::SensorType::VELODYNE_64; SensorPtr lidar_sensor_ptr(new Sensor(lidar_frame_ptr->sensor_info)); lidar_sensor_ptr->AddFrame(lidar_frame_ptr); SensorFramePtr lidar_sensor_frame_ptr(new SensorFrame()); lidar_sensor_frame_ptr->Initialize(lidar_frame_ptr, lidar_sensor_ptr->GetSensorId(), lidar_sensor_ptr->GetSensorType()); SensorObjectPtr lidar_sensor_object_ptr( new SensorObject(base_lidar_object_ptr, lidar_sensor_frame_ptr)); TrackPtr track(new Track()); EXPECT_TRUE(DstTypeFusion::Init()); EXPECT_TRUE(track->Initialize(lidar_sensor_object_ptr)); DstTypeFusion type_fusion(track); CHECK_EQ(static_cast<size_t>(track->GetFusedObject()->GetBaseObject()->type), static_cast<size_t>(base::ObjectType::UNKNOWN)); // create a camera measurement base::ObjectPtr base_camera_object_ptr(new base::Object()); base_camera_object_ptr->type = base::ObjectType::PEDESTRIAN; base_camera_object_ptr->type_probs.resize( static_cast<size_t>(base::ObjectType::MAX_OBJECT_TYPE)); base_camera_object_ptr->type_probs = std::vector<float>( static_cast<size_t>(base::ObjectType::MAX_OBJECT_TYPE), 0.1); base_camera_object_ptr ->type_probs[static_cast<size_t>(base::ObjectType::PEDESTRIAN)] = 0.4; base::FramePtr camera_frame_ptr(new base::Frame()); camera_frame_ptr->sensor_info.type = base::SensorType::MONOCULAR_CAMERA; SensorPtr camera_sensor_ptr(new Sensor(camera_frame_ptr->sensor_info)); camera_sensor_ptr->AddFrame(camera_frame_ptr); SensorFramePtr camera_sensor_frame_ptr(new SensorFrame()); camera_sensor_frame_ptr->Initialize(camera_frame_ptr, camera_sensor_ptr->GetSensorId(), camera_sensor_ptr->GetSensorType()); SensorObjectPtr camera_sensor_object_ptr( new SensorObject(base_camera_object_ptr, camera_sensor_frame_ptr)); // camera not supported camera_frame_ptr->sensor_info.name = "camera_test"; type_fusion.UpdateWithMeasurement(camera_sensor_object_ptr, 0.0); CHECK_EQ(static_cast<size_t>(track->GetFusedObject()->GetBaseObject()->type), static_cast<size_t>(base::ObjectType::UNKNOWN)); camera_frame_ptr->sensor_info.name = "camera_smartereye"; SensorFramePtr camera_sensor_frame_normal(new SensorFrame()); SensorPtr camera_sensor_ptr1(new Sensor(camera_frame_ptr->sensor_info)); camera_sensor_ptr1->AddFrame(camera_frame_ptr); camera_sensor_frame_normal->Initialize(camera_frame_ptr, camera_sensor_ptr->GetSensorId(), camera_sensor_ptr->GetSensorType()); SensorObjectPtr camera_sensor_object_ptr1( new SensorObject(base_camera_object_ptr, camera_sensor_frame_normal)); // update with measurment type_fusion.UpdateWithMeasurement(camera_sensor_object_ptr1, 0.0); // std::cout<< "fused dst: " << type_fusion.PrintFusedDst(); CHECK_NE(static_cast<size_t>(track->GetFusedObject()->GetBaseObject()->type), static_cast<size_t>(base::ObjectType::PEDESTRIAN)); // update more times type_fusion.UpdateWithMeasurement(camera_sensor_object_ptr1, 0.0); type_fusion.UpdateWithMeasurement(camera_sensor_object_ptr1, 0.0); CHECK_NE(static_cast<size_t>(track->GetFusedObject()->GetBaseObject()->type), static_cast<size_t>(base::ObjectType::PEDESTRIAN)); } TEST(DstTypeFusionTest, test_update_without_measurement) { FLAGS_work_root = "/apollo/modules/perception/testdata/" "fusion/dst_type_fusion"; FLAGS_obs_sensor_intrinsic_path = "/apollo/modules/perception/testdata/" "fusion/dst_type_fusion/params"; FLAGS_obs_sensor_meta_path = "./conf/sensor_meta.config"; common::SensorManager *sensor_manager = lib::Singleton<common::SensorManager>::get_instance(); EXPECT_TRUE(sensor_manager != nullptr); EXPECT_TRUE(sensor_manager->Init()); std::cout << "start init dst app\n"; bool flag = DstTypeFusion::Init(); EXPECT_TRUE(flag); base::SensorInfo radar_front_info; EXPECT_TRUE(sensor_manager->GetSensorInfo("radar", &radar_front_info)); SensorPtr radar_front_sensor(new Sensor(radar_front_info)); // radar front frame base::ObjectPtr base_obj(new base::Object()); base::FramePtr base_frame(new base::Frame()); base_obj->center = Eigen::Vector3d(2.3, 2.3, 0.0); base_obj->anchor_point = base_obj->center; base_obj->velocity = Eigen::Vector3f(5, 0, 0); base_obj->direction = Eigen::Vector3f(1, 0, 0); base_obj->radar_supplement.range = 10; base_obj->radar_supplement.angle = 10; base_frame->objects.emplace_back(base_obj); base_frame->sensor_info = radar_front_info; SensorFramePtr radar_frame(new SensorFrame()); radar_frame->Initialize(base_frame, radar_front_sensor->GetSensorId(), radar_front_sensor->GetSensorType()); // create a lidar track base::ObjectPtr base_lidar_object_ptr(new base::Object()); base_lidar_object_ptr->type = base::ObjectType::VEHICLE; base_lidar_object_ptr->type_probs.resize( static_cast<size_t>(base::ObjectType::MAX_OBJECT_TYPE), 0.0); base_lidar_object_ptr->type_probs = std::vector<float>( static_cast<size_t>(base::ObjectType::MAX_OBJECT_TYPE), 0.1); base_lidar_object_ptr ->type_probs[static_cast<size_t>(base::ObjectType::VEHICLE)] = 0.6; base_lidar_object_ptr->center = Eigen::Vector3d(0, 0, 10); base::FramePtr lidar_frame_ptr(new base::Frame()); lidar_frame_ptr->sensor_info.name = "velodyne_64"; lidar_frame_ptr->sensor_info.type = base::SensorType::VELODYNE_64; SensorPtr lidar_sensor_ptr(new Sensor(lidar_frame_ptr->sensor_info)); lidar_sensor_ptr->AddFrame(lidar_frame_ptr); SensorFramePtr lidar_sensor_frame_ptr(new SensorFrame()); lidar_sensor_frame_ptr->Initialize(lidar_frame_ptr, lidar_sensor_ptr->GetSensorId(), lidar_sensor_ptr->GetSensorType()); SensorObjectPtr lidar_sensor_object_ptr( new SensorObject(base_lidar_object_ptr, lidar_sensor_frame_ptr)); TrackPtr track1(new Track()); EXPECT_TRUE(track1->Initialize(lidar_sensor_object_ptr)); EXPECT_TRUE(DstTypeFusion::Init()); DstTypeFusion type_fusion1(track1); CHECK_EQ(static_cast<size_t>(track1->GetFusedObject()->GetBaseObject()->type), static_cast<size_t>(base::ObjectType::UNKNOWN)); base::FramePtr camera_frame_ptr(new base::Frame()); camera_frame_ptr->sensor_info.name = "camera_smartereye"; camera_frame_ptr->sensor_info.type = base::SensorType::MONOCULAR_CAMERA; camera_frame_ptr->timestamp = 151192277.124567989; Eigen::Affine3d pose(Eigen::Affine3d::Identity()); camera_frame_ptr->sensor2world_pose = pose; SensorPtr camera_sensor_ptr(new Sensor(camera_frame_ptr->sensor_info)); camera_sensor_ptr->AddFrame(camera_frame_ptr); SensorDataManager *sensor_date_manager = lib::Singleton<SensorDataManager>::get_instance(); sensor_date_manager->AddSensorMeasurements(camera_frame_ptr); // update without measurment std::string sensor_id = "camera_smartereye"; // std::cout<< "fused dst: " << type_fusion1.PrintFusedDst(); type_fusion1.UpdateWithoutMeasurement("velodyne_64", 151192277.124567989, 151192277.124567989, 0.9); CHECK_EQ(static_cast<size_t>(track1->GetFusedObject()->GetBaseObject()->type), static_cast<size_t>(base::ObjectType::UNKNOWN)); type_fusion1.UpdateWithoutMeasurement(sensor_id, 151192277.124567989, 151192277.124567989, 0.9); CHECK_EQ(static_cast<size_t>(track1->GetFusedObject()->GetBaseObject()->type), static_cast<size_t>(base::ObjectType::UNKNOWN)); type_fusion1.UpdateWithoutMeasurement("camera_test", 151192277.124567989, 151192277.124567989, 0.9); CHECK_EQ(static_cast<size_t>(track1->GetFusedObject()->GetBaseObject()->type), static_cast<size_t>(base::ObjectType::UNKNOWN)); // update more times type_fusion1.UpdateWithoutMeasurement(sensor_id, 151192277.124567989, 151192277.124567989, 0.0); type_fusion1.UpdateWithoutMeasurement(sensor_id, 151192277.124567989, 151192277.124567989, 0.0); type_fusion1.UpdateWithoutMeasurement(sensor_id, 0, 0, 0.0); CHECK_EQ(static_cast<size_t>(track1->GetFusedObject()->GetBaseObject()->type), static_cast<size_t>(base::ObjectType::UNKNOWN)); TrackPtr track2(new Track()); track2->Initialize(radar_frame->GetForegroundObjects()[0]); DstTypeFusion type_fusion_2(track2); type_fusion_2.UpdateWithoutMeasurement(sensor_id, 151192277.124567989, 151192277.124567989, 0.0); CHECK_EQ(static_cast<size_t>(track1->GetFusedObject()->GetBaseObject()->type), static_cast<size_t>(base::ObjectType::UNKNOWN)); base::ObjectPtr base_camera_object_ptr(new base::Object()); SensorFramePtr camera_sensor_frame_ptr(new SensorFrame()); camera_sensor_frame_ptr->Initialize(camera_frame_ptr, camera_sensor_ptr->GetSensorId(), camera_sensor_ptr->GetSensorType()); SensorObjectPtr camera_sensor_object_ptr( new SensorObject(base_camera_object_ptr, camera_sensor_frame_ptr)); TrackPtr track3(new Track()); track3->Initialize(camera_sensor_object_ptr); DstTypeFusion type_fusion_3(track3); type_fusion_3.UpdateWithoutMeasurement(sensor_id, 151192277.124567989, 151192277.124567989, 0.0); CHECK_EQ(static_cast<size_t>(track3->GetFusedObject()->GetBaseObject()->type), static_cast<size_t>(base::ObjectType::UNKNOWN)); } } // namespace fusion } // namespace perception } // namespace apollo <|endoftext|>
<commit_before> // Qt includes #include <QTextStream> #include <QCoreApplication> #include <QProcess> // STD includes #include <iostream> #include <cstdlib> /* /pieper/ctk/latest/CTK-superbuild/CMakeExternals/Install/bin/dcmqrscp -c /pieper/ctk/latest/CTK-superbuild/CTK-build/Testing/Temporary/dcmqrscp.cfg -d -v storescu -aec COMMONTK -aet CTK_AE localhost 11112 /data/pieper-face-2005-05-11/1.2.840.113619.2.135.3596.6358736.5118.1115807980.182.UID/000001.SER/000001.IMA findscu -aet CTK_AE -aec COMMONTK -P -k 0010,0010=\* localhost 11112 patqry.dcm ./CTK-build/bin/ctkDICOMQuery test.db CTK_AE COMMONTK localhost 11112 ./CTK-build/bin/ctkDICOMRetrieve 1.2.840.113619.2.135.3596.6358736.5118.1115807980.182 /tmp/hoot CTK_AE 11113 CTK_AE localhost 11112 CTK_CLIENT_AE */ int ctkDICOMApplicationTest1(int argc, char * argv []) { QCoreApplication app(argc, argv); QTextStream out(stdout); if ( argc < 10 ) { out << "ERROR: invalid arguments. Should be:\n"; out << " ctkDICOMApplicationTest1 <dcmqrscp> <configfile> <dicomData1> <dcmData2> <storescu> <ctkDICOMQuery> <ctkDICOMRetrieve> <retrieveDirectory>\n"; return EXIT_FAILURE; } QString dcmqrscp_exe (argv[1]); QString dcmqrscp_cfg (argv[2]); QString dicomData1 (argv[3]); QString dicomData2 (argv[4]); QString storescu_exe (argv[5]); QString ctkDICOMQuery_exe (argv[6]); QString ctkDICOMQuery_db_file (argv[7]); QString ctkDICOMRetrieve_exe (argv[8]); QString ctkDICOMRetrieve_directory (argv[9]); // // first, start the server process // QProcess *dcmqrscp = new QProcess(0); QStringList dcmqrscp_args; dcmqrscp_args << "--config" << dcmqrscp_cfg; dcmqrscp_args << "--debug" << "--verbose"; dcmqrscp_args << "11112"; try { out << "starting server" << dcmqrscp_exe << "\n"; out << "with args " << dcmqrscp_args.join(" ") << "\n"; dcmqrscp->start(dcmqrscp_exe, dcmqrscp_args); dcmqrscp->waitForStarted(); } catch (std::exception e) { out << "ERROR: could not start server" << e.what(); return EXIT_FAILURE; } // // now push some dicom data in using storescp // QProcess *storescu = new QProcess(0); QStringList storescu_args; storescu_args << "-aec" << "CTK_AE"; storescu_args << "-aet" << "CTK_AE"; storescu_args << "localhost" << "11112"; storescu_args << dicomData1; storescu_args << dicomData2; try { out << "running client" << storescu_exe << "\n"; out << "with args" << storescu_args.join(" ") << "\n"; storescu->start(storescu_exe, storescu_args); storescu->waitForFinished(); out << "storescu Finished.\n"; out << "Standard Output:\n"; out << storescu->readAllStandardOutput(); out << "Standard Error:\n"; out << storescu->readAllStandardError(); } catch (std::exception e) { out << "ERROR: could not start client" << e.what(); return EXIT_FAILURE; } // // now query the server to see if the data arrived okay // - our database file will be updated with metadata from the query // QProcess *ctkDICOMQuery = new QProcess(0); QStringList ctkDICOMQuery_args; ctkDICOMQuery_args << ctkDICOMQuery_db_file; ctkDICOMQuery_args << "CTK_AE" << "CTK_AE"; ctkDICOMQuery_args << "localhost" << "11112"; try { out << "running client" << ctkDICOMQuery_exe << "\n"; out << "with args" << ctkDICOMQuery_args.join(" ") << "\n"; ctkDICOMQuery->start(ctkDICOMQuery_exe, ctkDICOMQuery_args); ctkDICOMQuery->waitForFinished(); out << "ctkDICOMQuery Finished.\n"; out << "Standard Output:\n"; out << ctkDICOMQuery->readAllStandardOutput(); out << "Standard Error:\n"; out << ctkDICOMQuery->readAllStandardError(); } catch (std::exception e) { out << "ERROR: could not start client" << e.what(); return EXIT_FAILURE; } // // now do a retrieve into our download directory // // this is the study id of the dicom files we load from CTKData QString studyUID("1.2.840.113619.2.135.3596.6358736.5118.1115807980.182"); QProcess *ctkDICOMRetrieve = new QProcess(0); QStringList ctkDICOMRetrieve_args; ctkDICOMRetrieve_args << studyUID; ctkDICOMRetrieve_args << ctkDICOMRetrieve_directory; ctkDICOMRetrieve_args << "CTK_AE" << "11113"; ctkDICOMRetrieve_args << "CTK_AE"; ctkDICOMRetrieve_args << "localhost" << "11112" << "CTK_CLIENT_AE"; try { out << "running client" << ctkDICOMRetrieve_exe << "\n"; out << "with args" << ctkDICOMRetrieve_args.join(" ") << "\n"; ctkDICOMRetrieve->start(ctkDICOMRetrieve_exe, ctkDICOMRetrieve_args); ctkDICOMRetrieve->waitForFinished(); out << "ctkDICOMRetrieve Finished.\n"; out << "Standard Output:\n"; out << ctkDICOMRetrieve->readAllStandardOutput(); out << "Standard Error:\n"; out << ctkDICOMRetrieve->readAllStandardError(); } catch (std::exception e) { out << "ERROR: could not start client" << e.what(); return EXIT_FAILURE; } // // clients are finished, not kill server and print output // try { dcmqrscp->kill(); dcmqrscp->waitForFinished(); out << "dcmqrscp Finished.\n"; out << "Standard Output:\n"; out << dcmqrscp->readAllStandardOutput(); out << "Standard Error:\n"; out << dcmqrscp->readAllStandardError(); } catch (std::exception e) { out << "ERROR: could not start client" << e.what(); return EXIT_FAILURE; } return EXIT_SUCCESS; } <commit_msg>STYLE: cleaned up comments in dicom qr testing code<commit_after> // Qt includes #include <QTextStream> #include <QCoreApplication> #include <QProcess> // STD includes #include <iostream> #include <cstdlib> /* * This test performs a full dicom store, query, and retrieve. * * To recreate the parts, from the CTK-superbuild directory, run: * ./CMakeExternals/Install/bin/dcmqrscp -c ./CTK-build/Testing/Temporary/dcmqrscp.cfg -d -v ./CMakeExternals/Install/bin/storescu -aec CTK_AE -aet CTK_AE localhost 11112 ./CMakeExternals/Source/CTKData/Data/DICOM/MRHEAD/*.IMA ./CMakeExternals/Install/bin/findscu -aet CTK_AE -aec COMMONTK -P -k 0010,0010=\* localhost 11112 patqry.dcm ./CTK-build/bin/ctkDICOMQuery /tmp/test.db CTK_AE CTK_AE localhost 11112 ./CTK-build/bin/ctkDICOMRetrieve 1.2.840.113619.2.135.3596.6358736.5118.1115807980.182 /tmp/hoot CTK_AE 11113 CTK_AE localhost 11112 CTK_CLIENT_AE */ int ctkDICOMApplicationTest1(int argc, char * argv []) { QCoreApplication app(argc, argv); QTextStream out(stdout); if ( argc < 10 ) { out << "ERROR: invalid arguments. Should be:\n"; out << " ctkDICOMApplicationTest1 <dcmqrscp> <configfile> <dicomData1> <dcmData2> <storescu> <ctkDICOMQuery> <ctkDICOMRetrieve> <retrieveDirectory>\n"; return EXIT_FAILURE; } QString dcmqrscp_exe (argv[1]); QString dcmqrscp_cfg (argv[2]); QString dicomData1 (argv[3]); QString dicomData2 (argv[4]); QString storescu_exe (argv[5]); QString ctkDICOMQuery_exe (argv[6]); QString ctkDICOMQuery_db_file (argv[7]); QString ctkDICOMRetrieve_exe (argv[8]); QString ctkDICOMRetrieve_directory (argv[9]); // // first, start the server process // QProcess *dcmqrscp = new QProcess(0); QStringList dcmqrscp_args; dcmqrscp_args << "--config" << dcmqrscp_cfg; dcmqrscp_args << "--debug" << "--verbose"; dcmqrscp_args << "11112"; try { out << "starting server" << dcmqrscp_exe << "\n"; out << "with args " << dcmqrscp_args.join(" ") << "\n"; dcmqrscp->start(dcmqrscp_exe, dcmqrscp_args); dcmqrscp->waitForStarted(); } catch (std::exception e) { out << "ERROR: could not start server" << e.what(); return EXIT_FAILURE; } // // now push some dicom data in using storescp // QProcess *storescu = new QProcess(0); QStringList storescu_args; storescu_args << "-aec" << "CTK_AE"; storescu_args << "-aet" << "CTK_AE"; storescu_args << "localhost" << "11112"; storescu_args << dicomData1; storescu_args << dicomData2; try { out << "running client" << storescu_exe << "\n"; out << "with args" << storescu_args.join(" ") << "\n"; storescu->start(storescu_exe, storescu_args); storescu->waitForFinished(); out << "storescu Finished.\n"; out << "Standard Output:\n"; out << storescu->readAllStandardOutput(); out << "Standard Error:\n"; out << storescu->readAllStandardError(); } catch (std::exception e) { out << "ERROR: could not start client" << e.what(); return EXIT_FAILURE; } // // now query the server to see if the data arrived okay // - our database file will be updated with metadata from the query // QProcess *ctkDICOMQuery = new QProcess(0); QStringList ctkDICOMQuery_args; ctkDICOMQuery_args << ctkDICOMQuery_db_file; ctkDICOMQuery_args << "CTK_AE" << "CTK_AE"; ctkDICOMQuery_args << "localhost" << "11112"; try { out << "running client" << ctkDICOMQuery_exe << "\n"; out << "with args" << ctkDICOMQuery_args.join(" ") << "\n"; ctkDICOMQuery->start(ctkDICOMQuery_exe, ctkDICOMQuery_args); ctkDICOMQuery->waitForFinished(); out << "ctkDICOMQuery Finished.\n"; out << "Standard Output:\n"; out << ctkDICOMQuery->readAllStandardOutput(); out << "Standard Error:\n"; out << ctkDICOMQuery->readAllStandardError(); } catch (std::exception e) { out << "ERROR: could not start client" << e.what(); return EXIT_FAILURE; } // // now do a retrieve into our download directory // // this is the study id of the dicom files we load from CTKData QString studyUID("1.2.840.113619.2.135.3596.6358736.5118.1115807980.182"); QProcess *ctkDICOMRetrieve = new QProcess(0); QStringList ctkDICOMRetrieve_args; ctkDICOMRetrieve_args << studyUID; ctkDICOMRetrieve_args << ctkDICOMRetrieve_directory; ctkDICOMRetrieve_args << "CTK_AE" << "11113"; ctkDICOMRetrieve_args << "CTK_AE"; ctkDICOMRetrieve_args << "localhost" << "11112" << "CTK_CLIENT_AE"; try { out << "running client" << ctkDICOMRetrieve_exe << "\n"; out << "with args" << ctkDICOMRetrieve_args.join(" ") << "\n"; ctkDICOMRetrieve->start(ctkDICOMRetrieve_exe, ctkDICOMRetrieve_args); ctkDICOMRetrieve->waitForFinished(); out << "ctkDICOMRetrieve Finished.\n"; out << "Standard Output:\n"; out << ctkDICOMRetrieve->readAllStandardOutput(); out << "Standard Error:\n"; out << ctkDICOMRetrieve->readAllStandardError(); } catch (std::exception e) { out << "ERROR: could not start client" << e.what(); return EXIT_FAILURE; } // // clients are finished, not kill server and print output // try { dcmqrscp->kill(); dcmqrscp->waitForFinished(); out << "dcmqrscp Finished.\n"; out << "Standard Output:\n"; out << dcmqrscp->readAllStandardOutput(); out << "Standard Error:\n"; out << dcmqrscp->readAllStandardError(); } catch (std::exception e) { out << "ERROR: could not start client" << e.what(); return EXIT_FAILURE; } return EXIT_SUCCESS; } <|endoftext|>
<commit_before>/** * Copyright (C) 2018 3D Repo Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <OdaCommon.h> #include <OdString.h> #include <toString.h> #include <DgLevelTableRecord.h> #include "geometry_dumper.h" #include "../../../../core/model/bson/repo_bson_factory.h" using namespace repo::manipulator::modelconvertor::odaHelper; void GeometryDumper::triangleOut(const OdInt32* p3Vertices, const OdGeVector3d* pNormal) { const OdGePoint3d* pVertexDataList = vertexDataList(); const OdGeVector3d* pNormals = NULL; if ((pVertexDataList + p3Vertices[0]) != (pVertexDataList + p3Vertices[1]) && (pVertexDataList + p3Vertices[0]) != (pVertexDataList + p3Vertices[2]) && (pVertexDataList + p3Vertices[1]) != (pVertexDataList + p3Vertices[2])) { std::vector<repo::lib::RepoVector3D64> vertices; for (int i = 0; i < 3; ++i) { vertices.push_back({ pVertexDataList[p3Vertices[i]].x , pVertexDataList[p3Vertices[i]].y, pVertexDataList[p3Vertices[i]].z }); } collector->addFace(vertices); } } double GeometryDumper::deviation( const OdGiDeviationType deviationType, const OdGePoint3d& pointOnCurve) const { return 0; } VectoriseDevice* GeometryDumper::device() { return static_cast<VectoriseDevice*>(OdGsBaseVectorizeView::device()); } bool GeometryDumper::doDraw(OdUInt32 i, const OdGiDrawable* pDrawable) { OdDgElementPtr pElm = OdDgElement::cast(pDrawable); OdString sClassName = toString(pElm->isA()); OdString sHandle = pElm->isDBRO() ? toString(pElm->elementId().getHandle()) : toString(OD_T("non-DbResident")); std::stringstream ss; ss << sHandle; collector->setNextMeshName(ss.str()); OdGiSubEntityTraitsData traits = effectiveTraits(); OdDgElementId idLevel = traits.layer(); if (!idLevel.isNull()) { OdDgLevelTableRecordPtr pLevel = idLevel.openObject(OdDg::kForRead); OdUInt32 iLevelEntry = pLevel->getEntryId(); std::stringstream ss; ss << pLevel->getName().c_str(); auto layerName = ss.str(); collector->setLayer(layerName); } return OdGsBaseMaterialView::doDraw(i, pDrawable); } OdCmEntityColor GeometryDumper::fixByACI(const ODCOLORREF *ids, const OdCmEntityColor &color) { if (color.isByACI() || color.isByDgnIndex()) { return OdCmEntityColor(ODGETRED(ids[color.colorIndex()]), ODGETGREEN(ids[color.colorIndex()]), ODGETBLUE(ids[color.colorIndex()])); } else if (!color.isByColor()) { return OdCmEntityColor(0, 0, 0); } return color; } OdGiMaterialItemPtr GeometryDumper::fillMaterialCache( OdGiMaterialItemPtr prevCache, OdDbStub* materialId, const OdGiMaterialTraitsData & materialData ) { auto id = (OdUInt64)(OdIntPtr)materialId; OdGiMaterialColor diffuseColor; OdGiMaterialMap diffuseMap; OdGiMaterialColor ambientColor; OdGiMaterialColor specularColor; OdGiMaterialMap specularMap; double glossFactor; double opacityPercentage; OdGiMaterialMap opacityMap; double refrIndex; OdGiMaterialMap refrMap; materialData.diffuse(diffuseColor, diffuseMap); materialData.ambient(ambientColor); materialData.specular(specularColor, specularMap, glossFactor); materialData.opacity(opacityPercentage, opacityMap); materialData.refraction(refrIndex, refrMap); OdGiMaterialMap bumpMap; materialData.bump(bumpMap); ODCOLORREF colorDiffuse(0), colorAmbient(0), colorSpecular(0); if (diffuseColor.color().colorMethod() == OdCmEntityColor::kByColor) { colorDiffuse = ODTOCOLORREF(diffuseColor.color()); } else if (diffuseColor.color().colorMethod() == OdCmEntityColor::kByACI) { colorDiffuse = OdCmEntityColor::lookUpRGB((OdUInt8)diffuseColor.color().colorIndex()); } if (ambientColor.color().colorMethod() == OdCmEntityColor::kByColor) { colorAmbient = ODTOCOLORREF(ambientColor.color()); } else if (ambientColor.color().colorMethod() == OdCmEntityColor::kByACI) { colorAmbient = OdCmEntityColor::lookUpRGB((OdUInt8)ambientColor.color().colorIndex()); } if (specularColor.color().colorMethod() == OdCmEntityColor::kByColor) { colorSpecular = ODTOCOLORREF(specularColor.color()); } else if (specularColor.color().colorMethod() == OdCmEntityColor::kByACI) { colorSpecular = OdCmEntityColor::lookUpRGB((OdUInt8)specularColor.color().colorIndex()); } OdCmEntityColor color = fixByACI(this->device()->getPalette(), effectiveTraits().trueColor()); repo_material_t material; // diffuse if (diffuseColor.method() == OdGiMaterialColor::kOverride) material.diffuse = { ODGETRED(colorDiffuse) / 255.0f, ODGETGREEN(colorDiffuse) / 255.0f, ODGETBLUE(colorDiffuse) / 255.0f, 1.0f }; else material.diffuse = { color.red() / 255.0f, color.green() / 255.0f, color.blue() / 255.0f, 1.0f }; /* TODO: texture support mData.bDiffuseChannelEnabled = (GETBIT(materialData.channelFlags(), OdGiMaterialTraits::kUseDiffuse)) ? true : false; if (mData.bDiffuseChannelEnabled && diffuseMap.source() == OdGiMaterialMap::kFile && !diffuseMap.sourceFileName().isEmpty()) { mData.bDiffuseHasTexture = true; mData.sDiffuseFileSource = diffuseMap.sourceFileName(); }*/ // specular if (specularColor.method() == OdGiMaterialColor::kOverride) material.specular = { ODGETRED(colorSpecular) / 255.0f, ODGETGREEN(colorSpecular) / 255.0f, ODGETBLUE(colorSpecular) / 255.0f, 1.0f }; else material.specular = { color.red() / 255.0f, color.green() / 255.0f, color.blue() / 255.0f, 1.0f }; material.shininessStrength = 1 - glossFactor; material.shininess = materialData.reflectivity(); // opacity material.opacity = opacityPercentage; // refraction /*mData.bRefractionChannelEnabled = (GETBIT(materialData.channelFlags(), OdGiMaterialTraits::kUseRefraction)) ? 1 : 0; mData.dRefractionIndex = materialData.reflectivity();*/ // transclucence //mData.dTranslucence = materialData.translucence(); collector->setCurrentMaterial(material); collector->stopMeshEntry(); collector->startMeshEntry(); return OdGiMaterialItemPtr(); } void GeometryDumper::init(GeometryCollector *const geoCollector) { collector = geoCollector; } void GeometryDumper::beginViewVectorization() { OdGsBaseMaterialView::beginViewVectorization(); setEyeToOutputTransform(getEyeToWorldTransform()); OdGiGeometrySimplifier::setDrawContext(OdGsBaseMaterialView::drawContext()); output().setDestGeometry((OdGiGeometrySimplifier&)*this); } void GeometryDumper::endViewVectorization() { collector->stopMeshEntry(); OdGsBaseMaterialView::endViewVectorization(); } void GeometryDumper::setMode(OdGsView::RenderMode mode) { OdGsBaseVectorizeView::m_renderMode = kGouraudShaded; m_regenerationType = kOdGiRenderCommand; OdGiGeometrySimplifier::m_renderMode = OdGsBaseVectorizeView::m_renderMode; }<commit_msg>ISSUE #271 try fix travis via char conversion 2<commit_after>/** * Copyright (C) 2018 3D Repo Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <OdaCommon.h> #include <OdString.h> #include <toString.h> #include <DgLevelTableRecord.h> #include "geometry_dumper.h" #include "../../../../core/model/bson/repo_bson_factory.h" using namespace repo::manipulator::modelconvertor::odaHelper; void GeometryDumper::triangleOut(const OdInt32* p3Vertices, const OdGeVector3d* pNormal) { const OdGePoint3d* pVertexDataList = vertexDataList(); const OdGeVector3d* pNormals = NULL; if ((pVertexDataList + p3Vertices[0]) != (pVertexDataList + p3Vertices[1]) && (pVertexDataList + p3Vertices[0]) != (pVertexDataList + p3Vertices[2]) && (pVertexDataList + p3Vertices[1]) != (pVertexDataList + p3Vertices[2])) { std::vector<repo::lib::RepoVector3D64> vertices; for (int i = 0; i < 3; ++i) { vertices.push_back({ pVertexDataList[p3Vertices[i]].x , pVertexDataList[p3Vertices[i]].y, pVertexDataList[p3Vertices[i]].z }); } collector->addFace(vertices); } } double GeometryDumper::deviation( const OdGiDeviationType deviationType, const OdGePoint3d& pointOnCurve) const { return 0; } VectoriseDevice* GeometryDumper::device() { return static_cast<VectoriseDevice*>(OdGsBaseVectorizeView::device()); } bool GeometryDumper::doDraw(OdUInt32 i, const OdGiDrawable* pDrawable) { OdDgElementPtr pElm = OdDgElement::cast(pDrawable); OdString sClassName = toString(pElm->isA()); OdString sHandle = pElm->isDBRO() ? toString(pElm->elementId().getHandle()) : toString(OD_T("non-DbResident")); std::stringstream ss; ss << sHandle.c_str(); collector->setNextMeshName(ss.str()); OdGiSubEntityTraitsData traits = effectiveTraits(); OdDgElementId idLevel = traits.layer(); if (!idLevel.isNull()) { OdDgLevelTableRecordPtr pLevel = idLevel.openObject(OdDg::kForRead); OdUInt32 iLevelEntry = pLevel->getEntryId(); std::stringstream ss; ss << pLevel->getName().c_str(); auto layerName = ss.str(); collector->setLayer(layerName); } return OdGsBaseMaterialView::doDraw(i, pDrawable); } OdCmEntityColor GeometryDumper::fixByACI(const ODCOLORREF *ids, const OdCmEntityColor &color) { if (color.isByACI() || color.isByDgnIndex()) { return OdCmEntityColor(ODGETRED(ids[color.colorIndex()]), ODGETGREEN(ids[color.colorIndex()]), ODGETBLUE(ids[color.colorIndex()])); } else if (!color.isByColor()) { return OdCmEntityColor(0, 0, 0); } return color; } OdGiMaterialItemPtr GeometryDumper::fillMaterialCache( OdGiMaterialItemPtr prevCache, OdDbStub* materialId, const OdGiMaterialTraitsData & materialData ) { auto id = (OdUInt64)(OdIntPtr)materialId; OdGiMaterialColor diffuseColor; OdGiMaterialMap diffuseMap; OdGiMaterialColor ambientColor; OdGiMaterialColor specularColor; OdGiMaterialMap specularMap; double glossFactor; double opacityPercentage; OdGiMaterialMap opacityMap; double refrIndex; OdGiMaterialMap refrMap; materialData.diffuse(diffuseColor, diffuseMap); materialData.ambient(ambientColor); materialData.specular(specularColor, specularMap, glossFactor); materialData.opacity(opacityPercentage, opacityMap); materialData.refraction(refrIndex, refrMap); OdGiMaterialMap bumpMap; materialData.bump(bumpMap); ODCOLORREF colorDiffuse(0), colorAmbient(0), colorSpecular(0); if (diffuseColor.color().colorMethod() == OdCmEntityColor::kByColor) { colorDiffuse = ODTOCOLORREF(diffuseColor.color()); } else if (diffuseColor.color().colorMethod() == OdCmEntityColor::kByACI) { colorDiffuse = OdCmEntityColor::lookUpRGB((OdUInt8)diffuseColor.color().colorIndex()); } if (ambientColor.color().colorMethod() == OdCmEntityColor::kByColor) { colorAmbient = ODTOCOLORREF(ambientColor.color()); } else if (ambientColor.color().colorMethod() == OdCmEntityColor::kByACI) { colorAmbient = OdCmEntityColor::lookUpRGB((OdUInt8)ambientColor.color().colorIndex()); } if (specularColor.color().colorMethod() == OdCmEntityColor::kByColor) { colorSpecular = ODTOCOLORREF(specularColor.color()); } else if (specularColor.color().colorMethod() == OdCmEntityColor::kByACI) { colorSpecular = OdCmEntityColor::lookUpRGB((OdUInt8)specularColor.color().colorIndex()); } OdCmEntityColor color = fixByACI(this->device()->getPalette(), effectiveTraits().trueColor()); repo_material_t material; // diffuse if (diffuseColor.method() == OdGiMaterialColor::kOverride) material.diffuse = { ODGETRED(colorDiffuse) / 255.0f, ODGETGREEN(colorDiffuse) / 255.0f, ODGETBLUE(colorDiffuse) / 255.0f, 1.0f }; else material.diffuse = { color.red() / 255.0f, color.green() / 255.0f, color.blue() / 255.0f, 1.0f }; /* TODO: texture support mData.bDiffuseChannelEnabled = (GETBIT(materialData.channelFlags(), OdGiMaterialTraits::kUseDiffuse)) ? true : false; if (mData.bDiffuseChannelEnabled && diffuseMap.source() == OdGiMaterialMap::kFile && !diffuseMap.sourceFileName().isEmpty()) { mData.bDiffuseHasTexture = true; mData.sDiffuseFileSource = diffuseMap.sourceFileName(); }*/ // specular if (specularColor.method() == OdGiMaterialColor::kOverride) material.specular = { ODGETRED(colorSpecular) / 255.0f, ODGETGREEN(colorSpecular) / 255.0f, ODGETBLUE(colorSpecular) / 255.0f, 1.0f }; else material.specular = { color.red() / 255.0f, color.green() / 255.0f, color.blue() / 255.0f, 1.0f }; material.shininessStrength = 1 - glossFactor; material.shininess = materialData.reflectivity(); // opacity material.opacity = opacityPercentage; // refraction /*mData.bRefractionChannelEnabled = (GETBIT(materialData.channelFlags(), OdGiMaterialTraits::kUseRefraction)) ? 1 : 0; mData.dRefractionIndex = materialData.reflectivity();*/ // transclucence //mData.dTranslucence = materialData.translucence(); collector->setCurrentMaterial(material); collector->stopMeshEntry(); collector->startMeshEntry(); return OdGiMaterialItemPtr(); } void GeometryDumper::init(GeometryCollector *const geoCollector) { collector = geoCollector; } void GeometryDumper::beginViewVectorization() { OdGsBaseMaterialView::beginViewVectorization(); setEyeToOutputTransform(getEyeToWorldTransform()); OdGiGeometrySimplifier::setDrawContext(OdGsBaseMaterialView::drawContext()); output().setDestGeometry((OdGiGeometrySimplifier&)*this); } void GeometryDumper::endViewVectorization() { collector->stopMeshEntry(); OdGsBaseMaterialView::endViewVectorization(); } void GeometryDumper::setMode(OdGsView::RenderMode mode) { OdGsBaseVectorizeView::m_renderMode = kGouraudShaded; m_regenerationType = kOdGiRenderCommand; OdGiGeometrySimplifier::m_renderMode = OdGsBaseVectorizeView::m_renderMode; }<|endoftext|>
<commit_before>#include <iostream> using namespace std; enum CPU_Rank {P1=1,P2,P3,P4,P5,P6,P7}; class CPU{ private: CPU_Rank rank; int frequency; float voltage; public: CPU(CPU_Rank r,int f, float v){ rank = r; frequency = f; voltage = v; cout<<"构造了一个CPU!"<<endl; } ~CPU() {cout<<"析构了一个CPU!"<<endl;} CPU_Rank getrank() const {return rank;} int getfrequency() const {return frequency;} float getvoltage() const {return voltage;} void setrank(CPU_Rank r){rank = r;} void setfrequency(int f){frequency = f;} void setvoltage(float v){voltage = v;} void Run(){cout<<"CPU 开始运行!"<<endl;} void Stop(){cout<<"CPU 停止运行!"<<endl;} }; int main(){ CPU a(P6,300,2.8); a.Run(); a.Stop(); return 0; }<commit_msg>new practice.<commit_after>#include <iostream> using namespace std; enum CPU_Rank {P1=1,P2,P3,P4,P5,P6,P7}; class CPU{ private: CPU_Rank rank; int frequency; float voltage; public: CPU(CPU_Rank r,int f, float v){ rank = r; frequency = f; voltage = v; cout<<"构造了一个CPU!"<<endl; } ~CPU() {cout<<"析构了一个CPU!"<<endl;} CPU_Rank getrank() const {return rank;} int getfrequency() const {return frequency;} float getvoltage() const {return voltage;} void setrank(CPU_Rank r){rank = r;} void setfrequency(int f){frequency = f;} void setvoltage(float v){voltage = v;} void Run(){cout<<"CPU 开始运行!"<<endl;} void Stop(){cout<<"CPU 停止运行!"<<endl;} }; enum RAM_Type {DDR2=2,DDR3,DDR4}; class RAM{ private: enum RAM_Type type; unsigned int frequency; unsigned int size; public: RAM(RAM_Type t, unsigned int f, unsigned int s){ type = t; frequency = f; size = s; cout<<"构造了一个RAM!"<<endl; } ~RAM() {cout<<"析构了一个RAM!"<<endl;} RAM_Type getType() const {return type;} unsigned int getFrequency() const {return frequency;} unsigned int getSize() const {return size;} void setType(RAM_Type t) {type = t;} void setFrequency(unsigned int f) {frequency = f;} void setSize(unsigned int s) {size = s;} void Run() {cout<<"RAM 开始运行!"<<endl;} void Stop() {cout<<"RAM 停止运行!"<<endl;} }; enum CDROM_Interface {SATA, USB}; enum CDROM_Install_type {external, built_in}; class CDROM{ private: enum CDROM_Interface interface_type; unsigned int cache_size; enum CDROM_Install_type install_type; public: CDROM(CDROM_Interface i, unsigned int s, CDROM_Install_type it){ interface_type = i; cache_size = s; install_type = it; cout<<"构造了一个CDROM!"<<endl; } ~CDROM() {cout<<"析构了一个CDROM!"<<endl;} CDROM_Interface getInterfaceType() {return interface_type;} unsigned int getCacheSize() {return cache_size;} CDROM_Install_type getInstallType() {return install_type;} void setInterfaceType(CDROM_Interface i) {interface_type = i;} void setCacheSize(unsigned int s) {cache_size = s;} void setInstallType(CDROM_Install_type it) {install_type = it;} void Run() {cout<<"CDROM 开始运行!"<<endl;} void Stop() {cout<<"CDROM 停止运行!"<<endl;} }; class COMPUTER{ private: CPU my_cpu; RAM my_ram; CDROM my_cdrom; unsigned int storage_size; unsigned int bandwidth; public: COMPUTER(CPU c, RAM r, CDROM cd, unsigned int s, unsigned int b); ~COMPUTER() {cout<<"析构了一个COMPUTER!"<<endl;} void Run(){ my_cpu.Run(); my_ram.Run(); my_cdrom.Run(); cout<<"COMPUTER 开始运行!"<<endl; } void Stop(){ my_cpu.Stop(); my_ram.Stop(); my_cdrom.Stop(); cout<<"COMPUTER 停止运行!"<<endl; } }; COMPUTER::COMPUTER(CPU c, RAM r, CDROM cd, unsigned int s, unsigned int b):my_cpu(c),my_ram(r),my_cdrom(cd){ storage_size = s; bandwidth = b; cout<<"构造了一个COMPUTER!"<<endl; }; int main(){ CPU a(P6,300,2.8); a.Run(); a.Stop(); cout<<"*********************\n"; RAM b(DDR3,1600,8); b.Run(); b.Stop(); cout<<"*********************\n"; CDROM c(SATA,2,built_in); c.Run(); c.Stop(); cout<<"*********************\n"; COMPUTER my_computer(a,b,c,128,10); cout<<"*********************\n"; my_computer.Run(); my_computer.Stop(); cout<<"*********************\n"; return 0; }<|endoftext|>
<commit_before>#include "btree/get.hpp" #include "errors.hpp" #include <boost/shared_ptr.hpp> #include "btree/delete_expired.hpp" #include "btree/btree_data_provider.hpp" #include "btree/internal_node.hpp" #include "btree/leaf_node.hpp" #include "btree/operations.hpp" #include "buffer_cache/buf_lock.hpp" #include "store.hpp" get_result_t btree_get(const store_key_t &store_key, btree_slice_t *slice, order_token_t token) { btree_key_buffer_t kbuffer(store_key); btree_key_t *key = kbuffer.key(); slice->assert_thread(); on_thread_t mover(slice->home_thread()); got_superblock_t got; get_btree_superblock(slice, rwi_read, token, &got); memcached_value_sizer_t sizer(slice->cache()->get_block_size()); keyvalue_location_t kv_location; find_keyvalue_location_for_read(&sizer, &got, key, &kv_location); if (!kv_location.value) { return get_result_t(); } const btree_value_t *value = reinterpret_cast<const btree_value_t *>(kv_location.value.get()); if (value->expired()) { // If the value is expired, delete it in the background. btree_delete_expired(store_key, slice); return get_result_t(); } boost::shared_ptr<value_data_provider_t> dp(value_data_provider_t::create(value, kv_location.txn.get())); return get_result_t(dp, value->mcflags(), 0); } <commit_msg>Removed on_thread_t usage in get.cc that was asserted against anyway.<commit_after>#include "btree/get.hpp" #include "errors.hpp" #include <boost/shared_ptr.hpp> #include "btree/delete_expired.hpp" #include "btree/btree_data_provider.hpp" #include "btree/internal_node.hpp" #include "btree/leaf_node.hpp" #include "btree/operations.hpp" #include "buffer_cache/buf_lock.hpp" #include "store.hpp" get_result_t btree_get(const store_key_t &store_key, btree_slice_t *slice, order_token_t token) { btree_key_buffer_t kbuffer(store_key); btree_key_t *key = kbuffer.key(); slice->assert_thread(); got_superblock_t got; get_btree_superblock(slice, rwi_read, token, &got); memcached_value_sizer_t sizer(slice->cache()->get_block_size()); keyvalue_location_t kv_location; find_keyvalue_location_for_read(&sizer, &got, key, &kv_location); if (!kv_location.value) { return get_result_t(); } const btree_value_t *value = reinterpret_cast<const btree_value_t *>(kv_location.value.get()); if (value->expired()) { // If the value is expired, delete it in the background. btree_delete_expired(store_key, slice); return get_result_t(); } boost::shared_ptr<value_data_provider_t> dp(value_data_provider_t::create(value, kv_location.txn.get())); return get_result_t(dp, value->mcflags(), 0); } <|endoftext|>
<commit_before>// Copyright 2015 Google Inc. All rights reserved // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // +build ignore #include "exec.h" #include <stdio.h> #include <stdlib.h> #include <memory> #include <unordered_map> #include <unordered_set> #include <utility> #include <vector> #include "dep.h" #include "eval.h" #include "fileutil.h" #include "log.h" #include "string_piece.h" #include "strutil.h" #include "value.h" #include "var.h" namespace { class Executor; class AutoVar : public Var { public: virtual const char* Flavor() const override { return "undefined"; } virtual const char* Origin() const override { return "automatic"; } virtual void AppendVar(Evaluator*, Value*) override { CHECK(false); } virtual StringPiece String() const override { ERROR("$(value %s) is not implemented yet", sym_); return ""; } virtual string DebugString() const override { return string("AutoVar(") + sym_ + ")"; } protected: AutoVar(Executor* ex, const char* sym) : ex_(ex), sym_(sym) {} virtual ~AutoVar() = default; Executor* ex_; const char* sym_; }; #define DECLARE_AUTO_VAR_CLASS(name) \ class name : public AutoVar { \ public: \ name(Executor* ex, const char* sym) \ : AutoVar(ex, sym) {} \ virtual ~name() = default; \ virtual void Eval(Evaluator* ev, string* s) const override; \ } DECLARE_AUTO_VAR_CLASS(AutoAtVar); DECLARE_AUTO_VAR_CLASS(AutoLessVar); DECLARE_AUTO_VAR_CLASS(AutoHatVar); DECLARE_AUTO_VAR_CLASS(AutoPlusVar); DECLARE_AUTO_VAR_CLASS(AutoStarVar); class AutoSuffixDVar : public AutoVar { public: AutoSuffixDVar(Executor* ex, const char* sym, Var* wrapped) : AutoVar(ex, sym), wrapped_(wrapped) { } virtual ~AutoSuffixDVar() = default; virtual void Eval(Evaluator* ev, string* s) const override; private: Var* wrapped_; }; class AutoSuffixFVar : public AutoVar { public: AutoSuffixFVar(Executor* ex, const char* sym, Var* wrapped) : AutoVar(ex, sym), wrapped_(wrapped) {} virtual ~AutoSuffixFVar() = default; virtual void Eval(Evaluator* ev, string* s) const override; private: Var* wrapped_; }; struct Runner { Runner() : echo(true), ignore_error(false) { } StringPiece output; shared_ptr<string> cmd; bool echo; bool ignore_error; //StringPiece shell; }; class Executor { public: explicit Executor(Evaluator* ev) : ev_(ev) { Vars* vars = ev_->mutable_vars(); #define INSERT_AUTO_VAR(name, sym) do { \ Var* v = new name(this, sym); \ (*vars)[STRING_PIECE(sym)] = v; \ (*vars)[STRING_PIECE(sym"D")] = new AutoSuffixDVar(this, sym"D", v); \ (*vars)[STRING_PIECE(sym"F")] = new AutoSuffixFVar(this, sym"F", v); \ } while (0) INSERT_AUTO_VAR(AutoAtVar, "@"); INSERT_AUTO_VAR(AutoLessVar, "<"); INSERT_AUTO_VAR(AutoHatVar, "^"); INSERT_AUTO_VAR(AutoPlusVar, "+"); INSERT_AUTO_VAR(AutoStarVar, "*"); } void ExecNode(DepNode* n, DepNode* needed_by) { if (done_[n->output]) return; done_[n->output] = true; LOG("ExecNode: %s for %s", n->output.as_string().c_str(), needed_by ? needed_by->output.as_string().c_str() : "(null)"); for (DepNode* d : n->deps) { if (d->is_order_only && Exists(d->output)) { continue; } // TODO: Check the timestamp. if (Exists(d->output)) { continue; } ExecNode(d, n); } vector<Runner*> runners; CreateRunners(n, &runners); for (Runner* runner : runners) { if (runner->echo) { printf("%s\n", runner->cmd->c_str()); fflush(stdout); } system(runner->cmd->c_str()); delete runner; } } void CreateRunners(DepNode* n, vector<Runner*>* runners) { ev_->set_current_scope(n->rule_vars); current_dep_node_ = n; for (Value* v : n->cmds) { shared_ptr<string> cmd = v->Eval(ev_); while (true) { size_t index = cmd->find('\n'); if (index == string::npos) break; Runner* runner = new Runner; runner->output = n->output; runner->cmd = make_shared<string>(cmd->substr(0, index)); runners->push_back(runner); cmd = make_shared<string>(cmd->substr(index + 1)); } Runner* runner = new Runner; runner->output = n->output; runner->cmd = cmd; runners->push_back(runner); continue; } ev_->set_current_scope(NULL); } const DepNode* current_dep_node() const { return current_dep_node_; } private: Vars* vars_; Evaluator* ev_; unordered_map<StringPiece, bool> done_; DepNode* current_dep_node_; }; void AutoAtVar::Eval(Evaluator*, string* s) const { AppendString(ex_->current_dep_node()->output, s); } void AutoLessVar::Eval(Evaluator*, string* s) const { auto& ai = ex_->current_dep_node()->actual_inputs; if (!ai.empty()) AppendString(ai[0], s); } void AutoHatVar::Eval(Evaluator*, string* s) const { unordered_set<StringPiece> seen; WordWriter ww(s); for (StringPiece ai : ex_->current_dep_node()->actual_inputs) { if (seen.insert(ai).second) ww.Write(ai); } } void AutoPlusVar::Eval(Evaluator*, string* s) const { WordWriter ww(s); for (StringPiece ai : ex_->current_dep_node()->actual_inputs) { ww.Write(ai); } } void AutoStarVar::Eval(Evaluator*, string* s) const { AppendString(StripExt(ex_->current_dep_node()->output), s); } void AutoSuffixDVar::Eval(Evaluator* ev, string* s) const { string buf; wrapped_->Eval(ev, &buf); WordWriter ww(s); for (StringPiece tok : WordScanner(buf)) { ww.Write(Dirname(tok)); } } void AutoSuffixFVar::Eval(Evaluator* ev, string* s) const { string buf; wrapped_->Eval(ev, &buf); WordWriter ww(s); for (StringPiece tok : WordScanner(buf)) { ww.Write(Basename(tok)); } } } // namespace void Exec(const vector<DepNode*>& roots, Evaluator* ev) { unique_ptr<Executor> executor(new Executor(ev)); for (DepNode* root : roots) { executor->ExecNode(root, NULL); } } <commit_msg>[C++] Skip empty command<commit_after>// Copyright 2015 Google Inc. All rights reserved // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // +build ignore #include "exec.h" #include <stdio.h> #include <stdlib.h> #include <memory> #include <unordered_map> #include <unordered_set> #include <utility> #include <vector> #include "dep.h" #include "eval.h" #include "fileutil.h" #include "log.h" #include "string_piece.h" #include "strutil.h" #include "value.h" #include "var.h" namespace { class Executor; class AutoVar : public Var { public: virtual const char* Flavor() const override { return "undefined"; } virtual const char* Origin() const override { return "automatic"; } virtual void AppendVar(Evaluator*, Value*) override { CHECK(false); } virtual StringPiece String() const override { ERROR("$(value %s) is not implemented yet", sym_); return ""; } virtual string DebugString() const override { return string("AutoVar(") + sym_ + ")"; } protected: AutoVar(Executor* ex, const char* sym) : ex_(ex), sym_(sym) {} virtual ~AutoVar() = default; Executor* ex_; const char* sym_; }; #define DECLARE_AUTO_VAR_CLASS(name) \ class name : public AutoVar { \ public: \ name(Executor* ex, const char* sym) \ : AutoVar(ex, sym) {} \ virtual ~name() = default; \ virtual void Eval(Evaluator* ev, string* s) const override; \ } DECLARE_AUTO_VAR_CLASS(AutoAtVar); DECLARE_AUTO_VAR_CLASS(AutoLessVar); DECLARE_AUTO_VAR_CLASS(AutoHatVar); DECLARE_AUTO_VAR_CLASS(AutoPlusVar); DECLARE_AUTO_VAR_CLASS(AutoStarVar); class AutoSuffixDVar : public AutoVar { public: AutoSuffixDVar(Executor* ex, const char* sym, Var* wrapped) : AutoVar(ex, sym), wrapped_(wrapped) { } virtual ~AutoSuffixDVar() = default; virtual void Eval(Evaluator* ev, string* s) const override; private: Var* wrapped_; }; class AutoSuffixFVar : public AutoVar { public: AutoSuffixFVar(Executor* ex, const char* sym, Var* wrapped) : AutoVar(ex, sym), wrapped_(wrapped) {} virtual ~AutoSuffixFVar() = default; virtual void Eval(Evaluator* ev, string* s) const override; private: Var* wrapped_; }; struct Runner { Runner() : echo(true), ignore_error(false) { } StringPiece output; shared_ptr<string> cmd; bool echo; bool ignore_error; //StringPiece shell; }; class Executor { public: explicit Executor(Evaluator* ev) : ev_(ev) { Vars* vars = ev_->mutable_vars(); #define INSERT_AUTO_VAR(name, sym) do { \ Var* v = new name(this, sym); \ (*vars)[STRING_PIECE(sym)] = v; \ (*vars)[STRING_PIECE(sym"D")] = new AutoSuffixDVar(this, sym"D", v); \ (*vars)[STRING_PIECE(sym"F")] = new AutoSuffixFVar(this, sym"F", v); \ } while (0) INSERT_AUTO_VAR(AutoAtVar, "@"); INSERT_AUTO_VAR(AutoLessVar, "<"); INSERT_AUTO_VAR(AutoHatVar, "^"); INSERT_AUTO_VAR(AutoPlusVar, "+"); INSERT_AUTO_VAR(AutoStarVar, "*"); } void ExecNode(DepNode* n, DepNode* needed_by) { if (done_[n->output]) return; done_[n->output] = true; LOG("ExecNode: %s for %s", n->output.as_string().c_str(), needed_by ? needed_by->output.as_string().c_str() : "(null)"); for (DepNode* d : n->deps) { if (d->is_order_only && Exists(d->output)) { continue; } // TODO: Check the timestamp. if (Exists(d->output)) { continue; } ExecNode(d, n); } vector<Runner*> runners; CreateRunners(n, &runners); for (Runner* runner : runners) { if (runner->echo) { printf("%s\n", runner->cmd->c_str()); fflush(stdout); } system(runner->cmd->c_str()); delete runner; } } void CreateRunners(DepNode* n, vector<Runner*>* runners) { ev_->set_current_scope(n->rule_vars); current_dep_node_ = n; for (Value* v : n->cmds) { shared_ptr<string> cmd = v->Eval(ev_); if (TrimSpace(*cmd) == "") continue; while (true) { size_t index = cmd->find('\n'); if (index == string::npos) break; Runner* runner = new Runner; runner->output = n->output; runner->cmd = make_shared<string>(cmd->substr(0, index)); runners->push_back(runner); cmd = make_shared<string>(cmd->substr(index + 1)); } Runner* runner = new Runner; runner->output = n->output; runner->cmd = cmd; runners->push_back(runner); continue; } ev_->set_current_scope(NULL); } const DepNode* current_dep_node() const { return current_dep_node_; } private: Vars* vars_; Evaluator* ev_; unordered_map<StringPiece, bool> done_; DepNode* current_dep_node_; }; void AutoAtVar::Eval(Evaluator*, string* s) const { AppendString(ex_->current_dep_node()->output, s); } void AutoLessVar::Eval(Evaluator*, string* s) const { auto& ai = ex_->current_dep_node()->actual_inputs; if (!ai.empty()) AppendString(ai[0], s); } void AutoHatVar::Eval(Evaluator*, string* s) const { unordered_set<StringPiece> seen; WordWriter ww(s); for (StringPiece ai : ex_->current_dep_node()->actual_inputs) { if (seen.insert(ai).second) ww.Write(ai); } } void AutoPlusVar::Eval(Evaluator*, string* s) const { WordWriter ww(s); for (StringPiece ai : ex_->current_dep_node()->actual_inputs) { ww.Write(ai); } } void AutoStarVar::Eval(Evaluator*, string* s) const { AppendString(StripExt(ex_->current_dep_node()->output), s); } void AutoSuffixDVar::Eval(Evaluator* ev, string* s) const { string buf; wrapped_->Eval(ev, &buf); WordWriter ww(s); for (StringPiece tok : WordScanner(buf)) { ww.Write(Dirname(tok)); } } void AutoSuffixFVar::Eval(Evaluator* ev, string* s) const { string buf; wrapped_->Eval(ev, &buf); WordWriter ww(s); for (StringPiece tok : WordScanner(buf)) { ww.Write(Basename(tok)); } } } // namespace void Exec(const vector<DepNode*>& roots, Evaluator* ev) { unique_ptr<Executor> executor(new Executor(ev)); for (DepNode* root : roots) { executor->ExecNode(root, NULL); } } <|endoftext|>
<commit_before>#include <turbo/memory/alignment.hpp> #include <cstdint> #include <gtest/gtest.h> namespace tme = turbo::memory; TEST(alignment_test, align_single_element) { std::uint8_t buffer[64]; std::uint8_t* pointer1 = &buffer[0]; if ((reinterpret_cast<std::uintptr_t>(pointer1) % 2U) == 0) { ++pointer1; } std::uint8_t* expected1 = pointer1 + 1; std::size_t size1 = sizeof(buffer); void* tmp1 = static_cast<void*>(pointer1); tme::align(sizeof(std::uint16_t), sizeof(std::uint16_t), tmp1, size1); pointer1 = static_cast<std::uint8_t*>(tmp1); EXPECT_EQ(expected1, pointer1) << "Pointer is not aligned"; } <commit_msg>added more test cases<commit_after>#include <turbo/memory/alignment.hpp> #include <cstdint> #include <gtest/gtest.h> namespace tme = turbo::memory; TEST(alignment_test, align_single_element) { std::uint8_t buffer1[64]; std::uint8_t* actual_ptr1 = &buffer1[0]; std::size_t actual_size1 = sizeof(buffer1); if ((reinterpret_cast<std::uintptr_t>(actual_ptr1) % 2U) == 0) { ++actual_ptr1; } std::uint8_t* expected_ptr1 = actual_ptr1 + 1; std::size_t expected_size1 = actual_size1 - 1; void* tmp1 = static_cast<void*>(actual_ptr1); tme::align(sizeof(std::uint16_t), sizeof(std::uint16_t), tmp1, actual_size1); actual_ptr1 = static_cast<std::uint8_t*>(tmp1); EXPECT_EQ(expected_ptr1, actual_ptr1) << "Pointer is not aligned"; EXPECT_EQ(expected_size1, actual_size1) << "Incorrect available space"; std::uint8_t buffer2[64]; std::uint8_t* actual_ptr2 = &buffer2[0]; std::size_t actual_size2 = sizeof(buffer2); if ((reinterpret_cast<std::uintptr_t>(actual_ptr2) % 2U) == 0) { ++actual_ptr2; } std::uint8_t* expected_ptr2 = actual_ptr2 + 7; std::size_t expected_size2 = actual_size2 - 7; void* tmp2 = static_cast<void*>(actual_ptr2); tme::align(sizeof(std::uint64_t), sizeof(std::uint64_t), tmp2, actual_size2); actual_ptr2 = static_cast<std::uint8_t*>(tmp2); EXPECT_EQ(expected_ptr2, actual_ptr2) << "Pointer is not aligned"; EXPECT_EQ(expected_size2, actual_size2) << "Incorrect available space"; } TEST(alignment_test, align_multiple_element) { std::uint8_t buffer1[64]; std::uint8_t* actual_ptr1 = &buffer1[0]; std::size_t actual_size1 = sizeof(buffer1); if ((reinterpret_cast<std::uintptr_t>(actual_ptr1) % 2U) == 0) { ++actual_ptr1; } std::uint8_t* expected_ptr1 = actual_ptr1 + 3; std::size_t expected_size1 = actual_size1 - 3; void* tmp1 = static_cast<void*>(actual_ptr1); tme::align(sizeof(std::uint32_t), sizeof(std::uint16_t), tmp1, actual_size1); actual_ptr1 = static_cast<std::uint8_t*>(tmp1); EXPECT_EQ(expected_ptr1, actual_ptr1) << "Pointer is not aligned"; EXPECT_EQ(expected_size1, actual_size1) << "Incorrect available space"; } <|endoftext|>
<commit_before>// Test that a module constructor can not map memory over the MSan heap // (without MAP_FIXED, of course). Current implementation ensures this by // mapping the heap early, in __msan_init. // // RUN: %clangxx_msan -O0 %s -o %t_1 // RUN: %clangxx_msan -O0 -DHEAP_ADDRESS=$(%run %t_1) %s -o %t_2 && %run %t_2 #include <assert.h> #include <stdio.h> #include <sys/mman.h> #include <stdlib.h> #ifdef HEAP_ADDRESS struct A { A() { void *const hint = reinterpret_cast<void *>(HEAP_ADDRESS); void *p = mmap(hint, 4096, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); // This address must be already mapped. Check that mmap() succeeds, but at a // different address. assert(p != reinterpret_cast<void *>(-1)); assert(p != hint); } } a; #endif int main() { void *p = malloc(10); printf("0x%zx\n", reinterpret_cast<size_t>(p) & (~0xfff)); free(p); } <commit_msg>[msan] Disable allocator_mapping test on mips64 and aarch64.<commit_after>// Test that a module constructor can not map memory over the MSan heap // (without MAP_FIXED, of course). Current implementation ensures this by // mapping the heap early, in __msan_init. // // RUN: %clangxx_msan -O0 %s -o %t_1 // RUN: %clangxx_msan -O0 -DHEAP_ADDRESS=$(%run %t_1) %s -o %t_2 && %run %t_2 // // This test only makes sense for the 64-bit allocator. The 32-bit allocator // does not have a fixed mapping. Exclude platforms that use the 32-bit // allocator. // UNSUPPORTED: mips64,aarch64 #include <assert.h> #include <stdio.h> #include <sys/mman.h> #include <stdlib.h> #ifdef HEAP_ADDRESS struct A { A() { void *const hint = reinterpret_cast<void *>(HEAP_ADDRESS); void *p = mmap(hint, 4096, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); // This address must be already mapped. Check that mmap() succeeds, but at a // different address. assert(p != reinterpret_cast<void *>(-1)); assert(p != hint); } } a; #endif int main() { void *p = malloc(10); printf("0x%zx\n", reinterpret_cast<size_t>(p) & (~0xfff)); free(p); } <|endoftext|>
<commit_before>// Copyright 2011 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // Author: nadavs@google.com <Nadav Samet> // Jin Qing (http://blog.csdn.net/jq0123) #include <iostream> #include <boost/optional/optional.hpp> #include <boost/thread/thread.hpp> #include <glog/logging.h> #include <gtest/gtest.h> #include <zmq.hpp> #include "rpcz/application.hpp" #include "rpcz/connection.hpp" #include "rpcz/connection_manager.hpp" #include "rpcz/connection_manager_ptr.hpp" #include "rpcz/replier.hpp" #include "rpcz/rpc_channel.hpp" #include "rpcz/server.hpp" #include "rpcz/sync_event.hpp" #include "proto/search.pb.h" #include "proto/search.rpcz.h" using namespace std; namespace rpcz { class SearchServiceImpl : public SearchService { public: SearchServiceImpl() { } ~SearchServiceImpl() { } virtual void Search( const SearchRequest& request, replier replier_copy) { if (request.query() == "timeout") { // We "lose" the request. return; } SearchResponse response; response.add_results("The search for " + request.query()); response.add_results("is great"); replier_copy.send(response); } }; class server_test : public ::testing::Test { public: server_test() : context_(new zmq::context_t(1)) /* scoped_ptr */ { EXPECT_TRUE(connection_manager::is_destroyed()); application::set_zmq_context(context_.get()); application::set_connection_manager_threads(10); connection_.reset(new connection); server_.reset(new server); start_server(); } ~server_test() { // terminate the context, which will cause the thread to quit. application::terminate(); server_.reset(); service_.reset(); connection_.reset(); EXPECT_TRUE(connection_manager::is_destroyed()); context_.reset(); } void start_server() { rpcz::connection_manager_ptr cm = rpcz::connection_manager::get(); service_.reset(new SearchServiceImpl); server_->register_singleton_service(*service_); server_->bind("inproc://myserver.frontend"); *connection_ = cm->connect("inproc://myserver.frontend"); } protected: // destruct in reversed order scoped_ptr<zmq::context_t> context_; // destruct last scoped_ptr<connection> connection_; scoped_ptr<SearchServiceImpl> service_; // Server must destruct before service. (Or unregister services before destruct.) scoped_ptr<server> server_; }; struct handler { rpcz::sync_event sync; SearchResponse response; boost::optional<rpc_error> error; void operator()(const rpc_error* e, const SearchResponse& resp) { if (e) { error.reset(*e); } else { response = resp; } sync.signal(); } }; /* Test all kinds of request interfaces. . Sync or async . Explicit deadline or implicit default deadline . Return response or use output parameter (only for sync) . Explicit error handler or implicit default error handler (only for async) There are 4 sync interfaces and 4 async interfaces. Ordered as the declaration in search.rpcz.h. */ // Async interfaces: TEST_F(server_test, AsyncRequestWithTimeout) { SearchService_Stub stub(rpc_channel::create(*connection_), true); SearchRequest request; request.set_query("timeout"); handler hdl; stub.async_Search(request, boost::ref(hdl), 1/*ms*/); hdl.sync.wait(); ASSERT_TRUE(hdl.error); ASSERT_EQ(rpc_response_header::DEADLINE_EXCEEDED, hdl.error->get_status()); } TEST_F(server_test, AsyncRequest) { SearchService_Stub stub(rpc_channel::create(*connection_), true); SearchRequest request; request.set_query("stone"); handler hdl; stub.async_Search(request, boost::ref(hdl)); hdl.sync.wait(); ASSERT_FALSE(hdl.error); ASSERT_EQ(2, hdl.response.results_size()); ASSERT_EQ("The search for stone", hdl.response.results(0)); } TEST_F(server_test, AsyncOnewayRequest) { SearchService_Stub stub(rpc_channel::create(*connection_), true); SearchRequest request; request.set_query("rocket"); // XXX fix crash on reset... //stub.async_Search(request, 0/*ms*/); //stub.async_Search(request, 1/*ms*/); //stub.async_Search(request, 10/*ms*/); //stub.async_Search(request, 1000/*ms*/); //stub.async_Search(request, 10000/*ms*/); //stub.async_Search(request, -1/*ms*/); } TEST_F(server_test, AsyncOnewayRequestDefaultMs) { SearchService_Stub stub(rpc_channel::create(*connection_), true); SearchRequest request; request.set_query("robot"); // XXX fix crash on reset... //stub.async_Search(request); } // Sync interfaces: TEST_F(server_test, SyncRequest) { SearchService_Stub stub(rpc_channel::create(*connection_), true); SearchRequest request; request.set_query("student"); SearchResponse response; stub.Search(request, 5000/*ms*/, &response); ASSERT_EQ(2, response.results_size()); ASSERT_EQ("The search for student", response.results(0)); } TEST_F(server_test, SyncRequestDefaultMs) { SearchService_Stub stub(rpc_channel::create(*connection_), true); SearchRequest request; request.set_query("stupid"); SearchResponse response; stub.Search(request, &response); ASSERT_EQ(2, response.results_size()); ASSERT_EQ("The search for stupid", response.results(0)); } TEST_F(server_test, SyncRequestReturn) { SearchService_Stub stub(rpc_channel::create(*connection_), true); SearchRequest request; request.set_query("spool"); SearchResponse response = stub.Search(request, 5000/*ms*/); ASSERT_EQ(2, response.results_size()); ASSERT_EQ("The search for spool", response.results(0)); } TEST_F(server_test, SyncRequestReturnDefaultMs) { SearchService_Stub stub(rpc_channel::create(*connection_), true); SearchRequest request; request.set_query("star"); SearchResponse response = stub.Search(request); ASSERT_EQ(2, response.results_size()); ASSERT_EQ("The search for star", response.results(0)); } // Other interfaces: TEST_F(server_test, SetDefaulDeadlineMs) { SearchService_Stub stub(rpc_channel::create(*connection_), true); SearchRequest request; SearchResponse response; request.set_query("timeout"); stub.set_default_deadline_ms(1); try { stub.Search(request, &response); ASSERT_TRUE(false); } catch (const rpc_error& error) { ASSERT_EQ(status::DEADLINE_EXCEEDED, error.get_status()); return; } ASSERT_TRUE(false); } } // namespace <commit_msg>fix test<commit_after>// Copyright 2011 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // Author: nadavs@google.com <Nadav Samet> // Jin Qing (http://blog.csdn.net/jq0123) #include <iostream> #include <boost/optional/optional.hpp> #include <boost/thread/thread.hpp> #include <glog/logging.h> #include <gtest/gtest.h> #include <zmq.hpp> #include "rpcz/application.hpp" #include "rpcz/connection.hpp" #include "rpcz/connection_manager.hpp" #include "rpcz/connection_manager_ptr.hpp" #include "rpcz/replier.hpp" #include "rpcz/rpc_channel.hpp" #include "rpcz/server.hpp" #include "rpcz/sync_event.hpp" #include "proto/search.pb.h" #include "proto/search.rpcz.h" using namespace std; namespace rpcz { class SearchServiceImpl : public SearchService { public: SearchServiceImpl() { } ~SearchServiceImpl() { } virtual void Search( const SearchRequest& request, replier replier_copy) { if (request.query() == "timeout") { // We "lose" the request. return; } SearchResponse response; response.add_results("The search for " + request.query()); response.add_results("is great"); replier_copy.send(response); } }; class server_test : public ::testing::Test { public: server_test() : context_(new zmq::context_t(1)) /* scoped_ptr */ { EXPECT_TRUE(connection_manager::is_destroyed()); application::set_zmq_context(context_.get()); application::set_connection_manager_threads(10); connection_.reset(new connection); server_.reset(new server); start_server(); } ~server_test() { // terminate the context, which will cause the thread to quit. application::terminate(); server_.reset(); service_.reset(); connection_.reset(); EXPECT_TRUE(connection_manager::is_destroyed()); context_.reset(); } void start_server() { rpcz::connection_manager_ptr cm = rpcz::connection_manager::get(); service_.reset(new SearchServiceImpl); server_->register_singleton_service(*service_); server_->bind("inproc://myserver.frontend"); *connection_ = cm->connect("inproc://myserver.frontend"); } protected: // destruct in reversed order scoped_ptr<zmq::context_t> context_; // destruct last scoped_ptr<connection> connection_; scoped_ptr<SearchServiceImpl> service_; // Server must destruct before service. (Or unregister services before destruct.) scoped_ptr<server> server_; }; struct handler { rpcz::sync_event sync; SearchResponse response; boost::optional<rpc_error> error; void operator()(const rpc_error* e, const SearchResponse& resp) { if (e) { error.reset(*e); } else { response = resp; } sync.signal(); } }; /* Test all kinds of request interfaces. . Sync or async . Explicit deadline or implicit default deadline . Return response or use output parameter (only for sync) . Explicit error handler or implicit default error handler (only for async) There are 4 sync interfaces and 4 async interfaces. Ordered as the declaration in search.rpcz.h. */ // Async interfaces: TEST_F(server_test, AsyncRequestWithTimeout) { SearchService_Stub stub(rpc_channel::create(*connection_), true); SearchRequest request; request.set_query("timeout"); handler hdl; stub.async_Search(request, boost::ref(hdl), 1/*ms*/); hdl.sync.wait(); ASSERT_TRUE(hdl.error); ASSERT_EQ(rpc_response_header::DEADLINE_EXCEEDED, hdl.error->get_status()); } TEST_F(server_test, AsyncRequest) { SearchService_Stub stub(rpc_channel::create(*connection_), true); SearchRequest request; request.set_query("stone"); handler hdl; stub.async_Search(request, boost::ref(hdl)); hdl.sync.wait(); ASSERT_FALSE(hdl.error); ASSERT_EQ(2, hdl.response.results_size()); ASSERT_EQ("The search for stone", hdl.response.results(0)); } TEST_F(server_test, AsyncOnewayRequest) { SearchService_Stub stub(rpc_channel::create(*connection_), true); SearchRequest request; request.set_query("rocket"); stub.async_Search(request, 0/*ms*/); stub.async_Search(request, 1/*ms*/); stub.async_Search(request, 10/*ms*/); stub.async_Search(request, 1000/*ms*/); stub.async_Search(request, 10000/*ms*/); stub.async_Search(request, -1/*ms*/); // Sync request to end. Crash on reset if not. (void)stub.Search(request); } TEST_F(server_test, AsyncOnewayRequestDefaultMs) { SearchService_Stub stub(rpc_channel::create(*connection_), true); SearchRequest request; request.set_query("robot"); stub.async_Search(request); // Sync request to end. Crash on reset if not. (void)stub.Search(request); } // Sync interfaces: TEST_F(server_test, SyncRequest) { SearchService_Stub stub(rpc_channel::create(*connection_), true); SearchRequest request; request.set_query("student"); SearchResponse response; stub.Search(request, 5000/*ms*/, &response); ASSERT_EQ(2, response.results_size()); ASSERT_EQ("The search for student", response.results(0)); } TEST_F(server_test, SyncRequestDefaultMs) { SearchService_Stub stub(rpc_channel::create(*connection_), true); SearchRequest request; request.set_query("stupid"); SearchResponse response; stub.Search(request, &response); ASSERT_EQ(2, response.results_size()); ASSERT_EQ("The search for stupid", response.results(0)); } TEST_F(server_test, SyncRequestReturn) { SearchService_Stub stub(rpc_channel::create(*connection_), true); SearchRequest request; request.set_query("spool"); SearchResponse response = stub.Search(request, 5000/*ms*/); ASSERT_EQ(2, response.results_size()); ASSERT_EQ("The search for spool", response.results(0)); } TEST_F(server_test, SyncRequestReturnDefaultMs) { SearchService_Stub stub(rpc_channel::create(*connection_), true); SearchRequest request; request.set_query("star"); SearchResponse response = stub.Search(request); ASSERT_EQ(2, response.results_size()); ASSERT_EQ("The search for star", response.results(0)); } // Other interfaces: TEST_F(server_test, SetDefaulDeadlineMs) { SearchService_Stub stub(rpc_channel::create(*connection_), true); SearchRequest request; SearchResponse response; request.set_query("timeout"); stub.set_default_deadline_ms(1); try { stub.Search(request, &response); ASSERT_TRUE(false); } catch (const rpc_error& error) { ASSERT_EQ(status::DEADLINE_EXCEEDED, error.get_status()); return; } ASSERT_TRUE(false); } } // namespace <|endoftext|>
<commit_before>/*========================================================================= * * Copyright UMC Utrecht and contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ #include "itkParameterFileParser.h" #include <itksys/SystemTools.hxx> #include <itksys/RegularExpression.hxx> #include <fstream> namespace itk { /** * **************** Constructor *************** */ ParameterFileParser::ParameterFileParser() = default; /** * **************** Destructor *************** */ ParameterFileParser ::~ParameterFileParser() = default; /** * **************** GetParameterMap *************** */ const ParameterFileParser::ParameterMapType & ParameterFileParser::GetParameterMap(void) const { return this->m_ParameterMap; } // end GetParameterMap() /** * **************** ReadParameterFile *************** */ void ParameterFileParser::ReadParameterFile(void) { /** Perform some basic checks. */ this->BasicFileChecking(); /** Open the parameter file for reading. */ std::ifstream parameterFile(this->m_ParameterFileName); /** Check if it opened. */ if (!parameterFile.is_open()) { itkExceptionMacro(<< "ERROR: could not open " << this->m_ParameterFileName << " for reading."); } /** Clear the map. */ this->m_ParameterMap.clear(); /** Loop over the parameter file, line by line. */ std::string lineIn; std::string lineOut; while (parameterFile.good()) { /** Extract a line. */ itksys::SystemTools::GetLineFromStream(parameterFile, lineIn); /** Check this line. */ const bool validLine = this->CheckLine(lineIn, lineOut); if (validLine) { /** Get the parameter name from this line and store it. */ this->GetParameterFromLine(lineIn, lineOut); } // Otherwise, we simply ignore this line } } // end ReadParameterFile() /** * **************** BasicFileChecking *************** */ void ParameterFileParser::BasicFileChecking(void) const { /** Check if the file name is given. */ if (this->m_ParameterFileName.empty()) { itkExceptionMacro(<< "ERROR: FileName has not been set."); } /** Basic error checking: existence. */ const bool exists = itksys::SystemTools::FileExists(this->m_ParameterFileName); if (!exists) { itkExceptionMacro(<< "ERROR: the file " << this->m_ParameterFileName << " does not exist."); } /** Basic error checking: file or directory. */ const bool isDir = itksys::SystemTools::FileIsDirectory(this->m_ParameterFileName); if (isDir) { itkExceptionMacro(<< "ERROR: the file " << this->m_ParameterFileName << " is a directory."); } /** Check the extension. */ const std::string ext = itksys::SystemTools::GetFilenameLastExtension(this->m_ParameterFileName); if (ext != ".txt") { itkExceptionMacro(<< "ERROR: the file " << this->m_ParameterFileName << " should be a text file (*.txt)."); } } // end BasicFileChecking() /** * **************** CheckLine *************** */ bool ParameterFileParser::CheckLine(const std::string & lineIn, std::string & lineOut) const { /** Preprocessing of lineIn: * 1) Replace tabs with spaces * 2) Remove everything after comment sign // * 3) Remove leading spaces * 4) Remove trailing spaces */ lineOut = lineIn; itksys::SystemTools::ReplaceString(lineOut, "\t", " "); itksys::RegularExpression commentPart("//"); if (commentPart.find(lineOut)) { lineOut = lineOut.substr(0, commentPart.start()); } itksys::RegularExpression leadingSpaces("^[ ]*(.*)"); leadingSpaces.find(lineOut); lineOut = leadingSpaces.match(1); itksys::RegularExpression trailingSpaces("[ \t]+$"); if (trailingSpaces.find(lineOut)) { lineOut = lineOut.substr(0, trailingSpaces.start()); } /** * Checks: * 1. Empty line -> false * 2. Comment (line starts with "//") -> false * 3. Line is not between brackets (...) -> exception * 4. Line contains less than two words -> exception * * Otherwise return true. */ /** 1. Check for non-empty lines. */ itksys::RegularExpression reNonEmptyLine("[^ ]+"); const bool match1 = reNonEmptyLine.find(lineOut); if (!match1) { return false; } /** 2. Check for comments. */ itksys::RegularExpression reComment("^//"); const bool match2 = reComment.find(lineOut); if (match2) { return false; } /** 3. Check if line is between brackets. */ if (!itksys::SystemTools::StringStartsWith(lineOut, "(") || !itksys::SystemTools::StringEndsWith(lineOut, ")")) { const std::string hint = "Line is not between brackets: \"(...)\"."; this->ThrowException(lineIn, hint); } /** Remove brackets. */ lineOut = lineOut.substr(1, lineOut.size() - 2); /** 4. Check: the line should contain at least two words. */ itksys::RegularExpression reTwoWords("([ ]+)([^ ]+)"); const bool match4 = reTwoWords.find(lineOut); if (!match4) { const std::string hint = "Line does not contain a parameter name and value."; this->ThrowException(lineIn, hint); } /** At this point we know its at least a line containing a parameter. * However, this line can still be invalid, for example: * (string &^%^*) * This will be checked later. */ return true; } // end CheckLine() /** * **************** GetParameterFromLine *************** */ void ParameterFileParser::GetParameterFromLine(const std::string & fullLine, const std::string & line) { /** A line has a parameter name followed by one or more parameters. * They are all separated by one or more spaces (all tabs have been * removed previously) or by quotes in case of strings. So, * 1) we split the line at the spaces or quotes * 2) the first one is the parameter name * 3) the other strings that are not a series of spaces, are parameter values */ /** 1) Split the line. */ std::vector<std::string> splittedLine; this->SplitLine(fullLine, line, splittedLine); /** 2) Get the parameter name. */ std::string parameterName = splittedLine[0]; itksys::SystemTools::ReplaceString(parameterName, " ", ""); splittedLine.erase(splittedLine.begin()); /** 3) Get the parameter values. */ std::vector<std::string> parameterValues; for (const auto & value : splittedLine) { if (!value.empty()) { parameterValues.push_back(value); } } /** 4) Perform some checks on the parameter name. */ itksys::RegularExpression reInvalidCharacters1("[.,:;!@#$%^&-+|<>?]"); const bool match = reInvalidCharacters1.find(parameterName); if (match) { const std::string hint = "The parameter \"" + parameterName + "\" contains invalid characters (.,:;!@#$%^&-+|<>?)."; this->ThrowException(fullLine, hint); } /** 5) Perform checks on the parameter values. */ itksys::RegularExpression reInvalidCharacters2("[,;!@#$%&|<>?]"); for (const auto & parameterValue : parameterValues) { /** For all entries some characters are not allowed. */ if (reInvalidCharacters2.find(parameterValue)) { const std::string hint = "The parameter value \"" + parameterValue + "\" contains invalid characters (,;!@#$%&|<>?)."; this->ThrowException(fullLine, hint); } } /** 6) Insert this combination in the parameter map. */ if (this->m_ParameterMap.count(parameterName)) { const std::string hint = "The parameter \"" + parameterName + "\" is specified more than once."; this->ThrowException(fullLine, hint); } else { this->m_ParameterMap.insert(make_pair(parameterName, parameterValues)); } } // end GetParameterFromLine() /** * **************** SplitLine *************** */ void ParameterFileParser::SplitLine(const std::string & fullLine, const std::string & line, std::vector<std::string> & splittedLine) const { splittedLine.clear(); splittedLine.resize(1); /** Count the number of quotes in the line. If it is an odd value, the * line contains an error; strings should start and end with a quote, so * the total number of quotes is even. */ std::size_t numQuotes = itksys::SystemTools::CountChar(line.c_str(), '"'); if (numQuotes % 2 == 1) { /** An invalid parameter line. */ const std::string hint = "This line has an odd number of quotes (\")."; this->ThrowException(fullLine, hint); } /** Loop over the line. */ unsigned int index = 0; numQuotes = 0; for (const char currentChar : line) { if (currentChar == '"') { /** Start a new element. */ splittedLine.push_back(""); index++; numQuotes++; } else if (currentChar == ' ') { /** Only start a new element if it is not a quote, otherwise just add * the space to the string. */ if (numQuotes % 2 == 0) { splittedLine.push_back(""); index++; } else { splittedLine[index].push_back(currentChar); } } else { /** Add this character to the element. */ splittedLine[index].push_back(currentChar); } } } // end SplitLine() /** * **************** ThrowException *************** */ void ParameterFileParser::ThrowException(const std::string & line, const std::string & hint) const { /** Construct an error message. */ const std::string errorMessage = "ERROR: the following line in your parameter file is invalid: \n\"" + line + "\"\n" + hint + "\nPlease correct you parameter file!"; /** Throw exception. */ itkExceptionMacro(<< errorMessage); } // end ThrowException() /** * **************** ReturnParameterFileAsString *************** */ std::string ParameterFileParser::ReturnParameterFileAsString(void) { /** Perform some basic checks. */ this->BasicFileChecking(); /** Open the parameter file for reading. */ std::ifstream parameterFile(this->m_ParameterFileName); /** Check if it opened. */ if (!parameterFile.is_open()) { itkExceptionMacro(<< "ERROR: could not open " << this->m_ParameterFileName << " for reading."); } /** Loop over the parameter file, line by line. */ std::string line; std::string output; while (parameterFile.good()) { /** Extract a line. */ itksys::SystemTools::GetLineFromStream(parameterFile, line); // \todo: returns bool output += line + "\n"; } /** Return the string. */ return output; } // end ReturnParameterFileAsString() } // end namespace itk <commit_msg>ENH: Lift ParameterFileParser restrictions on chars of parameter values<commit_after>/*========================================================================= * * Copyright UMC Utrecht and contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ #include "itkParameterFileParser.h" #include <itksys/SystemTools.hxx> #include <itksys/RegularExpression.hxx> #include <fstream> namespace itk { /** * **************** Constructor *************** */ ParameterFileParser::ParameterFileParser() = default; /** * **************** Destructor *************** */ ParameterFileParser ::~ParameterFileParser() = default; /** * **************** GetParameterMap *************** */ const ParameterFileParser::ParameterMapType & ParameterFileParser::GetParameterMap(void) const { return this->m_ParameterMap; } // end GetParameterMap() /** * **************** ReadParameterFile *************** */ void ParameterFileParser::ReadParameterFile(void) { /** Perform some basic checks. */ this->BasicFileChecking(); /** Open the parameter file for reading. */ std::ifstream parameterFile(this->m_ParameterFileName); /** Check if it opened. */ if (!parameterFile.is_open()) { itkExceptionMacro(<< "ERROR: could not open " << this->m_ParameterFileName << " for reading."); } /** Clear the map. */ this->m_ParameterMap.clear(); /** Loop over the parameter file, line by line. */ std::string lineIn; std::string lineOut; while (parameterFile.good()) { /** Extract a line. */ itksys::SystemTools::GetLineFromStream(parameterFile, lineIn); /** Check this line. */ const bool validLine = this->CheckLine(lineIn, lineOut); if (validLine) { /** Get the parameter name from this line and store it. */ this->GetParameterFromLine(lineIn, lineOut); } // Otherwise, we simply ignore this line } } // end ReadParameterFile() /** * **************** BasicFileChecking *************** */ void ParameterFileParser::BasicFileChecking(void) const { /** Check if the file name is given. */ if (this->m_ParameterFileName.empty()) { itkExceptionMacro(<< "ERROR: FileName has not been set."); } /** Basic error checking: existence. */ const bool exists = itksys::SystemTools::FileExists(this->m_ParameterFileName); if (!exists) { itkExceptionMacro(<< "ERROR: the file " << this->m_ParameterFileName << " does not exist."); } /** Basic error checking: file or directory. */ const bool isDir = itksys::SystemTools::FileIsDirectory(this->m_ParameterFileName); if (isDir) { itkExceptionMacro(<< "ERROR: the file " << this->m_ParameterFileName << " is a directory."); } /** Check the extension. */ const std::string ext = itksys::SystemTools::GetFilenameLastExtension(this->m_ParameterFileName); if (ext != ".txt") { itkExceptionMacro(<< "ERROR: the file " << this->m_ParameterFileName << " should be a text file (*.txt)."); } } // end BasicFileChecking() /** * **************** CheckLine *************** */ bool ParameterFileParser::CheckLine(const std::string & lineIn, std::string & lineOut) const { /** Preprocessing of lineIn: * 1) Replace tabs with spaces * 2) Remove everything after comment sign // * 3) Remove leading spaces * 4) Remove trailing spaces */ lineOut = lineIn; itksys::SystemTools::ReplaceString(lineOut, "\t", " "); itksys::RegularExpression commentPart("//"); if (commentPart.find(lineOut)) { lineOut = lineOut.substr(0, commentPart.start()); } itksys::RegularExpression leadingSpaces("^[ ]*(.*)"); leadingSpaces.find(lineOut); lineOut = leadingSpaces.match(1); itksys::RegularExpression trailingSpaces("[ \t]+$"); if (trailingSpaces.find(lineOut)) { lineOut = lineOut.substr(0, trailingSpaces.start()); } /** * Checks: * 1. Empty line -> false * 2. Comment (line starts with "//") -> false * 3. Line is not between brackets (...) -> exception * 4. Line contains less than two words -> exception * * Otherwise return true. */ /** 1. Check for non-empty lines. */ itksys::RegularExpression reNonEmptyLine("[^ ]+"); const bool match1 = reNonEmptyLine.find(lineOut); if (!match1) { return false; } /** 2. Check for comments. */ itksys::RegularExpression reComment("^//"); const bool match2 = reComment.find(lineOut); if (match2) { return false; } /** 3. Check if line is between brackets. */ if (!itksys::SystemTools::StringStartsWith(lineOut, "(") || !itksys::SystemTools::StringEndsWith(lineOut, ")")) { const std::string hint = "Line is not between brackets: \"(...)\"."; this->ThrowException(lineIn, hint); } /** Remove brackets. */ lineOut = lineOut.substr(1, lineOut.size() - 2); /** 4. Check: the line should contain at least two words. */ itksys::RegularExpression reTwoWords("([ ]+)([^ ]+)"); const bool match4 = reTwoWords.find(lineOut); if (!match4) { const std::string hint = "Line does not contain a parameter name and value."; this->ThrowException(lineIn, hint); } /** At this point we know its at least a line containing a parameter. * However, this line can still be invalid, for example: * (string &^%^*) * This will be checked later. */ return true; } // end CheckLine() /** * **************** GetParameterFromLine *************** */ void ParameterFileParser::GetParameterFromLine(const std::string & fullLine, const std::string & line) { /** A line has a parameter name followed by one or more parameters. * They are all separated by one or more spaces (all tabs have been * removed previously) or by quotes in case of strings. So, * 1) we split the line at the spaces or quotes * 2) the first one is the parameter name * 3) the other strings that are not a series of spaces, are parameter values */ /** 1) Split the line. */ std::vector<std::string> splittedLine; this->SplitLine(fullLine, line, splittedLine); /** 2) Get the parameter name. */ std::string parameterName = splittedLine[0]; itksys::SystemTools::ReplaceString(parameterName, " ", ""); splittedLine.erase(splittedLine.begin()); /** 3) Get the parameter values. */ std::vector<std::string> parameterValues; for (const auto & value : splittedLine) { if (!value.empty()) { parameterValues.push_back(value); } } /** 4) Perform some checks on the parameter name. */ itksys::RegularExpression reInvalidCharacters1("[.,:;!@#$%^&-+|<>?]"); const bool match = reInvalidCharacters1.find(parameterName); if (match) { const std::string hint = "The parameter \"" + parameterName + "\" contains invalid characters (.,:;!@#$%^&-+|<>?)."; this->ThrowException(fullLine, hint); } /** 5) Insert this combination in the parameter map. */ if (this->m_ParameterMap.count(parameterName)) { const std::string hint = "The parameter \"" + parameterName + "\" is specified more than once."; this->ThrowException(fullLine, hint); } else { this->m_ParameterMap.insert(make_pair(parameterName, parameterValues)); } } // end GetParameterFromLine() /** * **************** SplitLine *************** */ void ParameterFileParser::SplitLine(const std::string & fullLine, const std::string & line, std::vector<std::string> & splittedLine) const { splittedLine.clear(); splittedLine.resize(1); /** Count the number of quotes in the line. If it is an odd value, the * line contains an error; strings should start and end with a quote, so * the total number of quotes is even. */ std::size_t numQuotes = itksys::SystemTools::CountChar(line.c_str(), '"'); if (numQuotes % 2 == 1) { /** An invalid parameter line. */ const std::string hint = "This line has an odd number of quotes (\")."; this->ThrowException(fullLine, hint); } /** Loop over the line. */ unsigned int index = 0; numQuotes = 0; for (const char currentChar : line) { if (currentChar == '"') { /** Start a new element. */ splittedLine.push_back(""); index++; numQuotes++; } else if (currentChar == ' ') { /** Only start a new element if it is not a quote, otherwise just add * the space to the string. */ if (numQuotes % 2 == 0) { splittedLine.push_back(""); index++; } else { splittedLine[index].push_back(currentChar); } } else { /** Add this character to the element. */ splittedLine[index].push_back(currentChar); } } } // end SplitLine() /** * **************** ThrowException *************** */ void ParameterFileParser::ThrowException(const std::string & line, const std::string & hint) const { /** Construct an error message. */ const std::string errorMessage = "ERROR: the following line in your parameter file is invalid: \n\"" + line + "\"\n" + hint + "\nPlease correct you parameter file!"; /** Throw exception. */ itkExceptionMacro(<< errorMessage); } // end ThrowException() /** * **************** ReturnParameterFileAsString *************** */ std::string ParameterFileParser::ReturnParameterFileAsString(void) { /** Perform some basic checks. */ this->BasicFileChecking(); /** Open the parameter file for reading. */ std::ifstream parameterFile(this->m_ParameterFileName); /** Check if it opened. */ if (!parameterFile.is_open()) { itkExceptionMacro(<< "ERROR: could not open " << this->m_ParameterFileName << " for reading."); } /** Loop over the parameter file, line by line. */ std::string line; std::string output; while (parameterFile.good()) { /** Extract a line. */ itksys::SystemTools::GetLineFromStream(parameterFile, line); // \todo: returns bool output += line + "\n"; } /** Return the string. */ return output; } // end ReturnParameterFileAsString() } // end namespace itk <|endoftext|>
<commit_before>#define _CRT_RAND_S // For Windows, rand_s #include <gtest/gtest.h> #include <array> #include <chrono> #include <future> #include <random> #ifdef _WIN32 #include <stdlib.h> #define rand_r rand_s #define INC_SRT_WIN_WINTIME // exclude gettimeofday from srt headers #else typedef int SOCKET; #define INVALID_SOCKET ((SOCKET)-1) #define closesocket close #endif #include"platform_sys.h" #include "srt.h" #include "netinet_any.h" #include "api.h" using namespace std; class TestConnection : public ::testing::Test { protected: TestConnection() { // initialization code here } ~TestConnection() { // cleanup any pending stuff, but no exceptions allowed } // It should be as much as possible, but how many sockets can // be withstood, depends on the platform. Currently used CI test // servers seem not to withstand more than 240. static const size_t NSOCK = 60; protected: // SetUp() is run immediately before a test starts. void SetUp() override { ASSERT_EQ(srt_startup(), 0); m_sa.sin_family = AF_INET; m_sa.sin_addr.s_addr = INADDR_ANY; m_server_sock = srt_create_socket(); ASSERT_NE(m_server_sock, SRT_INVALID_SOCK); // Find a port not used by another service. int bind_res = 0; const sockaddr* psa = reinterpret_cast<const sockaddr*>(&m_sa); for (int port = 5000; port <= 5100; ++port) { m_sa.sin_port = htons(port); bind_res = srt_bind(m_server_sock, psa, sizeof m_sa); if (bind_res == 0) { cerr << "Running test on port " << port << "\n"; break; } } ASSERT_GE(bind_res, 0) << "srt_bind returned " << bind_res << ": " << srt_getlasterror_str(); ASSERT_EQ(inet_pton(AF_INET, "127.0.0.1", &m_sa.sin_addr), 1); // Fill the buffer with random data std::random_device rnd_device; std::mt19937 gen(rnd_device()); std::uniform_int_distribution<short> dis(-128, 127); std::generate(m_buf.begin(), m_buf.end(), [dis, gen]() mutable { return (char)dis(gen); }); cout << "Generated: " << static_cast<int>(m_buf[0]) << ", " << static_cast<int>(m_buf[1]) << std::endl; ASSERT_NE(srt_listen(m_server_sock, NSOCK), -1); } void TearDown() override { srt_cleanup(); } void AcceptLoop() { for (;;) { sockaddr_any addr; int len = sizeof addr; int acp = srt_accept(m_server_sock, addr.get(), &len); if (acp == -1) { cerr << "[T] Accept error at " << m_accepted.size() << "/" << NSOCK << ": " << srt_getlasterror_str() << endl; break; } m_accepted.push_back(acp); } cerr << "[T] Closing those accepted ones\n"; m_accept_exit = true; for (const auto s : m_accepted) { srt_close(s); } cerr << "[T] End Accept Loop\n"; } protected: sockaddr_in m_sa = sockaddr_in(); SRTSOCKET m_server_sock = SRT_INVALID_SOCK; vector<SRTSOCKET> m_accepted; std::array<char, SRT_LIVE_DEF_PLSIZE> m_buf; SRTSOCKET m_connections[NSOCK]; volatile bool m_accept_exit = false; }; // This test establishes multiple connections to a single SRT listener on a localhost port. // Packets are submitted for sending to all those connections in a non-blocking mode. // Then all connections are closed. Some sockets may potentially still have undelivered packets. // This test tries to reproduce the issue described in #1182, and fixed by #1315. TEST_F(TestConnection, Multiple) { const sockaddr_in lsa = m_sa; const sockaddr* psa = reinterpret_cast<const sockaddr*>(&lsa); auto ex = std::async([this] { return AcceptLoop(); }); cerr << "Opening " << NSOCK << " connections\n"; for (size_t i = 0; i < NSOCK; i++) { m_connections[i] = srt_create_socket(); EXPECT_NE(m_connections[i], SRT_INVALID_SOCK); // Give it 60s timeout, many platforms fail to process // so many connections in a short time. int conntimeo = 60; srt_setsockflag(m_connections[i], SRTO_CONNTIMEO, &conntimeo, sizeof conntimeo); //cerr << "Connecting #" << i << " to " << sockaddr_any(psa).str() << "...\n"; //cerr << "Connecting to: " << sockaddr_any(psa).str() << endl; ASSERT_NE(srt_connect(m_connections[i], psa, sizeof lsa), SRT_ERROR); // Set now async sending so that sending isn't blocked int no = 0; ASSERT_NE(srt_setsockflag(m_connections[i], SRTO_SNDSYN, &no, sizeof no), -1); } for (size_t j = 1; j <= 100; j++) { for (size_t i = 0; i < NSOCK; i++) { EXPECT_GT(srt_send(m_connections[i], m_buf.data(), (int) m_buf.size()), 0); } } cerr << "Sending finished, closing caller sockets\n"; for (size_t i = 0; i < NSOCK; i++) { EXPECT_EQ(srt_close(m_connections[i]), SRT_SUCCESS); } EXPECT_FALSE(m_accept_exit) << "AcceptLoop already broken for some reason!"; // Up to this moment the server sock should survive cerr << "Closing server socket\n"; // Close server socket to break the accept loop EXPECT_EQ(srt_close(m_server_sock), 0); cerr << "Synchronize with the accepting thread\n"; ex.wait(); } <commit_msg>[tests] Fixed async launch TestConnection.Multiple<commit_after>#define _CRT_RAND_S // For Windows, rand_s #include <gtest/gtest.h> #include <array> #include <chrono> #include <future> #include <random> #ifdef _WIN32 #include <stdlib.h> #define rand_r rand_s #define INC_SRT_WIN_WINTIME // exclude gettimeofday from srt headers #else typedef int SOCKET; #define INVALID_SOCKET ((SOCKET)-1) #define closesocket close #endif #include"platform_sys.h" #include "srt.h" #include "netinet_any.h" #include "api.h" using namespace std; class TestConnection : public ::testing::Test { protected: TestConnection() { // initialization code here } ~TestConnection() { // cleanup any pending stuff, but no exceptions allowed } // It should be as much as possible, but how many sockets can // be withstood, depends on the platform. Currently used CI test // servers seem not to withstand more than 240. static const size_t NSOCK = 60; protected: // SetUp() is run immediately before a test starts. void SetUp() override { ASSERT_EQ(srt_startup(), 0); m_sa.sin_family = AF_INET; m_sa.sin_addr.s_addr = INADDR_ANY; m_server_sock = srt_create_socket(); ASSERT_NE(m_server_sock, SRT_INVALID_SOCK); // Find a port not used by another service. int bind_res = 0; const sockaddr* psa = reinterpret_cast<const sockaddr*>(&m_sa); for (int port = 5000; port <= 5100; ++port) { m_sa.sin_port = htons(port); bind_res = srt_bind(m_server_sock, psa, sizeof m_sa); if (bind_res == 0) { cerr << "Running test on port " << port << "\n"; break; } } ASSERT_GE(bind_res, 0) << "srt_bind returned " << bind_res << ": " << srt_getlasterror_str(); ASSERT_EQ(inet_pton(AF_INET, "127.0.0.1", &m_sa.sin_addr), 1); // Fill the buffer with random data std::random_device rnd_device; std::mt19937 gen(rnd_device()); std::uniform_int_distribution<short> dis(-128, 127); std::generate(m_buf.begin(), m_buf.end(), [dis, gen]() mutable { return (char)dis(gen); }); ASSERT_NE(srt_listen(m_server_sock, NSOCK), -1); } void TearDown() override { srt_cleanup(); } void AcceptLoop() { for (;;) { sockaddr_any addr; int len = sizeof addr; int acp = srt_accept(m_server_sock, addr.get(), &len); if (acp == -1) { cerr << "[T] Accept error at " << m_accepted.size() << "/" << NSOCK << ": " << srt_getlasterror_str() << endl; break; } m_accepted.push_back(acp); } cerr << "[T] Closing those accepted ones\n"; m_accept_exit = true; for (const auto s : m_accepted) { srt_close(s); } cerr << "[T] End Accept Loop\n"; } protected: sockaddr_in m_sa = sockaddr_in(); SRTSOCKET m_server_sock = SRT_INVALID_SOCK; vector<SRTSOCKET> m_accepted; std::array<char, SRT_LIVE_DEF_PLSIZE> m_buf; SRTSOCKET m_connections[NSOCK]; volatile bool m_accept_exit = false; }; // This test establishes multiple connections to a single SRT listener on a localhost port. // Packets are submitted for sending to all those connections in a non-blocking mode. // Then all connections are closed. Some sockets may potentially still have undelivered packets. // This test tries to reproduce the issue described in #1182, and fixed by #1315. TEST_F(TestConnection, Multiple) { const sockaddr_in lsa = m_sa; const sockaddr* psa = reinterpret_cast<const sockaddr*>(&lsa); auto ex = std::async(std::launch::async, [this] { return AcceptLoop(); }); cerr << "Opening " << NSOCK << " connections\n"; for (size_t i = 0; i < NSOCK; i++) { m_connections[i] = srt_create_socket(); EXPECT_NE(m_connections[i], SRT_INVALID_SOCK); // Give it 60s timeout, many platforms fail to process // so many connections in a short time. int conntimeo = 60; srt_setsockflag(m_connections[i], SRTO_CONNTIMEO, &conntimeo, sizeof conntimeo); //cerr << "Connecting #" << i << " to " << sockaddr_any(psa).str() << "...\n"; //cerr << "Connecting to: " << sockaddr_any(psa).str() << endl; ASSERT_NE(srt_connect(m_connections[i], psa, sizeof lsa), SRT_ERROR); // Set now async sending so that sending isn't blocked int no = 0; ASSERT_NE(srt_setsockflag(m_connections[i], SRTO_SNDSYN, &no, sizeof no), -1); } for (size_t j = 1; j <= 100; j++) { for (size_t i = 0; i < NSOCK; i++) { EXPECT_GT(srt_send(m_connections[i], m_buf.data(), (int) m_buf.size()), 0); } } cerr << "Sending finished, closing caller sockets\n"; for (size_t i = 0; i < NSOCK; i++) { EXPECT_EQ(srt_close(m_connections[i]), SRT_SUCCESS); } EXPECT_FALSE(m_accept_exit) << "AcceptLoop already broken for some reason!"; // Up to this moment the server sock should survive cerr << "Closing server socket\n"; // Close server socket to break the accept loop EXPECT_EQ(srt_close(m_server_sock), 0); cerr << "Synchronize with the accepting thread\n"; ex.wait(); cerr << "Synchronization done\n"; } <|endoftext|>
<commit_before>/* Copyright (c) 2010, The Mineserver Project All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the The Mineserver Project nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <cstdlib> #include <cstdio> #include <iostream> #include <deque> #include <fstream> #include <vector> #include <ctime> #include <math.h> #ifdef WIN32 #include <winsock2.h> #else #include <netinet/in.h> #include <string.h> #endif #include "logger.h" #include "constants.h" #include "tools.h" #include "map.h" #include "user.h" #include "chat.h" #include "config.h" #include "tools.h" #include "physics.h" namespace { void reportError(User *user, std::string message) { Chat::get().sendMsg(user, COLOR_DARK_MAGENTA + "Error! " + COLOR_RED + message, Chat::USER); } void playerList(User *user, std::string command, std::deque<std::string> args) { Chat::get().sendUserlist(user); } void about(User *user, std::string command, std::deque<std::string> args) { Chat::get().sendMsg(user, COLOR_DARK_MAGENTA + Conf::get().sValue("servername")+ "Running Mineserver v." + VERSION, Chat::USER); } void rules(User *user, std::string command, std::deque<std::string> args) { User *tUser = user; if(!args.empty() && user->admin) tUser = getUserByNick(args[0]); if(tUser != NULL) { // Send rules std::ifstream ifs( RULESFILE.c_str()); std::string temp; if(ifs.fail()) { std::cout << "> Warning: " << RULESFILE << " not found." << std::endl; return; } else { while(getline(ifs, temp)) { // If not a comment if(!temp.empty() && temp[0] != COMMENTPREFIX) Chat::get().sendMsg(tUser, temp, Chat::USER); } ifs.close(); } } else reportError(user, "User " + args[0] + " not found (see /players)"); } } void home(User *user, std::string command, std::deque<std::string> args) { Chat::get().sendMsg(user, COLOR_DARK_MAGENTA + "Teleported you home!", Chat::USER); user->teleport(Map::get().spawnPos.x(), Map::get().spawnPos.y() + 2, Map::get().spawnPos.z()); } void kit(User *user, std::string command, std::deque<std::string> args) { if(args.size() == 1) { std::vector<int> kitItems = Conf::get().vValue("kit_" + args[0]); // If kit is found if(!kitItems.empty()) { for(uint32 i=0;i<kitItems.size();i++) { spawnedItem item; item.EID = generateEID(); item.item = kitItems[i]; item.count = 1; item.health=0; item.pos.x() = static_cast<int>(user->pos.x*32 + (rand() % 30)); item.pos.y() = static_cast<int>(user->pos.y*32); item.pos.z() = static_cast<int>(user->pos.z*32 + (rand() % 30)); Map::get().sendPickupSpawn(item); } } else reportError(user, "Kit " + args[0] + " not found"); } else reportError(user, "Usage: /kit name"); } void saveMap(User *user, std::string command, std::deque<std::string> args) { Map::get().saveWholeMap(); Chat::get().sendMsg(user, COLOR_DARK_MAGENTA + "SERVER:" + COLOR_RED + " Saved map to disc", Chat::USER); } void kick(User *user, std::string command, std::deque<std::string> args) { if(!args.empty()) { std::string victim = args[0]; User *tUser = getUserByNick(victim); if(tUser != NULL) { args.pop_front(); std::string kickMsg; if(args.empty()) kickMsg = Conf::get().sValue("default_kick_message"); else { while(!args.empty()) { kickMsg += args[0] + " "; args.pop_front(); } } tUser->kick(kickMsg); } else reportError(user, "User " + victim + " not found (see /players)"); } else reportError(user, "Usage: /kick user [reason]"); } void setTime(User *user, std::string command, std::deque<std::string> args) { if(args.size() == 1) { Map::get().mapTime = (sint64)atoi(args[0].c_str()); Packet pkt; pkt << (sint8)PACKET_TIME_UPDATE << (sint64)Map::get().mapTime; if(Users.size()) Users[0]->sendAll((uint8*)pkt.getWrite(), pkt.getWriteLen()); Chat::get().sendMsg(user, COLOR_MAGENTA + "Time set to " + args[0], Chat::USER); } else reportError(user, "Usage: /settime time (time = 0-24000)"); } void setHealth(User *user, std::string command, std::deque<std::string> args) { if(args.size() == 2) { user->sethealth(atoi(args[1].c_str())); } else reportError(user, "Usage: /sethealth [player] health (health = 0-20)"); } void coordinateTeleport(User *user, std::string command, std::deque<std::string> args) { if(args.size() == 3) { LOG(user->nick + " teleport to: " + args[0] + " " + args[1] + " " + args[2]); double x = atof(args[0].c_str()); double y = atof(args[1].c_str()); double z = atof(args[2].c_str()); user->teleport(x, y, z); } else reportError(user, "Usage: /ctp x y z"); } void userTeleport(User *user, std::string command, std::deque<std::string> args) { if(args.size() == 1) { LOG(user->nick + " teleport to: " + args[0]); User *tUser = getUserByNick(args[0]); if(tUser != NULL) user->teleport(tUser->pos.x, tUser->pos.y + 2, tUser->pos.z); else reportError(user, "User " + args[0] + " not found (see /players)"); } else if(args.size() == 2) { LOG(user->nick + ": teleport " + args[0] + " to " + args[1]); User *whoUser = getUserByNick(args[0]); User *toUser = getUserByNick(args[1]); if(whoUser != NULL && toUser != NULL) { whoUser->teleport(toUser->pos.x, toUser->pos.y + 2, toUser->pos.z); Chat::get().sendMsg(user, COLOR_MAGENTA + "Teleported!", Chat::USER); } else { reportError(user, "User " + (whoUser == NULL ? args[0] : args[1])+ " not found (see /players"); } } else reportError(user, "Usage: /tp [player] targetplayer"); } void showPosition(User *user, std::string command, std::deque<std::string> args) { if(args.size() == 1) { User *tUser = getUserByNick(args[0]); if(tUser != NULL) Chat::get().sendMsg(user, COLOR_MAGENTA + args[0] + " is at: " + dtos(tUser->pos.x) + " " + dtos(tUser->pos.y) + " " + dtos(tUser->pos.z), Chat::USER); else reportError(user, "User " + args[0] + " not found (see /players)"); } else if(args.size() == 0) { Chat::get().sendMsg(user, COLOR_MAGENTA + "You are at: " + dtos(user->pos.x) + " " + dtos(user->pos.y) + " " + dtos(user->pos.z), Chat::USER); } else reportError(user, "Usage: /gps [player]"); } void regenerateLighting(User *user, std::string command, std::deque<std::string> args) { printf("Regenerating lighting for chunk %d,%d\n", blockToChunk((sint32)user->pos.x), blockToChunk((sint32)user->pos.z)); //First load the map if(Map::get().loadMap(blockToChunk((sint32)user->pos.x), blockToChunk((sint32)user->pos.z))) { //Then regenerate lighting Map::get().generateLight(blockToChunk((sint32)user->pos.x), blockToChunk((sint32)user->pos.z)); } } void reloadConfiguration(User *user, std::string command, std::deque<std::string> args) { Chat::get().loadAdmins(ADMINFILE); Conf::get().load(CONFIGFILE); // Set physics enable state based on config Physics::get().enabled = ((Conf::get().iValue("liquid_physics") == 0) ? false : true); Chat::get().sendMsg(user, COLOR_DARK_MAGENTA + "SERVER:" + COLOR_RED+ " Reloaded admins and config", Chat::USER); // Note that the MOTD is loaded on-demand each time it is requested } bool isValidItem(int id) { if(id < 1) // zero or negative items are all invalid return false; if(id > 91 && id < 256) // these are undefined blocks and items return false; if(id == 2256 || id == 2257) // records are special cased return true; if(id > 350) // high items are invalid return false; if(id >= BLOCK_RED_CLOTH && id <= BLOCK_GRAY_CLOTH) // coloured cloth causes client crashes return false; return true; } int roundUpTo(int x, int nearest) { x += (nearest - 1); x /= nearest; x *= nearest; return x; } void giveItems(User *user, std::string command, std::deque<std::string> args) { User *tUser = NULL; int itemId = 0, itemCount = 1, itemStacks = 1; if(args.size() == 2 || args.size() == 3) { tUser = getUserByNick(args[0]); //First check if item is a number itemId = atoi(args[1].c_str()); //If item was not a number, search the name from config if(itemId == 0) itemId = Conf::get().iValue(args[1]); // Check item validity if(!isValidItem(itemId)) { reportError(user, "Item " + args[1] + " not found."); return; } if(args.size() == 3) { itemCount = atoi(args[2].c_str()); // If multiple stacks itemStacks = roundUpTo(itemCount, 64) / 64; itemCount -= (itemStacks-1) * 64; } } else { reportError(user, "Usage: /give player item [count]"); return; } if(tUser) { int amount = 64; for(int i = 0; i < itemStacks; i++) { // if last stack if(i == itemStacks - 1) amount = itemCount; spawnedItem item; item.EID = generateEID(); item.item = itemId; item.health = 0; item.count = amount; item.pos.x() = static_cast<int>(tUser->pos.x * 32); item.pos.y() = static_cast<int>(tUser->pos.y * 32); item.pos.z() = static_cast<int>(tUser->pos.z * 32); Map::get().sendPickupSpawn(item); } Chat::get().sendMsg(user, COLOR_RED + user->nick + " spawned " + args[1], Chat::ADMINS); } else reportError(user, "User " + args[0] + " not found (see /players)"); } void Chat::registerStandardCommands() { registerCommand("players", playerList, false); registerCommand("about", about, false); registerCommand("rules", rules, false); registerCommand("home", home, false); registerCommand("kit", kit, false); registerCommand("save", saveMap, true); registerCommand("kick", kick, true); registerCommand("ctp", coordinateTeleport, true); registerCommand("tp", userTeleport, true); registerCommand("reload", reloadConfiguration, true); registerCommand("give", giveItems, true); registerCommand("gps", showPosition, true); registerCommand("settime", setTime, true); registerCommand("regen", regenerateLighting, true); registerCommand("sethealth", setHealth, true); } <commit_msg>ban + unban + whitelist<commit_after>/* Copyright (c) 2010, The Mineserver Project All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the The Mineserver Project nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <cstdlib> #include <cstdio> #include <iostream> #include <deque> #include <fstream> #include <vector> #include <ctime> #include <math.h> #ifdef WIN32 #include <winsock2.h> #else #include <netinet/in.h> #include <string.h> #endif #include "logger.h" #include "constants.h" #include "tools.h" #include "map.h" #include "user.h" #include "chat.h" #include "config.h" #include "tools.h" #include "physics.h" namespace { void reportError(User *user, std::string message) { Chat::get().sendMsg(user, COLOR_DARK_MAGENTA + "Error! " + COLOR_RED + message, Chat::USER); } void playerList(User *user, std::string command, std::deque<std::string> args) { Chat::get().sendUserlist(user); } void about(User *user, std::string command, std::deque<std::string> args) { Chat::get().sendMsg(user, COLOR_DARK_MAGENTA + Conf::get().sValue("servername")+ "Running Mineserver v." + VERSION, Chat::USER); } void rules(User *user, std::string command, std::deque<std::string> args) { User *tUser = user; if(!args.empty() && user->admin) tUser = getUserByNick(args[0]); if(tUser != NULL) { // Send rules std::ifstream ifs( RULESFILE.c_str()); std::string temp; if(ifs.fail()) { std::cout << "> Warning: " << RULESFILE << " not found." << std::endl; return; } else { while(getline(ifs, temp)) { // If not a comment if(!temp.empty() && temp[0] != COMMENTPREFIX) Chat::get().sendMsg(tUser, temp, Chat::USER); } ifs.close(); } } else reportError(user, "User " + args[0] + " not found (see /players)"); } } void home(User *user, std::string command, std::deque<std::string> args) { Chat::get().sendMsg(user, COLOR_DARK_MAGENTA + "Teleported you home!", Chat::USER); user->teleport(Map::get().spawnPos.x(), Map::get().spawnPos.y() + 2, Map::get().spawnPos.z()); } void kit(User *user, std::string command, std::deque<std::string> args) { if(!args.empty()) { std::vector<int> kitItems = Conf::get().vValue("kit_" + args[0]); // If kit is found if(!kitItems.empty()) { for(uint32 i=0;i<kitItems.size();i++) { spawnedItem item; item.EID = generateEID(); item.item = kitItems[i]; item.count = 1; item.health=0; item.pos.x() = static_cast<int>(user->pos.x*32 + (rand() % 30)); item.pos.y() = static_cast<int>(user->pos.y*32); item.pos.z() = static_cast<int>(user->pos.z*32 + (rand() % 30)); Map::get().sendPickupSpawn(item); } } else reportError(user, "Kit " + args[0] + " not found"); } } void saveMap(User *user, std::string command, std::deque<std::string> args) { Map::get().saveWholeMap(); Chat::get().sendMsg(user, COLOR_DARK_MAGENTA + "SERVER:" + COLOR_RED + " Saved map to disc", Chat::USER); } void ban(User *user, std::string command, std::deque<std::string> args) { std::string victim = args[0]; User *tUser = getUserByNick(victim); std::fstream bannedf; bannedf.open("banned.txt",std::fstream::app); bannedf << victim << std::endl; bannedf.close(); if(tUser != NULL) { args.pop_front(); std::string kickMsg; if(args.empty()) kickMsg = Conf::get().sValue("default_banned_message"); else { while(!args.empty()) { kickMsg += args[0] + " "; args.pop_front(); } } tUser->kick(kickMsg); } else Chat::get().sendMsg(user, COLOR_DARK_MAGENTA + victim +" was banned in his absence!", Chat::USER); // Reload list with banned users Chat::get().loadBanned(BANNEDFILE); } void unban(User *user, std::string command, std::deque<std::string> args) { std::string victim = args[0]; User *tUser = getUserByNick(victim); std::string line; std::ifstream in("banned.txt"); std::ofstream out("banned.tmp"); while( getline(in,line) ) { if(line != victim) out << line << "\n"; } in.close(); out.close(); remove("banned.txt"); rename("banned.tmp","banned.txt"); // Reload list with banned users Chat::get().loadBanned(BANNEDFILE); } void kick(User *user, std::string command, std::deque<std::string> args) { if(!args.empty()) { std::string victim = args[0]; User *tUser = getUserByNick(victim); if(tUser != NULL) { args.pop_front(); std::string kickMsg; if(args.empty()) kickMsg = Conf::get().sValue("default_kick_message"); else { while(!args.empty()) { kickMsg += args[0] + " "; args.pop_front(); } } tUser->kick(kickMsg); } else reportError(user, "User " + victim + " not found (see /players)"); } else reportError(user, "Usage: /kick user [reason]"); } void setTime(User *user, std::string command, std::deque<std::string> args) { if(args.size() == 1) { Map::get().mapTime = (sint64)atoi(args[0].c_str()); Packet pkt; pkt << (sint8)PACKET_TIME_UPDATE << (sint64)Map::get().mapTime; if(Users.size()) Users[0]->sendAll((uint8*)pkt.getWrite(), pkt.getWriteLen()); Chat::get().sendMsg(user, COLOR_MAGENTA + "Time set to " + args[0], Chat::USER); } else reportError(user, "Usage: /settime time (time = 0-24000)"); } void coordinateTeleport(User *user, std::string command, std::deque<std::string> args) { if(args.size() > 2) { LOG(user->nick + " teleport to: " + args[0] + " " + args[1] + " " + args[2]); double x = atof(args[0].c_str()); double y = atof(args[1].c_str()); double z = atof(args[2].c_str()); user->teleport(x, y, z); } } void userTeleport(User *user, std::string command, std::deque<std::string> args) { if(args.size() == 1) { LOG(user->nick + " teleport to: " + args[0]); User *tUser = getUserByNick(args[0]); if(tUser != NULL) user->teleport(tUser->pos.x, tUser->pos.y + 2, tUser->pos.z); else reportError(user, "User " + args[0] + " not found (see /players)"); } else if(args.size() == 2) { LOG(user->nick + ": teleport " + args[0] + " to " + args[1]); User *whoUser = getUserByNick(args[0]); User *toUser = getUserByNick(args[1]); if(whoUser != NULL && toUser != NULL) { whoUser->teleport(toUser->pos.x, toUser->pos.y + 2, toUser->pos.z); Chat::get().sendMsg(user, COLOR_MAGENTA + "Teleported!", Chat::USER); } else { reportError(user, "User " + (whoUser == NULL ? args[0] : args[1])+ " not found (see /players"); } } } void showPosition(User *user, std::string command, std::deque<std::string> args) { if(args.size() == 1) { User *tUser = getUserByNick(args[0]); if(tUser != NULL) Chat::get().sendMsg(user, COLOR_MAGENTA + args[0] + " is at: " + dtos(tUser->pos.x) + " " + dtos(tUser->pos.y) + " " + dtos(tUser->pos.z), Chat::USER); else reportError(user, "User " + args[0] + " not found (see /players)"); } else { Chat::get().sendMsg(user, COLOR_MAGENTA + "You are at: " + dtos(user->pos.x) + " " + dtos(user->pos.y) + " " + dtos(user->pos.z), Chat::USER); } } void regenerateLighting(User *user, std::string command, std::deque<std::string> args) { printf("Regenerating lighting for chunk %d,%d\n", blockToChunk((sint32)user->pos.x), blockToChunk((sint32)user->pos.z)); //First load the map if(Map::get().loadMap(blockToChunk((sint32)user->pos.x), blockToChunk((sint32)user->pos.z))) { //Then regenerate lighting Map::get().generateLight(blockToChunk((sint32)user->pos.x), blockToChunk((sint32)user->pos.z)); } } void reloadConfiguration(User *user, std::string command, std::deque<std::string> args) { Chat::get().loadAdmins(ADMINFILE); Chat::get().loadBanned(BANNEDFILE); Chat::get().loadWhitelist(WHITELISTFILE); Conf::get().load(CONFIGFILE); // Set physics enable state based on config Physics::get().enabled = ((Conf::get().iValue("liquid_physics") == 0) ? false : true); Chat::get().sendMsg(user, COLOR_DARK_MAGENTA + "SERVER:" + COLOR_RED+ " Reloaded admins and config", Chat::USER); // Note that the MOTD is loaded on-demand each time it is requested } bool isValidItem(int id) { if(id < 1) // zero or negative items are all invalid return false; if(id > 91 && id < 256) // these are undefined blocks and items return false; if(id == 2256 || id == 2257) // records are special cased return true; if(id > 350) // high items are invalid return false; if(id >= BLOCK_RED_CLOTH && id <= BLOCK_GRAY_CLOTH) // coloured cloth causes client crashes return false; return true; } int roundUpTo(int x, int nearest) { x += (nearest - 1); x /= nearest; x *= nearest; return x; } void giveItems(User *user, std::string command, std::deque<std::string> args) { User *tUser = NULL; int itemId = 0, itemCount = 1, itemStacks = 1; if(args.size() > 1) { tUser = getUserByNick(args[0]); //First check if item is a number itemId = atoi(args[1].c_str()); //If item was not a number, search the name from config if(itemId == 0) itemId = Conf::get().iValue(args[1]); // Check item validity if(!isValidItem(itemId)) { reportError(user, "Item " + args[1] + " not found."); return; } if(args.size() > 2) { itemCount = atoi(args[2].c_str()); // If multiple stacks itemStacks = roundUpTo(itemCount, 64) / 64; itemCount -= (itemStacks-1) * 64; } } else { reportError(user, "Too few parameters."); return; } if(tUser) { int amount = 64; for(int i = 0; i < itemStacks; i++) { // if last stack if(i == itemStacks - 1) amount = itemCount; spawnedItem item; item.EID = generateEID(); item.item = itemId; item.health = 0; item.count = amount; item.pos.x() = static_cast<int>(tUser->pos.x * 32); item.pos.y() = static_cast<int>(tUser->pos.y * 32); item.pos.z() = static_cast<int>(tUser->pos.z * 32); Map::get().sendPickupSpawn(item); } Chat::get().sendMsg(user, COLOR_RED + user->nick + " spawned " + args[1], Chat::ADMINS); } else reportError(user, "User " + args[0] + " not found (see /players)"); } void Chat::registerStandardCommands() { registerCommand("players", playerList, false); registerCommand("about", about, false); registerCommand("rules", rules, false); registerCommand("home", home, false); registerCommand("ban", ban, true); registerCommand("unban", unban, true); registerCommand("kit", kit, false); registerCommand("save", saveMap, true); registerCommand("kick", kick, true); registerCommand("ctp", coordinateTeleport, true); registerCommand("tp", userTeleport, true); registerCommand("reload", reloadConfiguration, true); registerCommand("give", giveItems, true); registerCommand("gps", showPosition, true); registerCommand("settime", setTime, true); registerCommand("regen", regenerateLighting, true); } <|endoftext|>
<commit_before>#include "gtest/gtest.h" #include "Models/StateSpace/Filters/SparseMatrix.hpp" #include "test_utils/test_utils.hpp" namespace { using namespace BOOM; using std::endl; class SparseMatrixTest : public ::testing::Test { protected: SparseMatrixTest() { GlobalRng::rng.seed(8675309); } }; void CheckLeftInverse(const Ptr<SparseMatrixBlock> &block, const Vector &rhs) { BlockDiagonalMatrix mat; mat.add_block(block); Vector lhs = mat.left_inverse(rhs); Vector rhs_new = mat * lhs; EXPECT_TRUE(VectorEquals(rhs, rhs_new)) << "Vectors were not equal." << endl << rhs << endl << rhs_new; } TEST_F(SparseMatrixTest, LeftInverseIdentity) { NEW(IdentityMatrix, mat)(3); Vector x(3); x.randomize(); CheckLeftInverse(mat, x); } TEST_F(SparseMatrixTest, LeftInverseSkinnyColumn) { NEW(FirstElementSingleColumnMatrix, column)(12); Vector errors(1); errors.randomize(); Vector x(12); x[0] = errors[0]; CheckLeftInverse(column, x); } } // namespace <commit_msg>Add testing for concrete sparse matrix classes.<commit_after>#include "gtest/gtest.h" #include "Models/StateSpace/Filters/SparseMatrix.hpp" #include "test_utils/test_utils.hpp" namespace { using namespace BOOM; using std::endl; class SparseMatrixTest : public ::testing::Test { protected: SparseMatrixTest() { GlobalRng::rng.seed(8675309); } }; void CheckSparseMatrixBlock( const Ptr<SparseMatrixBlock> &sparse, const Matrix &dense) { EXPECT_TRUE(MatrixEquals(sparse->dense(), dense)); EXPECT_EQ(sparse->nrow(), dense.nrow()) << endl << sparse->dense() << endl << dense; EXPECT_EQ(sparse->ncol(), dense.ncol()) << endl << sparse->dense() << endl << dense; Vector rhs_vector(dense.ncol()); rhs_vector.randomize(); Vector lhs_vector(dense.nrow()); sparse->multiply(VectorView(lhs_vector), rhs_vector); EXPECT_TRUE(VectorEquals(lhs_vector, dense * rhs_vector)) << endl << sparse->dense() << endl << dense << endl << "rhs = " << rhs_vector << endl << "sparse * rhs = " << lhs_vector << endl << "dense * rhs = " << dense * rhs_vector << endl; Vector original_lhs = lhs_vector; lhs_vector.randomize(); rhs_vector.randomize(); sparse->multiply_and_add(VectorView(lhs_vector), rhs_vector); EXPECT_TRUE(VectorEquals(lhs_vector, original_lhs + dense * rhs_vector)) << endl << sparse->dense() << endl << dense << endl << "rhs = " << rhs_vector << endl << "lhs = " << original_lhs << endl << "lhs + sparse * rhs = " << lhs_vector << endl << "lhs + dense * rhs = " << lhs_vector + dense * rhs_vector << endl; Vector rhs_tmult_vector(dense.nrow()); Vector lhs_tmult_vector(dense.ncol()); sparse->Tmult(VectorView(lhs_tmult_vector), rhs_tmult_vector); EXPECT_TRUE(VectorEquals(lhs_tmult_vector, rhs_tmult_vector * dense)); // Only check multiply_inplace and friends if the matrix is square. if (dense.nrow() == dense.ncol()) { Vector original_rhs = rhs_vector; sparse->multiply_inplace(VectorView(rhs_vector)); EXPECT_TRUE(VectorEquals(rhs_vector, dense * original_rhs)) << endl << sparse->dense() << endl << dense << endl << "rhs = " << original_rhs << endl << "sparse->multiply_inplace(rhs) = " << rhs_vector << endl << "dense * rhs = " << dense * original_rhs << endl; Matrix rhs_matrix(dense.ncol(), dense.ncol()); rhs_matrix.randomize(); Matrix original_rhs_matrix = rhs_matrix; sparse->matrix_multiply_inplace(SubMatrix(rhs_matrix)); EXPECT_TRUE(MatrixEquals(rhs_matrix, dense * original_rhs_matrix)) << endl << sparse->dense() << endl << dense << endl << "rhs = " << original_rhs_matrix << endl << "sparse->matrix_multiply_inplace(rhs) = " << rhs_matrix << endl << "dense * rhs = " << dense * original_rhs_matrix << endl; original_rhs_matrix = rhs_matrix; sparse->matrix_transpose_premultiply_inplace(SubMatrix(rhs_matrix)); EXPECT_TRUE(MatrixEquals(rhs_matrix, dense.transpose() * original_rhs_matrix)) << endl << sparse->dense() << endl << dense << endl << "rhs = " << original_rhs_matrix << endl << "sparse->matrix_transpose_multiply_inplace(rhs) = " << rhs_matrix << endl << "dense * rhs = " << dense.transpose() * original_rhs_matrix << endl; } Matrix summand(dense.nrow(), dense.ncol()); summand.randomize(); Matrix original_summand(summand); sparse->add_to(SubMatrix(summand)); EXPECT_TRUE(MatrixEquals(summand, dense + original_summand)) << endl << sparse->dense() << endl << dense << endl << "B = " << original_summand << endl << "sparse->add_to(B) = " << summand << endl << "dense + B = " << dense + original_summand << endl; } void CheckLeftInverse(const Ptr<SparseMatrixBlock> &block, const Vector &rhs) { BlockDiagonalMatrix mat; mat.add_block(block); Vector lhs = mat.left_inverse(rhs); Vector rhs_new = mat * lhs; EXPECT_TRUE(VectorEquals(rhs, rhs_new)) << "Vectors were not equal." << endl << rhs << endl << rhs_new; } TEST_F(SparseMatrixTest, LeftInverseIdentity) { NEW(IdentityMatrix, mat)(3); Vector x(3); x.randomize(); CheckLeftInverse(mat, x); } TEST_F(SparseMatrixTest, LeftInverseSkinnyColumn) { NEW(FirstElementSingleColumnMatrix, column)(12); Vector errors(1); errors.randomize(); Vector x(12); x[0] = errors[0]; CheckLeftInverse(column, x); } TEST_F(SparseMatrixTest, IdentityMatrix) { NEW(IdentityMatrix, I3)(3); SpdMatrix I3_dense(3, 1.0); CheckSparseMatrixBlock(I3, I3_dense); NEW(IdentityMatrix, I1)(1); SpdMatrix I1_dense(1, 1.0); CheckSparseMatrixBlock(I1, I1_dense); } TEST_F(SparseMatrixTest, LocalTrend) { NEW(LocalLinearTrendMatrix, T)(); Matrix Tdense = T->dense(); EXPECT_TRUE(VectorEquals(Tdense.row(0), Vector{1, 1})); EXPECT_TRUE(VectorEquals(Tdense.row(1), Vector{0, 1})); CheckSparseMatrixBlock(T, Tdense); } TEST_F(SparseMatrixTest, DenseMatrixTest) { Matrix square(4, 4); square.randomize(); NEW(DenseMatrix, square_kalman)(square); CheckSparseMatrixBlock(square_kalman, square); Matrix rectangle(3, 4); rectangle.randomize(); NEW(DenseMatrix, rectangle_kalman)(rectangle); CheckSparseMatrixBlock(rectangle_kalman, rectangle); } TEST_F(SparseMatrixTest, SpdTest) { SpdMatrix spd(3); spd.randomize(); NEW(DenseSpd, spd_kalman)(spd); CheckSparseMatrixBlock(spd_kalman, spd); NEW(SpdParams, sparams)(spd); NEW(DenseSpdParamView, spd_view)(sparams); CheckSparseMatrixBlock(spd_view, spd); } TEST_F(SparseMatrixTest, Diagonal) { Vector values(4); values.randomize(); NEW(DiagonalMatrixBlock, diag)(values); Matrix D(4, 4, 0.0); D.set_diag(values); CheckSparseMatrixBlock(diag, D); NEW(VectorParams, vprm)(values); NEW(DiagonalMatrixBlockVectorParamView, diag_view)(vprm); CheckSparseMatrixBlock(diag_view, D); } TEST_F(SparseMatrixTest, Seasonal) { NEW(SeasonalStateSpaceMatrix, seasonal)(4); Matrix seasonal_dense(4, 4, 0.0); seasonal_dense.row(0) = -1; seasonal_dense.subdiag(1) = 1.0; CheckSparseMatrixBlock(seasonal, seasonal_dense); } TEST_F(SparseMatrixTest, AutoRegression) { Vector elements(4); elements.randomize(); NEW(GlmCoefs, rho)(elements); NEW(AutoRegressionTransitionMatrix, rho_kalman)(rho); Matrix rho_dense(4, 4); rho_dense.row(0) = elements; rho_dense.subdiag(1) = 1.0; CheckSparseMatrixBlock(rho_kalman, rho_dense); } TEST_F(SparseMatrixTest, EmptyTest) { Matrix empty; NEW(EmptyMatrix, empty_kalman)(); CheckSparseMatrixBlock(empty_kalman, empty); } TEST_F(SparseMatrixTest, ConstantTest) { SpdMatrix dense(4, 8.7); NEW(ConstantMatrix, sparse)(4, 8.7); CheckSparseMatrixBlock(sparse, dense); NEW(UnivParams, prm)(8.7); NEW(ConstantMatrixParamView, sparse_view)(4, prm); CheckSparseMatrixBlock(sparse_view, dense); } TEST_F(SparseMatrixTest, ZeroTest) { NEW(ZeroMatrix, sparse)(7); Matrix dense(7, 7, 0.0); CheckSparseMatrixBlock(sparse, dense); } TEST_F(SparseMatrixTest, ULC) { NEW(UpperLeftCornerMatrix, sparse)(5, 19.2); Matrix dense(5, 5, 0.0); dense(0, 0) = 19.2; CheckSparseMatrixBlock(sparse, dense); NEW(UnivParams, prm)(19.2); NEW(UpperLeftCornerMatrixParamView, sparse_view)(5, prm); CheckSparseMatrixBlock(sparse_view, dense); } TEST_F(SparseMatrixTest, FirstElementSingleColumnMatrixTest) { NEW(FirstElementSingleColumnMatrix, sparse)(7); Matrix dense(7, 1, 0.0); dense(0, 0) = 1.0; CheckSparseMatrixBlock(sparse, dense); } TEST_F(SparseMatrixTest, ZeroPaddedIdTest) { NEW(ZeroPaddedIdentityMatrix, sparse)(20, 4); Matrix dense(20, 4); dense.set_diag(1.0); CheckSparseMatrixBlock(sparse, dense); } TEST_F(SparseMatrixTest, SingleSparseDiagonalElementMatrixTest) { NEW(SingleSparseDiagonalElementMatrix, sparse)(12, 18.7, 5); Matrix dense(12, 12, 0.0); dense(5, 5) = 18.7; CheckSparseMatrixBlock(sparse, dense); NEW(UnivParams, prm)(18.7); NEW(SingleSparseDiagonalElementMatrixParamView, sparse_view)(12, prm, 5); CheckSparseMatrixBlock(sparse_view, dense); } TEST_F(SparseMatrixTest, SingleElementInFirstRowTest) { NEW(SingleElementInFirstRow, sparse_square)(5, 5, 3, 12.9); Matrix dense(5, 5, 0.0); dense(0, 3) = 12.9; CheckSparseMatrixBlock(sparse_square, dense); NEW(SingleElementInFirstRow, sparse_rectangle)(5, 8, 0, 99.99); Matrix wide(5, 8, 0.0); wide(0, 0) = 99.99; CheckSparseMatrixBlock(sparse_rectangle, wide); NEW(SingleElementInFirstRow, sparse_tall)(20, 4, 2, 13.7); Matrix tall(20, 4, 0.0); tall(0, 2) = 13.7; CheckSparseMatrixBlock(sparse_tall, tall); } TEST_F(SparseMatrixTest, UpperLeftDiagonalTest) { std::vector<Ptr<UnivParams>> params; params.push_back(new UnivParams(3.2)); params.push_back(new UnivParams(1.7)); params.push_back(new UnivParams(-19.8)); NEW(UpperLeftDiagonalMatrix, sparse)(params, 17); Matrix dense(17, 17, 0.0); for (int i = 0; i < params.size(); ++i) { dense(i, i) = params[i]->value(); } CheckSparseMatrixBlock(sparse, dense); Vector scale_factor(3); scale_factor.randomize(); dense.diag() *= scale_factor; NEW(UpperLeftDiagonalMatrix, sparse2)(params, 17, scale_factor); CheckSparseMatrixBlock(sparse2, dense); } TEST_F(SparseMatrixTest, IdenticalRowsMatrixTest) { SparseVector row(20); row[0] = 8; row[17] = 6; row[12] = 7; row[9] = 5; row[3] = 3; row[1] = 0; row[2] = 9; NEW(IdenticalRowsMatrix, sparse)(row, 20); Matrix dense(20, 20, 0.0); dense.col(0) = 8; dense.col(17) = 6; dense.col(12) = 7; dense.col(9) = 5; dense.col(3) = 3; dense.col(1) = 0; dense.col(2) = 9; CheckSparseMatrixBlock(sparse, dense); } Matrix ConstraintMatrix(int dim) { Matrix ans(dim, dim, 0.0); ans.set_diag(1.0); return ans - Matrix(dim, dim, 1.0 / dim); } TEST_F(SparseMatrixTest, EffectConstrainedMatrixBlockTest) { NEW(SeasonalStateSpaceMatrix, seasonal)(12); NEW(EffectConstrainedMatrixBlock, constrained_seasonal)( seasonal); CheckSparseMatrixBlock(constrained_seasonal, seasonal->dense() * ConstraintMatrix(11)); } TEST_F(SparseMatrixTest, GenericSparseMatrixBlockTest) { NEW(GenericSparseMatrixBlock, sparse)(12, 18); (*sparse)(3, 7) = 19; (*sparse)(5, 2) = -4; Matrix dense(12, 18, 0.0); dense(3, 7) = 19; dense(5, 2) = -4; CheckSparseMatrixBlock(sparse, dense); } } // namespace <|endoftext|>
<commit_before>/*========================================================================= * * Copyright Insight Software Consortium * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ /*========================================================================= * * Portions of this file are subject to the VTK Toolkit Version 3 copyright. * * Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen * * For complete copyright, license and disclaimer of warranty information * please refer to the NOTICE file at the top of the ITK source tree. * *=========================================================================*/ #include "itkMultiThreader.h" #include "itkObjectFactory.h" #include "itksys/SystemTools.hxx" #include <stdlib.h> namespace itk { ThreadIdType MultiThreader::GetGlobalDefaultNumberOfThreadsByPlatform() { int num; // If we are not multithreading, the number of threads should // always be 1 num = 1; return num; } void MultiThreader::MultipleMethodExecute() { ThreadIdType thread_loop; // obey the global maximum number of threads limit if ( m_NumberOfThreads > m_GlobalMaximumNumberOfThreads ) { m_NumberOfThreads = m_GlobalMaximumNumberOfThreads; } for ( thread_loop = 0; thread_loop < m_NumberOfThreads; thread_loop++ ) { if ( m_MultipleMethod[thread_loop] == (ThreadFunctionType)0 ) { itkExceptionMacro(<< "No multiple method set for: " << thread_loop); return; } } // There is no multi threading, so there is only one thread. m_ThreadInfoArray[0].UserData = m_MultipleData[0]; m_ThreadInfoArray[0].NumberOfThreads = m_NumberOfThreads; ( m_MultipleMethod[0] )( (void *)( &m_ThreadInfoArray[0] ) ); } ThreadIdType MultiThreader::SpawnThread(ThreadFunctionType f, void *UserData) { int id = 0; while ( id < ITK_MAX_THREADS ) { if ( !m_SpawnedThreadActiveFlagLock[id] ) { m_SpawnedThreadActiveFlagLock[id] = MutexLock::New(); } m_SpawnedThreadActiveFlagLock[id]->Lock(); if ( m_SpawnedThreadActiveFlag[id] == 0 ) { // We've got a useable thread id, so grab it m_SpawnedThreadActiveFlag[id] = 1; m_SpawnedThreadActiveFlagLock[id]->Unlock(); break; } m_SpawnedThreadActiveFlagLock[id]->Unlock(); id++; } if ( id >= ITK_MAX_THREADS ) { itkExceptionMacro(<< "You have too many active threads!"); } m_SpawnedThreadInfoArray[id].UserData = UserData; m_SpawnedThreadInfoArray[id].NumberOfThreads = 1; m_SpawnedThreadInfoArray[id].ActiveFlag = &m_SpawnedThreadActiveFlag[id]; m_SpawnedThreadInfoArray[id].ActiveFlagLock = m_SpawnedThreadActiveFlagLock[id]; // There is no multi threading, so there is only one thread. // This won't work - so give an error message. itkExceptionMacro(<< "Cannot spawn thread in a single threaded environment!"); m_SpawnedThreadActiveFlagLock[id] = 0; id = -1; return id; } void MultiThreader::TerminateThread(ThreadIdType ThreadID) { if ( !m_SpawnedThreadActiveFlag[ThreadID] ) { return; } m_SpawnedThreadActiveFlagLock[ThreadID]->Lock(); m_SpawnedThreadActiveFlag[ThreadID] = 0; m_SpawnedThreadActiveFlagLock[ThreadID]->Unlock(); // There is no multi threading, so there is only one thread. // This won't work - so give an error message. itkExceptionMacro(<< "Cannot terminate thread in single threaded environment!"); m_SpawnedThreadActiveFlagLock[ThreadID] = 0; m_SpawnedThreadActiveFlagLock[ThreadID] = 0; } void MultiThreader ::ThreadPoolWaitForSingleMethodThread(ThreadProcessIdType threadHandle) { // No threading library specified. Do nothing. No joining or waiting // necessary. } ThreadProcessIdType MultiThreader ::ThreadPoolDispatchSingleMethodThread(MultiThreader::ThreadInfoStruct *threadInfo) { // No threading library specified. Do nothing. The computation // will be run by the main execution thread. } void MultiThreader ::SpawnWaitForSingleMethodThread(ThreadProcessIdType threadHandle) { // No threading library specified. Do nothing. No joining or waiting // necessary. } ThreadProcessIdType MultiThreader ::SpawnDispatchSingleMethodThread(MultiThreader::ThreadInfoStruct *threadInfo) { // No threading library specified. Do nothing. The computation // will be run by the main execution thread. } } // end namespace itk <commit_msg>COMP: Fix unused parameter warnings in itkMultiThreaderNoThreads.<commit_after>/*========================================================================= * * Copyright Insight Software Consortium * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ /*========================================================================= * * Portions of this file are subject to the VTK Toolkit Version 3 copyright. * * Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen * * For complete copyright, license and disclaimer of warranty information * please refer to the NOTICE file at the top of the ITK source tree. * *=========================================================================*/ #include "itkMultiThreader.h" #include "itkObjectFactory.h" #include "itksys/SystemTools.hxx" #include <stdlib.h> namespace itk { ThreadIdType MultiThreader::GetGlobalDefaultNumberOfThreadsByPlatform() { int num; // If we are not multithreading, the number of threads should // always be 1 num = 1; return num; } void MultiThreader::MultipleMethodExecute() { ThreadIdType thread_loop; // obey the global maximum number of threads limit if ( m_NumberOfThreads > m_GlobalMaximumNumberOfThreads ) { m_NumberOfThreads = m_GlobalMaximumNumberOfThreads; } for ( thread_loop = 0; thread_loop < m_NumberOfThreads; thread_loop++ ) { if ( m_MultipleMethod[thread_loop] == (ThreadFunctionType)0 ) { itkExceptionMacro(<< "No multiple method set for: " << thread_loop); return; } } // There is no multi threading, so there is only one thread. m_ThreadInfoArray[0].UserData = m_MultipleData[0]; m_ThreadInfoArray[0].NumberOfThreads = m_NumberOfThreads; ( m_MultipleMethod[0] )( (void *)( &m_ThreadInfoArray[0] ) ); } ThreadIdType MultiThreader::SpawnThread(ThreadFunctionType itkNotUsed( f ), void *UserData) { int id = 0; while ( id < ITK_MAX_THREADS ) { if ( !m_SpawnedThreadActiveFlagLock[id] ) { m_SpawnedThreadActiveFlagLock[id] = MutexLock::New(); } m_SpawnedThreadActiveFlagLock[id]->Lock(); if ( m_SpawnedThreadActiveFlag[id] == 0 ) { // We've got a useable thread id, so grab it m_SpawnedThreadActiveFlag[id] = 1; m_SpawnedThreadActiveFlagLock[id]->Unlock(); break; } m_SpawnedThreadActiveFlagLock[id]->Unlock(); id++; } if ( id >= ITK_MAX_THREADS ) { itkExceptionMacro(<< "You have too many active threads!"); } m_SpawnedThreadInfoArray[id].UserData = UserData; m_SpawnedThreadInfoArray[id].NumberOfThreads = 1; m_SpawnedThreadInfoArray[id].ActiveFlag = &m_SpawnedThreadActiveFlag[id]; m_SpawnedThreadInfoArray[id].ActiveFlagLock = m_SpawnedThreadActiveFlagLock[id]; // There is no multi threading, so there is only one thread. // This won't work - so give an error message. itkExceptionMacro(<< "Cannot spawn thread in a single threaded environment!"); m_SpawnedThreadActiveFlagLock[id] = 0; id = -1; return id; } void MultiThreader::TerminateThread(ThreadIdType ThreadID) { if ( !m_SpawnedThreadActiveFlag[ThreadID] ) { return; } m_SpawnedThreadActiveFlagLock[ThreadID]->Lock(); m_SpawnedThreadActiveFlag[ThreadID] = 0; m_SpawnedThreadActiveFlagLock[ThreadID]->Unlock(); // There is no multi threading, so there is only one thread. // This won't work - so give an error message. itkExceptionMacro(<< "Cannot terminate thread in single threaded environment!"); m_SpawnedThreadActiveFlagLock[ThreadID] = 0; m_SpawnedThreadActiveFlagLock[ThreadID] = 0; } void MultiThreader ::ThreadPoolWaitForSingleMethodThread(ThreadProcessIdType itkNotUsed( threadHandle )) { // No threading library specified. Do nothing. No joining or waiting // necessary. } ThreadProcessIdType MultiThreader ::ThreadPoolDispatchSingleMethodThread(MultiThreader::ThreadInfoStruct * itkNotUsed( threadInfo )) { // No threading library specified. Do nothing. The computation // will be run by the main execution thread. return 0; } void MultiThreader ::SpawnWaitForSingleMethodThread(ThreadProcessIdType itkNotUsed( threadHandle )) { // No threading library specified. Do nothing. No joining or waiting // necessary. } ThreadProcessIdType MultiThreader ::SpawnDispatchSingleMethodThread(MultiThreader::ThreadInfoStruct * itkNotUsed( threadInfo )) { // No threading library specified. Do nothing. The computation // will be run by the main execution thread. return 0; } } // end namespace itk <|endoftext|>
<commit_before>/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include <mitkPolhemusInterface.h> #define _USE_MATH_DEFINES #include <math.h> #include <PDI.h> BYTE MotionBuf[0x1FA400]; mitk::PolhemusInterface::PolhemusInterface() : m_continousTracking(false) { m_pdiDev = new CPDIdev(); m_numberOfTools = 0; } mitk::PolhemusInterface::~PolhemusInterface() { delete m_pdiDev; } bool mitk::PolhemusInterface::InitializeDevice() { m_pdiDev->ResetTracker(); m_pdiDev->ResetSAlignment(-1); m_pdiDev->Trace(TRUE, 7); m_continousTracking = false; return true; } bool mitk::PolhemusInterface::SetupDevice() { m_pdiDev->SetPnoBuffer(MotionBuf, 0x1FA400); m_pdiDev->SetMetric(true); //use cm instead of inches m_pdiDev->StartPipeExport(); CPDImdat pdiMDat; pdiMDat.Empty(); pdiMDat.Append(PDI_MODATA_FRAMECOUNT); pdiMDat.Append(PDI_MODATA_POS); pdiMDat.Append(PDI_MODATA_ORI); m_pdiDev->SetSDataList(-1, pdiMDat); CPDIbiterr cBE; m_pdiDev->GetBITErrs(cBE); if (!(cBE.IsClear())) { m_pdiDev->ClearBITErrs(); } return true; } bool mitk::PolhemusInterface::StartTracking() { LPCTSTR szWindowClass = _T("PDIconsoleWinClass"); HINSTANCE hInst = GetModuleHandle(0); HWND hwnd = CreateWindowEx( WS_EX_NOACTIVATE,//WS_EX_STATICEDGE, // szWindowClass, _T("MyWindowName"), WS_POPUP, 0, 0, 1, 1, HWND_MESSAGE, 0, hInst, 0); m_continousTracking = true; return m_pdiDev->StartContPno(hwnd); } bool mitk::PolhemusInterface::StopTracking() { m_continousTracking = false; m_pdiDev->StopContPno(); return true; } bool mitk::PolhemusInterface::Connect() { bool returnValue; //Initialize, and if it is not successful, return false. if (!InitializeDevice()) { returnValue = false; } //Connect else if (m_pdiDev->CnxReady()) { returnValue = true; } //If it is not successful, search for connections. else { CPDIser pdiSer; m_pdiDev->SetSerialIF(&pdiSer); ePiCommType eType = m_pdiDev->DiscoverCnx(); switch (eType) { case PI_CNX_USB: MITK_INFO << "USB Connection: " << m_pdiDev->GetLastResultStr(); break; case PI_CNX_SERIAL: MITK_INFO << "Serial Connection: " << m_pdiDev->GetLastResultStr(); break; default: MITK_INFO << "DiscoverCnx result: " << m_pdiDev->GetLastResultStr(); break; } //Setup device if (!SetupDevice()) { returnValue = false; } else { returnValue = m_pdiDev->CnxReady(); } } if (returnValue) { m_numberOfTools = this->GetNumberOfTools(); //On first startUp or if number of tools changed if (m_Hemispheres.empty() || m_Hemispheres.size() != m_numberOfTools) { //Set Hemisphere for all tools to default 1,0,0... mitk::Vector3D temp; mitk::FillVector3D(temp, 1, 0, 0); m_Hemispheres.clear(); m_Hemispheres.assign(m_numberOfTools, temp); this->SetHemisphere(-1, temp); } } return returnValue; } bool mitk::PolhemusInterface::Disconnect() { bool returnValue = true; //If Tracking is running, stop tracking first if (m_continousTracking) { this->StopTracking(); } returnValue = m_pdiDev->Disconnect(); MITK_INFO << "Disconnect: " << m_pdiDev->GetLastResultStr(); return returnValue; } std::vector<mitk::PolhemusInterface::trackingData> mitk::PolhemusInterface::GetLastFrame() { PBYTE pBuf; DWORD dwSize; //read one frame if (!m_pdiDev->LastPnoPtr(pBuf, dwSize)) { MITK_WARN << m_pdiDev->GetLastResultStr(); } std::vector<mitk::PolhemusInterface::trackingData> returnValue = ParsePolhemusRawData(pBuf, dwSize); if (returnValue.empty()) { MITK_WARN << "Cannot parse data / no tools present"; } return returnValue; } unsigned int mitk::PolhemusInterface::GetNumberOfTools() { if (m_continousTracking) return GetLastFrame().size(); else return GetSingleFrame().size(); } std::vector<mitk::PolhemusInterface::trackingData> mitk::PolhemusInterface::GetSingleFrame() { if (m_continousTracking) { MITK_WARN << "Cannot get a single frame when continuous tracking is on!"; return std::vector<mitk::PolhemusInterface::trackingData>(); } PBYTE pBuf; DWORD dwSize; //read one frame if (!m_pdiDev->ReadSinglePnoBuf(pBuf, dwSize)) { MITK_WARN << m_pdiDev->GetLastResultStr(); return std::vector<mitk::PolhemusInterface::trackingData>(); } return ParsePolhemusRawData(pBuf, dwSize); } std::vector<mitk::PolhemusInterface::trackingData> mitk::PolhemusInterface::ParsePolhemusRawData(PBYTE pBuf, DWORD dwSize) { std::vector<mitk::PolhemusInterface::trackingData> returnValue; DWORD i = 0; while (i < dwSize) { BYTE ucSensor = pBuf[i + 2]; SHORT shSize = pBuf[i + 6]; // skip rest of header i += 8; PDWORD pFC = (PDWORD)(&pBuf[i]); PFLOAT pPno = (PFLOAT)(&pBuf[i + 4]); mitk::PolhemusInterface::trackingData currentTrackingData; currentTrackingData.id = ucSensor; currentTrackingData.pos[0] = pPno[0] * 10; //from cm to mm currentTrackingData.pos[1] = pPno[1] * 10; currentTrackingData.pos[2] = pPno[2] * 10; double azimuthAngle = pPno[3] / 180 * M_PI; //from degree to rad double elevationAngle = pPno[4] / 180 * M_PI; double rollAngle = pPno[5] / 180 * M_PI; vnl_quaternion<double> eulerQuat(rollAngle, elevationAngle, azimuthAngle); currentTrackingData.rot = eulerQuat; returnValue.push_back(currentTrackingData); i += shSize; } return returnValue; } void mitk::PolhemusInterface::SetHemisphereTrackingEnabled(bool _HeisphereTrackingEnabeled) { //HemisphereTracking is switched on by SetSHemiTrack(-1). "-1" means for all sensors. //To switch heisphere tracking of, you need to set a hemisphere vector by calling SetSHemisphere(-1, { (float)1,0,0 }) if (_HeisphereTrackingEnabeled) { m_pdiDev->SetSHemiTrack(-1); } else if (!m_Hemispheres.empty()) { for (int i = 0; i < m_numberOfTools; ++i) SetHemisphere(i + 1, m_Hemispheres.at(i)); } else { //Default Hemisphere mitk::Vector3D temp; mitk::FillVector3D(temp, 1, 0, 0); m_Hemispheres.clear(); m_Hemispheres.assign(m_numberOfTools, temp); this->SetHemisphere(-1, temp); //MITK_INFO << m_pdiDev->GetLastResultStr(); } } void mitk::PolhemusInterface::ToggleHemisphere(int _tool) { BOOL _hemiTrack; //m_hemisphere indices start at 0, tool count starts at 1 //-1 == all tools if (_tool == -1) { for (int i = 0; i < m_numberOfTools; ++i) { //is hemiTrack on? m_pdiDev->GetSHemiTrack(i+1,_hemiTrack); m_Hemispheres.at(i)[0] = -m_Hemispheres.at(i)[0]; m_Hemispheres.at(i)[1] = -m_Hemispheres.at(i)[1]; m_Hemispheres.at(i)[2] = -m_Hemispheres.at(i)[2]; SetHemisphere(i+1, m_Hemispheres.at(i)); if (_hemiTrack) m_pdiDev->SetSHemiTrack(i+1); } } else { //is hemiTrack on? m_pdiDev->GetSHemiTrack(_tool, _hemiTrack); m_Hemispheres.at(_tool - 1)[0] = -m_Hemispheres.at(_tool - 1)[0]; m_Hemispheres.at(_tool - 1)[1] = -m_Hemispheres.at(_tool - 1)[1]; m_Hemispheres.at(_tool - 1)[2] = -m_Hemispheres.at(_tool - 1)[2]; SetHemisphere(_tool, m_Hemispheres.at(_tool - 1)); if (_hemiTrack) m_pdiDev->SetSHemiTrack(_tool); } } void mitk::PolhemusInterface::SetHemisphere(int _tool, mitk::Vector3D _hemisphere) { m_pdiDev->SetSHemisphere(_tool, { (float)_hemisphere[0], (float)_hemisphere[1], (float)_hemisphere[2] }); } void mitk::PolhemusInterface::PrintStatus() { MITK_INFO << "Polhemus status: " << this->m_pdiDev->CnxReady(); }<commit_msg>Window handle is not necessary and is not used. Parameter replaced by 0, works aswell.<commit_after>/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include <mitkPolhemusInterface.h> #define _USE_MATH_DEFINES #include <math.h> #include <PDI.h> BYTE MotionBuf[0x1FA400]; mitk::PolhemusInterface::PolhemusInterface() : m_continousTracking(false) { m_pdiDev = new CPDIdev(); m_numberOfTools = 0; } mitk::PolhemusInterface::~PolhemusInterface() { delete m_pdiDev; } bool mitk::PolhemusInterface::InitializeDevice() { m_pdiDev->ResetTracker(); m_pdiDev->ResetSAlignment(-1); m_pdiDev->Trace(TRUE, 7); m_continousTracking = false; return true; } bool mitk::PolhemusInterface::SetupDevice() { m_pdiDev->SetPnoBuffer(MotionBuf, 0x1FA400); m_pdiDev->SetMetric(true); //use cm instead of inches m_pdiDev->StartPipeExport(); CPDImdat pdiMDat; pdiMDat.Empty(); pdiMDat.Append(PDI_MODATA_FRAMECOUNT); pdiMDat.Append(PDI_MODATA_POS); pdiMDat.Append(PDI_MODATA_ORI); m_pdiDev->SetSDataList(-1, pdiMDat); CPDIbiterr cBE; m_pdiDev->GetBITErrs(cBE); if (!(cBE.IsClear())) { m_pdiDev->ClearBITErrs(); } return true; } bool mitk::PolhemusInterface::StartTracking() { m_continousTracking = true; return m_pdiDev->StartContPno(0); } bool mitk::PolhemusInterface::StopTracking() { m_continousTracking = false; m_pdiDev->StopContPno(); return true; } bool mitk::PolhemusInterface::Connect() { bool returnValue; //Initialize, and if it is not successful, return false. if (!InitializeDevice()) { returnValue = false; } //Connect else if (m_pdiDev->CnxReady()) { returnValue = true; } //If it is not successful, search for connections. else { CPDIser pdiSer; m_pdiDev->SetSerialIF(&pdiSer); ePiCommType eType = m_pdiDev->DiscoverCnx(); switch (eType) { case PI_CNX_USB: MITK_INFO << "USB Connection: " << m_pdiDev->GetLastResultStr(); break; case PI_CNX_SERIAL: MITK_INFO << "Serial Connection: " << m_pdiDev->GetLastResultStr(); break; default: MITK_INFO << "DiscoverCnx result: " << m_pdiDev->GetLastResultStr(); break; } //Setup device if (!SetupDevice()) { returnValue = false; } else { returnValue = m_pdiDev->CnxReady(); } } if (returnValue) { m_numberOfTools = this->GetNumberOfTools(); //On first startUp or if number of tools changed if (m_Hemispheres.empty() || m_Hemispheres.size() != m_numberOfTools) { //Set Hemisphere for all tools to default 1,0,0... mitk::Vector3D temp; mitk::FillVector3D(temp, 1, 0, 0); m_Hemispheres.clear(); m_Hemispheres.assign(m_numberOfTools, temp); this->SetHemisphere(-1, temp); } } return returnValue; } bool mitk::PolhemusInterface::Disconnect() { bool returnValue = true; //If Tracking is running, stop tracking first if (m_continousTracking) { this->StopTracking(); } returnValue = m_pdiDev->Disconnect(); MITK_INFO << "Disconnect: " << m_pdiDev->GetLastResultStr(); return returnValue; } std::vector<mitk::PolhemusInterface::trackingData> mitk::PolhemusInterface::GetLastFrame() { PBYTE pBuf; DWORD dwSize; //read one frame if (!m_pdiDev->LastPnoPtr(pBuf, dwSize)) { MITK_WARN << m_pdiDev->GetLastResultStr(); } std::vector<mitk::PolhemusInterface::trackingData> returnValue = ParsePolhemusRawData(pBuf, dwSize); if (returnValue.empty()) { MITK_WARN << "Cannot parse data / no tools present"; } return returnValue; } unsigned int mitk::PolhemusInterface::GetNumberOfTools() { if (m_continousTracking) return GetLastFrame().size(); else return GetSingleFrame().size(); } std::vector<mitk::PolhemusInterface::trackingData> mitk::PolhemusInterface::GetSingleFrame() { if (m_continousTracking) { MITK_WARN << "Cannot get a single frame when continuous tracking is on!"; return std::vector<mitk::PolhemusInterface::trackingData>(); } PBYTE pBuf; DWORD dwSize; //read one frame if (!m_pdiDev->ReadSinglePnoBuf(pBuf, dwSize)) { MITK_WARN << m_pdiDev->GetLastResultStr(); return std::vector<mitk::PolhemusInterface::trackingData>(); } return ParsePolhemusRawData(pBuf, dwSize); } std::vector<mitk::PolhemusInterface::trackingData> mitk::PolhemusInterface::ParsePolhemusRawData(PBYTE pBuf, DWORD dwSize) { std::vector<mitk::PolhemusInterface::trackingData> returnValue; DWORD i = 0; while (i < dwSize) { BYTE ucSensor = pBuf[i + 2]; SHORT shSize = pBuf[i + 6]; // skip rest of header i += 8; PDWORD pFC = (PDWORD)(&pBuf[i]); PFLOAT pPno = (PFLOAT)(&pBuf[i + 4]); mitk::PolhemusInterface::trackingData currentTrackingData; currentTrackingData.id = ucSensor; currentTrackingData.pos[0] = pPno[0] * 10; //from cm to mm currentTrackingData.pos[1] = pPno[1] * 10; currentTrackingData.pos[2] = pPno[2] * 10; double azimuthAngle = pPno[3] / 180 * M_PI; //from degree to rad double elevationAngle = pPno[4] / 180 * M_PI; double rollAngle = pPno[5] / 180 * M_PI; vnl_quaternion<double> eulerQuat(rollAngle, elevationAngle, azimuthAngle); currentTrackingData.rot = eulerQuat; returnValue.push_back(currentTrackingData); i += shSize; } return returnValue; } void mitk::PolhemusInterface::SetHemisphereTrackingEnabled(bool _HeisphereTrackingEnabeled) { //HemisphereTracking is switched on by SetSHemiTrack(-1). "-1" means for all sensors. //To switch heisphere tracking of, you need to set a hemisphere vector by calling SetSHemisphere(-1, { (float)1,0,0 }) if (_HeisphereTrackingEnabeled) { m_pdiDev->SetSHemiTrack(-1); } else if (!m_Hemispheres.empty()) { for (int i = 0; i < m_numberOfTools; ++i) SetHemisphere(i + 1, m_Hemispheres.at(i)); } else { //Default Hemisphere mitk::Vector3D temp; mitk::FillVector3D(temp, 1, 0, 0); m_Hemispheres.clear(); m_Hemispheres.assign(m_numberOfTools, temp); this->SetHemisphere(-1, temp); //MITK_INFO << m_pdiDev->GetLastResultStr(); } } void mitk::PolhemusInterface::ToggleHemisphere(int _tool) { BOOL _hemiTrack; //m_hemisphere indices start at 0, tool count starts at 1 //-1 == all tools if (_tool == -1) { for (int i = 0; i < m_numberOfTools; ++i) { //is hemiTrack on? m_pdiDev->GetSHemiTrack(i+1,_hemiTrack); m_Hemispheres.at(i)[0] = -m_Hemispheres.at(i)[0]; m_Hemispheres.at(i)[1] = -m_Hemispheres.at(i)[1]; m_Hemispheres.at(i)[2] = -m_Hemispheres.at(i)[2]; SetHemisphere(i+1, m_Hemispheres.at(i)); if (_hemiTrack) m_pdiDev->SetSHemiTrack(i+1); } } else { //is hemiTrack on? m_pdiDev->GetSHemiTrack(_tool, _hemiTrack); m_Hemispheres.at(_tool - 1)[0] = -m_Hemispheres.at(_tool - 1)[0]; m_Hemispheres.at(_tool - 1)[1] = -m_Hemispheres.at(_tool - 1)[1]; m_Hemispheres.at(_tool - 1)[2] = -m_Hemispheres.at(_tool - 1)[2]; SetHemisphere(_tool, m_Hemispheres.at(_tool - 1)); if (_hemiTrack) m_pdiDev->SetSHemiTrack(_tool); } } void mitk::PolhemusInterface::SetHemisphere(int _tool, mitk::Vector3D _hemisphere) { m_pdiDev->SetSHemisphere(_tool, { (float)_hemisphere[0], (float)_hemisphere[1], (float)_hemisphere[2] }); } void mitk::PolhemusInterface::PrintStatus() { MITK_INFO << "Polhemus status: " << this->m_pdiDev->CnxReady(); }<|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2000, 2010 Oracle and/or its affiliates. * * OpenOffice.org - a multi-platform office productivity suite * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #include "rtl/uuid.h" #include "osl/thread.h" #include "osl/mutex.hxx" #include "uno/environment.hxx" #include "uno/mapping.hxx" #include "uno/lbnames.h" #include "typelib/typedescription.h" #include "current.hxx" using namespace ::osl; using namespace ::rtl; using namespace ::cppu; using namespace ::com::sun::star::uno; namespace cppu { //-------------------------------------------------------------------------------------------------- class SAL_NO_VTABLE XInterface { public: virtual void SAL_CALL slot_queryInterface() = 0; virtual void SAL_CALL acquire() throw () = 0; virtual void SAL_CALL release() throw () = 0; protected: ~XInterface() {} // avoid warnings about virtual members and non-virtual dtor }; //-------------------------------------------------------------------------------------------------- static typelib_InterfaceTypeDescription * get_type_XCurrentContext() { static typelib_InterfaceTypeDescription * s_type_XCurrentContext = 0; if (0 == s_type_XCurrentContext) { ::osl::MutexGuard aGuard( ::osl::Mutex::getGlobalMutex() ); if (0 == s_type_XCurrentContext) { OUString sTypeName( RTL_CONSTASCII_USTRINGPARAM("com.sun.star.uno.XCurrentContext") ); typelib_InterfaceTypeDescription * pTD = 0; typelib_TypeDescriptionReference * pMembers[1] = { 0 }; OUString sMethodName0( RTL_CONSTASCII_USTRINGPARAM("com.sun.star.uno.XCurrentContext::getValueByName") ); typelib_typedescriptionreference_new( &pMembers[0], typelib_TypeClass_INTERFACE_METHOD, sMethodName0.pData ); typelib_typedescription_newInterface( &pTD, sTypeName.pData, 0x00000000, 0x0000, 0x0000, 0x00000000, 0x00000000, * typelib_static_type_getByTypeClass( typelib_TypeClass_INTERFACE ), 1, pMembers ); typelib_typedescription_register( (typelib_TypeDescription**)&pTD ); typelib_typedescriptionreference_release( pMembers[0] ); typelib_InterfaceMethodTypeDescription * pMethod = 0; typelib_Parameter_Init aParameters[1]; OUString sParamName0( RTL_CONSTASCII_USTRINGPARAM("Name") ); OUString sParamType0( RTL_CONSTASCII_USTRINGPARAM("string") ); aParameters[0].pParamName = sParamName0.pData; aParameters[0].eTypeClass = typelib_TypeClass_STRING; aParameters[0].pTypeName = sParamType0.pData; aParameters[0].bIn = sal_True; aParameters[0].bOut = sal_False; rtl_uString * pExceptions[1]; OUString sExceptionName0( RTL_CONSTASCII_USTRINGPARAM("com.sun.star.uno.RuntimeException") ); pExceptions[0] = sExceptionName0.pData; OUString sReturnType0( RTL_CONSTASCII_USTRINGPARAM("any") ); typelib_typedescription_newInterfaceMethod( &pMethod, 3, sal_False, sMethodName0.pData, typelib_TypeClass_ANY, sReturnType0.pData, 1, aParameters, 1, pExceptions ); typelib_typedescription_register( (typelib_TypeDescription**)&pMethod ); typelib_typedescription_release( (typelib_TypeDescription*)pMethod ); // another static ref: ++reinterpret_cast< typelib_TypeDescription * >( pTD )-> nStaticRefCount; s_type_XCurrentContext = pTD; } } return s_type_XCurrentContext; } //################################################################################################## //================================================================================================== class ThreadKey { sal_Bool _bInit; oslThreadKey _hThreadKey; oslThreadKeyCallbackFunction _pCallback; public: inline oslThreadKey getThreadKey() SAL_THROW(()); inline ThreadKey( oslThreadKeyCallbackFunction pCallback ) SAL_THROW(()); inline ~ThreadKey() SAL_THROW(()); }; //__________________________________________________________________________________________________ inline ThreadKey::ThreadKey( oslThreadKeyCallbackFunction pCallback ) SAL_THROW(()) : _bInit( sal_False ) , _pCallback( pCallback ) { } //__________________________________________________________________________________________________ inline ThreadKey::~ThreadKey() SAL_THROW(()) { if (_bInit) { ::osl_destroyThreadKey( _hThreadKey ); } } //__________________________________________________________________________________________________ inline oslThreadKey ThreadKey::getThreadKey() SAL_THROW(()) { if (! _bInit) { MutexGuard aGuard( Mutex::getGlobalMutex() ); if (! _bInit) { _hThreadKey = ::osl_createThreadKey( _pCallback ); _bInit = sal_True; } } return _hThreadKey; } //================================================================================================== extern "C" void SAL_CALL delete_IdContainer( void * p ) { if (p) { IdContainer * pId = reinterpret_cast< IdContainer * >( p ); if (pId->pCurrentContext) { (*pId->pCurrentContextEnv->releaseInterface)( pId->pCurrentContextEnv, pId->pCurrentContext ); (*((uno_Environment *)pId->pCurrentContextEnv)->release)( (uno_Environment *)pId->pCurrentContextEnv ); } if (pId->bInit) { ::rtl_byte_sequence_release( pId->pLocalThreadId ); ::rtl_byte_sequence_release( pId->pCurrentId ); } delete pId; } } //================================================================================================== IdContainer * getIdContainer() SAL_THROW(()) { static ThreadKey s_key( delete_IdContainer ); oslThreadKey aKey = s_key.getThreadKey(); IdContainer * pId = reinterpret_cast< IdContainer * >( ::osl_getThreadKeyData( aKey ) ); if (! pId) { pId = new IdContainer(); pId->pCurrentContext = 0; pId->pCurrentContextEnv = 0; pId->bInit = sal_False; ::osl_setThreadKeyData( aKey, pId ); } return pId; } } //################################################################################################## extern "C" CPPU_DLLPUBLIC sal_Bool SAL_CALL uno_setCurrentContext( void * pCurrentContext, rtl_uString * pEnvTypeName, void * pEnvContext ) SAL_THROW_EXTERN_C() { IdContainer * pId = getIdContainer(); OSL_ASSERT( pId ); // free old one if (pId->pCurrentContext) { (*pId->pCurrentContextEnv->releaseInterface)( pId->pCurrentContextEnv, pId->pCurrentContext ); (*((uno_Environment *)pId->pCurrentContextEnv)->release)( (uno_Environment *)pId->pCurrentContextEnv ); pId->pCurrentContextEnv = 0; pId->pCurrentContext = 0; } if (pCurrentContext) { uno_Environment * pEnv = 0; ::uno_getEnvironment( &pEnv, pEnvTypeName, pEnvContext ); OSL_ASSERT( pEnv && pEnv->pExtEnv ); if (pEnv) { if (pEnv->pExtEnv) { pId->pCurrentContextEnv = pEnv->pExtEnv; (*pId->pCurrentContextEnv->acquireInterface)( pId->pCurrentContextEnv, pCurrentContext ); pId->pCurrentContext = pCurrentContext; } else { (*pEnv->release)( pEnv ); return sal_False; } } else { return sal_False; } } return sal_True; } //################################################################################################## extern "C" CPPU_DLLPUBLIC sal_Bool SAL_CALL uno_getCurrentContext( void ** ppCurrentContext, rtl_uString * pEnvTypeName, void * pEnvContext ) SAL_THROW_EXTERN_C() { IdContainer * pId = getIdContainer(); OSL_ASSERT( pId ); Environment target_env; // release inout parameter if (*ppCurrentContext) { target_env = Environment(rtl::OUString(pEnvTypeName), pEnvContext); OSL_ASSERT( target_env.is() ); if (! target_env.is()) return sal_False; uno_ExtEnvironment * pEnv = target_env.get()->pExtEnv; OSL_ASSERT( 0 != pEnv ); if (0 == pEnv) return sal_False; (*pEnv->releaseInterface)( pEnv, *ppCurrentContext ); *ppCurrentContext = 0; } // case: null-ref if (0 == pId->pCurrentContext) return sal_True; if (! target_env.is()) { target_env = Environment(rtl::OUString(pEnvTypeName), pEnvContext); OSL_ASSERT( target_env.is() ); if (! target_env.is()) return sal_False; } Mapping mapping((uno_Environment *) pId->pCurrentContextEnv, target_env.get()); OSL_ASSERT( mapping.is() ); if (! mapping.is()) return sal_False; mapping.mapInterface(ppCurrentContext, pId->pCurrentContext, ::cppu::get_type_XCurrentContext() ); return sal_True; } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>Dead code<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2000, 2010 Oracle and/or its affiliates. * * OpenOffice.org - a multi-platform office productivity suite * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #include "rtl/uuid.h" #include "osl/thread.h" #include "osl/mutex.hxx" #include "uno/environment.hxx" #include "uno/mapping.hxx" #include "uno/lbnames.h" #include "typelib/typedescription.h" #include "current.hxx" using namespace ::osl; using namespace ::rtl; using namespace ::cppu; using namespace ::com::sun::star::uno; namespace cppu { static typelib_InterfaceTypeDescription * get_type_XCurrentContext() { static typelib_InterfaceTypeDescription * s_type_XCurrentContext = 0; if (0 == s_type_XCurrentContext) { ::osl::MutexGuard aGuard( ::osl::Mutex::getGlobalMutex() ); if (0 == s_type_XCurrentContext) { OUString sTypeName( RTL_CONSTASCII_USTRINGPARAM("com.sun.star.uno.XCurrentContext") ); typelib_InterfaceTypeDescription * pTD = 0; typelib_TypeDescriptionReference * pMembers[1] = { 0 }; OUString sMethodName0( RTL_CONSTASCII_USTRINGPARAM("com.sun.star.uno.XCurrentContext::getValueByName") ); typelib_typedescriptionreference_new( &pMembers[0], typelib_TypeClass_INTERFACE_METHOD, sMethodName0.pData ); typelib_typedescription_newInterface( &pTD, sTypeName.pData, 0x00000000, 0x0000, 0x0000, 0x00000000, 0x00000000, * typelib_static_type_getByTypeClass( typelib_TypeClass_INTERFACE ), 1, pMembers ); typelib_typedescription_register( (typelib_TypeDescription**)&pTD ); typelib_typedescriptionreference_release( pMembers[0] ); typelib_InterfaceMethodTypeDescription * pMethod = 0; typelib_Parameter_Init aParameters[1]; OUString sParamName0( RTL_CONSTASCII_USTRINGPARAM("Name") ); OUString sParamType0( RTL_CONSTASCII_USTRINGPARAM("string") ); aParameters[0].pParamName = sParamName0.pData; aParameters[0].eTypeClass = typelib_TypeClass_STRING; aParameters[0].pTypeName = sParamType0.pData; aParameters[0].bIn = sal_True; aParameters[0].bOut = sal_False; rtl_uString * pExceptions[1]; OUString sExceptionName0( RTL_CONSTASCII_USTRINGPARAM("com.sun.star.uno.RuntimeException") ); pExceptions[0] = sExceptionName0.pData; OUString sReturnType0( RTL_CONSTASCII_USTRINGPARAM("any") ); typelib_typedescription_newInterfaceMethod( &pMethod, 3, sal_False, sMethodName0.pData, typelib_TypeClass_ANY, sReturnType0.pData, 1, aParameters, 1, pExceptions ); typelib_typedescription_register( (typelib_TypeDescription**)&pMethod ); typelib_typedescription_release( (typelib_TypeDescription*)pMethod ); // another static ref: ++reinterpret_cast< typelib_TypeDescription * >( pTD )-> nStaticRefCount; s_type_XCurrentContext = pTD; } } return s_type_XCurrentContext; } //################################################################################################## //================================================================================================== class ThreadKey { sal_Bool _bInit; oslThreadKey _hThreadKey; oslThreadKeyCallbackFunction _pCallback; public: inline oslThreadKey getThreadKey() SAL_THROW(()); inline ThreadKey( oslThreadKeyCallbackFunction pCallback ) SAL_THROW(()); inline ~ThreadKey() SAL_THROW(()); }; //__________________________________________________________________________________________________ inline ThreadKey::ThreadKey( oslThreadKeyCallbackFunction pCallback ) SAL_THROW(()) : _bInit( sal_False ) , _pCallback( pCallback ) { } //__________________________________________________________________________________________________ inline ThreadKey::~ThreadKey() SAL_THROW(()) { if (_bInit) { ::osl_destroyThreadKey( _hThreadKey ); } } //__________________________________________________________________________________________________ inline oslThreadKey ThreadKey::getThreadKey() SAL_THROW(()) { if (! _bInit) { MutexGuard aGuard( Mutex::getGlobalMutex() ); if (! _bInit) { _hThreadKey = ::osl_createThreadKey( _pCallback ); _bInit = sal_True; } } return _hThreadKey; } //================================================================================================== extern "C" void SAL_CALL delete_IdContainer( void * p ) { if (p) { IdContainer * pId = reinterpret_cast< IdContainer * >( p ); if (pId->pCurrentContext) { (*pId->pCurrentContextEnv->releaseInterface)( pId->pCurrentContextEnv, pId->pCurrentContext ); (*((uno_Environment *)pId->pCurrentContextEnv)->release)( (uno_Environment *)pId->pCurrentContextEnv ); } if (pId->bInit) { ::rtl_byte_sequence_release( pId->pLocalThreadId ); ::rtl_byte_sequence_release( pId->pCurrentId ); } delete pId; } } //================================================================================================== IdContainer * getIdContainer() SAL_THROW(()) { static ThreadKey s_key( delete_IdContainer ); oslThreadKey aKey = s_key.getThreadKey(); IdContainer * pId = reinterpret_cast< IdContainer * >( ::osl_getThreadKeyData( aKey ) ); if (! pId) { pId = new IdContainer(); pId->pCurrentContext = 0; pId->pCurrentContextEnv = 0; pId->bInit = sal_False; ::osl_setThreadKeyData( aKey, pId ); } return pId; } } //################################################################################################## extern "C" CPPU_DLLPUBLIC sal_Bool SAL_CALL uno_setCurrentContext( void * pCurrentContext, rtl_uString * pEnvTypeName, void * pEnvContext ) SAL_THROW_EXTERN_C() { IdContainer * pId = getIdContainer(); OSL_ASSERT( pId ); // free old one if (pId->pCurrentContext) { (*pId->pCurrentContextEnv->releaseInterface)( pId->pCurrentContextEnv, pId->pCurrentContext ); (*((uno_Environment *)pId->pCurrentContextEnv)->release)( (uno_Environment *)pId->pCurrentContextEnv ); pId->pCurrentContextEnv = 0; pId->pCurrentContext = 0; } if (pCurrentContext) { uno_Environment * pEnv = 0; ::uno_getEnvironment( &pEnv, pEnvTypeName, pEnvContext ); OSL_ASSERT( pEnv && pEnv->pExtEnv ); if (pEnv) { if (pEnv->pExtEnv) { pId->pCurrentContextEnv = pEnv->pExtEnv; (*pId->pCurrentContextEnv->acquireInterface)( pId->pCurrentContextEnv, pCurrentContext ); pId->pCurrentContext = pCurrentContext; } else { (*pEnv->release)( pEnv ); return sal_False; } } else { return sal_False; } } return sal_True; } //################################################################################################## extern "C" CPPU_DLLPUBLIC sal_Bool SAL_CALL uno_getCurrentContext( void ** ppCurrentContext, rtl_uString * pEnvTypeName, void * pEnvContext ) SAL_THROW_EXTERN_C() { IdContainer * pId = getIdContainer(); OSL_ASSERT( pId ); Environment target_env; // release inout parameter if (*ppCurrentContext) { target_env = Environment(rtl::OUString(pEnvTypeName), pEnvContext); OSL_ASSERT( target_env.is() ); if (! target_env.is()) return sal_False; uno_ExtEnvironment * pEnv = target_env.get()->pExtEnv; OSL_ASSERT( 0 != pEnv ); if (0 == pEnv) return sal_False; (*pEnv->releaseInterface)( pEnv, *ppCurrentContext ); *ppCurrentContext = 0; } // case: null-ref if (0 == pId->pCurrentContext) return sal_True; if (! target_env.is()) { target_env = Environment(rtl::OUString(pEnvTypeName), pEnvContext); OSL_ASSERT( target_env.is() ); if (! target_env.is()) return sal_False; } Mapping mapping((uno_Environment *) pId->pCurrentContextEnv, target_env.get()); OSL_ASSERT( mapping.is() ); if (! mapping.is()) return sal_False; mapping.mapInterface(ppCurrentContext, pId->pCurrentContext, ::cppu::get_type_XCurrentContext() ); return sal_True; } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>/************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ /* $Id$ */ // --- Root --- #include <TClonesArray.h> #include <TGeoManager.h> #include <TObjArray.h> #include <TString.h> #include <TTree.h> #include "AliAODCaloCluster.h" #include "AliAODEvent.h" #include "AliAnalysisManager.h" #include "AliCDBEntry.h" #include "AliCDBManager.h" #include "AliCaloCalibPedestal.h" #include "AliEMCALAfterBurnerUF.h" #include "AliEMCALCalibData.h" #include "AliEMCALClusterizerNxN.h" #include "AliEMCALClusterizerv1.h" #include "AliEMCALDigit.h" #include "AliEMCALGeometry.h" #include "AliEMCALRecParam.h" #include "AliEMCALRecPoint.h" #include "AliEMCALRecoUtils.h" #include "AliESDEvent.h" #include "AliLog.h" #include "AliAnalysisTaskEMCALClusterizeFast.h" ClassImp(AliAnalysisTaskEMCALClusterizeFast) //________________________________________________________________________ AliAnalysisTaskEMCALClusterizeFast::AliAnalysisTaskEMCALClusterizeFast(const char *name) : AliAnalysisTaskSE(name), fRun(0), fDigitsArr(0), fClusterArr(0), fRecParam(new AliEMCALRecParam), fClusterizer(0), fUnfolder(0), fJustUnfold(kFALSE), fGeomName("EMCAL_FIRSTYEARV1"), fGeomMatrixSet(kFALSE), fLoadGeomMatrices(kFALSE), fOCDBpath(), fCalibData(0), fPedestalData(0), fOutputAODBranch(0), fOutputAODBrName(), fRecoUtils(0) { // Constructor fBranchNames = "ESD:AliESDHeader.,EMCALCells.,AOD:cells"; for(Int_t i = 0; i < 10; ++i) fGeomMatrix[i] = 0; } //________________________________________________________________________ AliAnalysisTaskEMCALClusterizeFast::~AliAnalysisTaskEMCALClusterizeFast() { // Destructor. delete fDigitsArr; delete fClusterizer; delete fUnfolder; delete fRecoUtils; } //------------------------------------------------------------------- void AliAnalysisTaskEMCALClusterizeFast::UserCreateOutputObjects() { // Create output objects. if (!fOutputAODBrName.IsNull()) { fOutputAODBranch = new TClonesArray("AliAODCaloCluster", 0); fOutputAODBranch->SetName(fOutputAODBrName); AddAODBranch("TClonesArray", &fOutputAODBranch); AliInfo(Form("Created Branch: %s",fOutputAODBrName.Data())); } } //________________________________________________________________________ void AliAnalysisTaskEMCALClusterizeFast::UserExec(Option_t *) { // Main loop, called for each event // remove the contents of output list set in the previous event if (fOutputAODBranch) fOutputAODBranch->Clear("C"); AliESDEvent *esdevent = dynamic_cast<AliESDEvent*>(InputEvent()); AliAODEvent *aodevent = dynamic_cast<AliAODEvent*>(InputEvent()); if (!esdevent&&!aodevent) { Error("UserExec","Event not available"); return; } LoadBranches(); Init(); if (fJustUnfold) { AliWarning("Unfolding not implemented"); } else { if (esdevent) FillDigitsArray(esdevent); else FillDigitsArray(aodevent); fClusterizer->Digits2Clusters(""); if (esdevent &&fRecoUtils) fRecoUtils->FindMatches(esdevent,fClusterArr); if (fOutputAODBranch) RecPoints2Clusters(); } } //________________________________________________________________________ void AliAnalysisTaskEMCALClusterizeFast::FillDigitsArray(AliAODEvent *event) { // Fill digits from cells. fDigitsArr->Clear("C"); AliAODCaloCells *cells = event->GetEMCALCells(); Int_t ncells = cells->GetNumberOfCells(); if (ncells>fDigitsArr->GetSize()) fDigitsArr->Expand(2*ncells); for (Int_t icell = 0, idigit = 0; icell < ncells; ++icell) { Double_t cellAmplitude=0, cellTime=0; Short_t cellNumber=0; if (cells->GetCell(icell, cellNumber, cellAmplitude, cellTime) != kTRUE) break; AliEMCALDigit *digit = (AliEMCALDigit*) fDigitsArr->New(idigit); digit->SetId(cellNumber); digit->SetAmplitude(cellAmplitude); digit->SetTime(cellTime); digit->SetTimeR(cellTime); digit->SetIndexInList(idigit); digit->SetType(AliEMCALDigit::kHG); idigit++; } } //________________________________________________________________________ void AliAnalysisTaskEMCALClusterizeFast::FillDigitsArray(AliESDEvent *event) { // Fill digits from cells. fDigitsArr->Clear("C"); AliESDCaloCells *cells = event->GetEMCALCells(); Int_t ncells = cells->GetNumberOfCells(); if (ncells>fDigitsArr->GetSize()) fDigitsArr->Expand(2*ncells); for (Int_t icell = 0, idigit = 0; icell < ncells; ++icell) { Double_t cellAmplitude=0, cellTime=0; Short_t cellNumber=0; if (cells->GetCell(icell, cellNumber, cellAmplitude, cellTime) != kTRUE) break; AliEMCALDigit *digit = (AliEMCALDigit*) fDigitsArr->New(idigit); digit->SetId(cellNumber); digit->SetAmplitude(cellAmplitude); digit->SetTime(cellTime); digit->SetTimeR(cellTime); digit->SetIndexInList(idigit); digit->SetType(AliEMCALDigit::kHG); idigit++; } } //________________________________________________________________________________________ void AliAnalysisTaskEMCALClusterizeFast::RecPoints2Clusters() { // Cluster energy, global position, cells and their amplitude fractions are restored. AliESDEvent *esdevent = dynamic_cast<AliESDEvent*>(InputEvent()); Int_t Ncls = fClusterArr->GetEntriesFast(); for(Int_t i=0, nout=0; i < Ncls; ++i) { AliEMCALRecPoint *recpoint = static_cast<AliEMCALRecPoint*>(fClusterArr->At(i)); Int_t ncells_true = 0; const Int_t ncells = recpoint->GetMultiplicity(); UShort_t absIds[ncells]; Double32_t ratios[ncells]; Int_t *dlist = recpoint->GetDigitsList(); Float_t *elist = recpoint->GetEnergiesList(); for (Int_t c = 0; c < ncells; ++c) { AliEMCALDigit *digit = static_cast<AliEMCALDigit*>(fDigitsArr->At(dlist[c])); absIds[ncells_true] = digit->GetId(); ratios[ncells_true] = elist[c]/digit->GetAmplitude(); if (ratios[ncells_true] > 0.001) ++ncells_true; } if (ncells_true < 1) { AliWarning("Skipping cluster with no cells"); continue; } // calculate new cluster position TVector3 gpos; Float_t g[3]; recpoint->EvalGlobalPosition(fRecParam->GetW0(), fDigitsArr); recpoint->GetGlobalPosition(gpos); gpos.GetXYZ(g); AliAODCaloCluster *clus = static_cast<AliAODCaloCluster*>(fOutputAODBranch->New(nout++)); clus->SetType(AliVCluster::kEMCALClusterv1); clus->SetE(recpoint->GetEnergy()); clus->SetPosition(g); clus->SetNCells(ncells_true); clus->SetCellsAbsId(absIds); clus->SetCellsAmplitudeFraction(ratios); clus->SetDispersion(recpoint->GetDispersion()); clus->SetChi2(-1); //not yet implemented clus->SetTOF(recpoint->GetTime()) ; //time-of-flight clus->SetNExMax(recpoint->GetNExMax()); //number of local maxima Float_t elipAxis[2]; recpoint->GetElipsAxis(elipAxis); clus->SetM02(elipAxis[0]*elipAxis[0]) ; clus->SetM20(elipAxis[1]*elipAxis[1]) ; clus->SetDistToBadChannel(recpoint->GetDistanceToBadTower()); if (esdevent && fRecoUtils) { Int_t trackIndex = fRecoUtils->GetMatchedTrackIndex(i); if(trackIndex >= 0) { clus->AddTrackMatched(esdevent->GetTrack(trackIndex)); if(DebugLevel() > 1) AliInfo(Form("Matched Track index %d to new cluster %d\n",trackIndex,i)); } } } } //________________________________________________________________________________________ void AliAnalysisTaskEMCALClusterizeFast::Init() { //Select clusterization/unfolding algorithm and set all the needed parameters AliVEvent * event = InputEvent(); if (!event) { AliWarning("Event not available!!!"); return; } if (event->GetRunNumber()==fRun) return; fRun = event->GetRunNumber(); if (fJustUnfold){ // init the unfolding afterburner delete fUnfolder; fUnfolder = new AliEMCALAfterBurnerUF(fRecParam->GetW0(),fRecParam->GetLocMaxCut()); return; } AliCDBManager *cdb = AliCDBManager::Instance(); if (!cdb->IsDefaultStorageSet() && !fOCDBpath.IsNull()) cdb->SetDefaultStorage(fOCDBpath); if (fRun!=cdb->GetRun()) cdb->SetRun(fRun); AliEMCALGeometry *geometry = AliEMCALGeometry::GetInstance(fGeomName); if (!geometry) { AliFatal("Geometry not available!!!"); return; } if (!fGeomMatrixSet) { if (fLoadGeomMatrices) { for(Int_t mod=0; mod < (geometry->GetEMCGeometry())->GetNumberOfSuperModules(); ++mod) { if(fGeomMatrix[mod]){ if(DebugLevel() > 2) fGeomMatrix[mod]->Print(); geometry->SetMisalMatrix(fGeomMatrix[mod],mod); } } } else { for(Int_t mod=0; mod < geometry->GetEMCGeometry()->GetNumberOfSuperModules(); ++mod) { if(event->GetEMCALMatrix(mod)) { if(DebugLevel() > 2) event->GetEMCALMatrix(mod)->Print(); geometry->SetMisalMatrix(event->GetEMCALMatrix(mod),mod); } } } fGeomMatrixSet=kTRUE; } // setup digit array if needed if (!fDigitsArr) { fDigitsArr = new TClonesArray("AliEMCALDigit", 1000); fDigitsArr->SetOwner(1); } // then setup clusterizer delete fClusterizer; if (fRecParam->GetClusterizerFlag() == AliEMCALRecParam::kClusterizerv1) fClusterizer = new AliEMCALClusterizerv1(geometry); else if(fRecParam->GetClusterizerFlag() == AliEMCALRecParam::kClusterizerNxN) fClusterizer = new AliEMCALClusterizerNxN(geometry); else if(fRecParam->GetClusterizerFlag() > AliEMCALRecParam::kClusterizerNxN) { AliEMCALClusterizerNxN *clusterizer = new AliEMCALClusterizerNxN(geometry); clusterizer->SetNRowDiff(2); clusterizer->SetNColDiff(2); fClusterizer = clusterizer; } else{ AliFatal(Form("Clusterizer < %d > not available", fRecParam->GetClusterizerFlag())); } fClusterizer->InitParameters(fRecParam); fClusterizer->SetInputCalibrated(kTRUE); if (!fCalibData&&0) { AliCDBEntry *entry = static_cast<AliCDBEntry*>(AliCDBManager::Instance()->Get("EMCAL/Calib/Data")); if (entry) fCalibData = static_cast<AliEMCALCalibData*>(entry->GetObject()); if (!fCalibData) AliFatal("Calibration parameters not found in CDB!"); } if (!fPedestalData&&0) { AliCDBEntry *entry = static_cast<AliCDBEntry*>(AliCDBManager::Instance()->Get("EMCAL/Calib/Pedestals")); if (entry) fPedestalData = static_cast<AliCaloCalibPedestal*>(entry->GetObject()); } fClusterizer->SetCalibrationParameters(fCalibData); fClusterizer->SetCaloCalibPedestal(fPedestalData); fClusterizer->SetDigitsArr(fDigitsArr); fClusterizer->SetOutput(0); fClusterArr = const_cast<TObjArray *>(fClusterizer->GetRecPoints()); } <commit_msg>run on AOD branches<commit_after>/************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ /* $Id$ */ // --- Root --- #include <TClonesArray.h> #include <TGeoManager.h> #include <TObjArray.h> #include <TString.h> #include <TTree.h> #include "AliAODCaloCluster.h" #include "AliAODEvent.h" #include "AliAnalysisManager.h" #include "AliCDBEntry.h" #include "AliCDBManager.h" #include "AliCaloCalibPedestal.h" #include "AliEMCALAfterBurnerUF.h" #include "AliEMCALCalibData.h" #include "AliEMCALClusterizerNxN.h" #include "AliEMCALClusterizerv1.h" #include "AliEMCALDigit.h" #include "AliEMCALGeometry.h" #include "AliEMCALRecParam.h" #include "AliEMCALRecPoint.h" #include "AliEMCALRecoUtils.h" #include "AliESDEvent.h" #include "AliLog.h" #include "AliAnalysisTaskEMCALClusterizeFast.h" ClassImp(AliAnalysisTaskEMCALClusterizeFast) //________________________________________________________________________ AliAnalysisTaskEMCALClusterizeFast::AliAnalysisTaskEMCALClusterizeFast(const char *name) : AliAnalysisTaskSE(name), fRun(0), fDigitsArr(0), fClusterArr(0), fRecParam(new AliEMCALRecParam), fClusterizer(0), fUnfolder(0), fJustUnfold(kFALSE), fGeomName("EMCAL_FIRSTYEARV1"), fGeomMatrixSet(kFALSE), fLoadGeomMatrices(kFALSE), fOCDBpath(), fCalibData(0), fPedestalData(0), fOutputAODBranch(0), fOutputAODBrName(), fRecoUtils(0) { // Constructor fBranchNames = "ESD:AliESDHeader.,EMCALCells. AOD:header,emcalCells"; for(Int_t i = 0; i < 10; ++i) fGeomMatrix[i] = 0; } //________________________________________________________________________ AliAnalysisTaskEMCALClusterizeFast::~AliAnalysisTaskEMCALClusterizeFast() { // Destructor. delete fDigitsArr; delete fClusterizer; delete fUnfolder; delete fRecoUtils; } //------------------------------------------------------------------- void AliAnalysisTaskEMCALClusterizeFast::UserCreateOutputObjects() { // Create output objects. if (!fOutputAODBrName.IsNull()) { fOutputAODBranch = new TClonesArray("AliAODCaloCluster", 0); fOutputAODBranch->SetName(fOutputAODBrName); AddAODBranch("TClonesArray", &fOutputAODBranch); AliInfo(Form("Created Branch: %s",fOutputAODBrName.Data())); } } //________________________________________________________________________ void AliAnalysisTaskEMCALClusterizeFast::UserExec(Option_t *) { // Main loop, called for each event // remove the contents of output list set in the previous event if (fOutputAODBranch) fOutputAODBranch->Clear("C"); AliESDEvent *esdevent = dynamic_cast<AliESDEvent*>(InputEvent()); AliAODEvent *aodevent = dynamic_cast<AliAODEvent*>(InputEvent()); if (!esdevent&&!aodevent) { Error("UserExec","Event not available"); return; } LoadBranches(); Init(); if (fJustUnfold) { AliWarning("Unfolding not implemented"); } else { if (esdevent) FillDigitsArray(esdevent); else FillDigitsArray(aodevent); fClusterizer->Digits2Clusters(""); if (esdevent &&fRecoUtils) fRecoUtils->FindMatches(esdevent,fClusterArr); if (fOutputAODBranch) RecPoints2Clusters(); } } //________________________________________________________________________ void AliAnalysisTaskEMCALClusterizeFast::FillDigitsArray(AliAODEvent *event) { // Fill digits from cells. fDigitsArr->Clear("C"); AliAODCaloCells *cells = event->GetEMCALCells(); Int_t ncells = cells->GetNumberOfCells(); if (ncells>fDigitsArr->GetSize()) fDigitsArr->Expand(2*ncells); for (Int_t icell = 0, idigit = 0; icell < ncells; ++icell) { Double_t cellAmplitude=0, cellTime=0; Short_t cellNumber=0; if (cells->GetCell(icell, cellNumber, cellAmplitude, cellTime) != kTRUE) break; AliEMCALDigit *digit = (AliEMCALDigit*) fDigitsArr->New(idigit); digit->SetId(cellNumber); digit->SetAmplitude(cellAmplitude); digit->SetTime(cellTime); digit->SetTimeR(cellTime); digit->SetIndexInList(idigit); digit->SetType(AliEMCALDigit::kHG); idigit++; } } //________________________________________________________________________ void AliAnalysisTaskEMCALClusterizeFast::FillDigitsArray(AliESDEvent *event) { // Fill digits from cells. fDigitsArr->Clear("C"); AliESDCaloCells *cells = event->GetEMCALCells(); Int_t ncells = cells->GetNumberOfCells(); if (ncells>fDigitsArr->GetSize()) fDigitsArr->Expand(2*ncells); for (Int_t icell = 0, idigit = 0; icell < ncells; ++icell) { Double_t cellAmplitude=0, cellTime=0; Short_t cellNumber=0; if (cells->GetCell(icell, cellNumber, cellAmplitude, cellTime) != kTRUE) break; AliEMCALDigit *digit = (AliEMCALDigit*) fDigitsArr->New(idigit); digit->SetId(cellNumber); digit->SetAmplitude(cellAmplitude); digit->SetTime(cellTime); digit->SetTimeR(cellTime); digit->SetIndexInList(idigit); digit->SetType(AliEMCALDigit::kHG); idigit++; } } //________________________________________________________________________________________ void AliAnalysisTaskEMCALClusterizeFast::RecPoints2Clusters() { // Cluster energy, global position, cells and their amplitude fractions are restored. AliESDEvent *esdevent = dynamic_cast<AliESDEvent*>(InputEvent()); Int_t Ncls = fClusterArr->GetEntriesFast(); for(Int_t i=0, nout=0; i < Ncls; ++i) { AliEMCALRecPoint *recpoint = static_cast<AliEMCALRecPoint*>(fClusterArr->At(i)); Int_t ncells_true = 0; const Int_t ncells = recpoint->GetMultiplicity(); UShort_t absIds[ncells]; Double32_t ratios[ncells]; Int_t *dlist = recpoint->GetDigitsList(); Float_t *elist = recpoint->GetEnergiesList(); for (Int_t c = 0; c < ncells; ++c) { AliEMCALDigit *digit = static_cast<AliEMCALDigit*>(fDigitsArr->At(dlist[c])); absIds[ncells_true] = digit->GetId(); ratios[ncells_true] = elist[c]/digit->GetAmplitude(); if (ratios[ncells_true] > 0.001) ++ncells_true; } if (ncells_true < 1) { AliWarning("Skipping cluster with no cells"); continue; } // calculate new cluster position TVector3 gpos; Float_t g[3]; recpoint->EvalGlobalPosition(fRecParam->GetW0(), fDigitsArr); recpoint->GetGlobalPosition(gpos); gpos.GetXYZ(g); AliAODCaloCluster *clus = static_cast<AliAODCaloCluster*>(fOutputAODBranch->New(nout++)); clus->SetType(AliVCluster::kEMCALClusterv1); clus->SetE(recpoint->GetEnergy()); clus->SetPosition(g); clus->SetNCells(ncells_true); clus->SetCellsAbsId(absIds); clus->SetCellsAmplitudeFraction(ratios); clus->SetDispersion(recpoint->GetDispersion()); clus->SetChi2(-1); //not yet implemented clus->SetTOF(recpoint->GetTime()) ; //time-of-flight clus->SetNExMax(recpoint->GetNExMax()); //number of local maxima Float_t elipAxis[2]; recpoint->GetElipsAxis(elipAxis); clus->SetM02(elipAxis[0]*elipAxis[0]) ; clus->SetM20(elipAxis[1]*elipAxis[1]) ; clus->SetDistToBadChannel(recpoint->GetDistanceToBadTower()); if (esdevent && fRecoUtils) { Int_t trackIndex = fRecoUtils->GetMatchedTrackIndex(i); if(trackIndex >= 0) { clus->AddTrackMatched(esdevent->GetTrack(trackIndex)); if(DebugLevel() > 1) AliInfo(Form("Matched Track index %d to new cluster %d\n",trackIndex,i)); } } } } //________________________________________________________________________________________ void AliAnalysisTaskEMCALClusterizeFast::Init() { //Select clusterization/unfolding algorithm and set all the needed parameters AliVEvent * event = InputEvent(); if (!event) { AliWarning("Event not available!!!"); return; } if (event->GetRunNumber()==fRun) return; fRun = event->GetRunNumber(); if (fJustUnfold){ // init the unfolding afterburner delete fUnfolder; fUnfolder = new AliEMCALAfterBurnerUF(fRecParam->GetW0(),fRecParam->GetLocMaxCut()); return; } AliCDBManager *cdb = AliCDBManager::Instance(); if (!cdb->IsDefaultStorageSet() && !fOCDBpath.IsNull()) cdb->SetDefaultStorage(fOCDBpath); if (fRun!=cdb->GetRun()) cdb->SetRun(fRun); AliEMCALGeometry *geometry = AliEMCALGeometry::GetInstance(fGeomName); if (!geometry) { AliFatal("Geometry not available!!!"); return; } if (!fGeomMatrixSet) { if (fLoadGeomMatrices) { for(Int_t mod=0; mod < (geometry->GetEMCGeometry())->GetNumberOfSuperModules(); ++mod) { if(fGeomMatrix[mod]){ if(DebugLevel() > 2) fGeomMatrix[mod]->Print(); geometry->SetMisalMatrix(fGeomMatrix[mod],mod); } } } else { for(Int_t mod=0; mod < geometry->GetEMCGeometry()->GetNumberOfSuperModules(); ++mod) { if(event->GetEMCALMatrix(mod)) { if(DebugLevel() > 2) event->GetEMCALMatrix(mod)->Print(); geometry->SetMisalMatrix(event->GetEMCALMatrix(mod),mod); } } } fGeomMatrixSet=kTRUE; } // setup digit array if needed if (!fDigitsArr) { fDigitsArr = new TClonesArray("AliEMCALDigit", 1000); fDigitsArr->SetOwner(1); } // then setup clusterizer delete fClusterizer; if (fRecParam->GetClusterizerFlag() == AliEMCALRecParam::kClusterizerv1) fClusterizer = new AliEMCALClusterizerv1(geometry); else if(fRecParam->GetClusterizerFlag() == AliEMCALRecParam::kClusterizerNxN) fClusterizer = new AliEMCALClusterizerNxN(geometry); else if(fRecParam->GetClusterizerFlag() > AliEMCALRecParam::kClusterizerNxN) { AliEMCALClusterizerNxN *clusterizer = new AliEMCALClusterizerNxN(geometry); clusterizer->SetNRowDiff(2); clusterizer->SetNColDiff(2); fClusterizer = clusterizer; } else{ AliFatal(Form("Clusterizer < %d > not available", fRecParam->GetClusterizerFlag())); } fClusterizer->InitParameters(fRecParam); fClusterizer->SetInputCalibrated(kTRUE); if (!fCalibData&&0) { AliCDBEntry *entry = static_cast<AliCDBEntry*>(AliCDBManager::Instance()->Get("EMCAL/Calib/Data")); if (entry) fCalibData = static_cast<AliEMCALCalibData*>(entry->GetObject()); if (!fCalibData) AliFatal("Calibration parameters not found in CDB!"); } if (!fPedestalData&&0) { AliCDBEntry *entry = static_cast<AliCDBEntry*>(AliCDBManager::Instance()->Get("EMCAL/Calib/Pedestals")); if (entry) fPedestalData = static_cast<AliCaloCalibPedestal*>(entry->GetObject()); } fClusterizer->SetCalibrationParameters(fCalibData); fClusterizer->SetCaloCalibPedestal(fPedestalData); fClusterizer->SetDigitsArr(fDigitsArr); fClusterizer->SetOutput(0); fClusterArr = const_cast<TObjArray *>(fClusterizer->GetRecPoints()); } <|endoftext|>
<commit_before> /////////////////////////////////////////////////////////////////////////// ///\file AddTaskEMCALPhotonIsolation.C ///\brief Configuration of AliAnalysisTaskEMCALPhotonIsolation /// /// Version to be used in lego train for testing on pp@7TeV /// /// \author Lucile Ronflette <lucile.ronflette@cern.ch>, SUBATECH, Nantes /// \author Davide Francesco Lodato <davide.francesco.lodato@cern.ch>, Utrecht University /// \author Marco Marquard <marco.marquard@cern.ch>, University Frankfurt am Main /////////////////////////////////////////////////////////////////////////// AliAnalysisTaskEMCALPhotonIsolation* AddTaskEMCALPhotonIsolation( const char* periodstr = "LHC11c", const char* ntracks = "EmcalTracks", const char* nclusters = "EmcCaloClusters", const UInt_t pSel = AliVEvent::kEMC7, const TString dType = "ESD", const Bool_t bHisto = kTRUE, const Int_t iOutput = 0, const Bool_t bIsMC = kFALSE, const Bool_t bMCNormalization = kFALSE, const Bool_t bNLMCut = kFALSE, const Int_t NLMCut = 0, const Double_t minPtCutCluster = 0.3, const Double_t EtIso = 2., const Int_t iIsoMethod = 1, const Int_t iEtIsoMethod = 0, const Int_t iUEMethod = 1, const Bool_t bUseofTPC = kFALSE, const Double_t TMdeta = 0.02, const Double_t TMdphi = 0.03, const Bool_t bTMClusterRejection = kTRUE, const Bool_t bTMClusterRejectionInCone = kTRUE, const Float_t iIsoConeRadius = 0.4, const Bool_t iSmearingSS = kFALSE, const Float_t iWidthSSsmear = 0., const Float_t iMean_SSsmear = 0., const Bool_t iExtraIsoCuts = kFALSE, const Bool_t i_pPb = kFALSE, const Bool_t isQA = kFALSE, TString configBasePath = "", const Int_t bWhichToSmear = 0, const Int_t minNLM = 1 ) { Printf("Preparing neutral cluster analysis\n"); // #### Define manager and data container names AliAnalysisManager *manager = AliAnalysisManager::GetAnalysisManager(); if (!manager) { ::Error("AddTaskEMCALPhotonIsolation", "No analysis manager to connect to."); return NULL; } printf("Creating container names for cluster analysis\n"); TString myContName(""); if(bIsMC) myContName = Form("Analysis_Neutrals_MC"); else myContName = Form("Analysis_Neutrals"); myContName.Append(Form("_TM_%s_CPVe%.2lf_CPVp%.2lf_IsoMet%d_EtIsoMet%d_UEMet%d_TPCbound_%s_IsoConeR%.1f_NLMCut_%s_minNLM%d_maxNLM%d_SSsmear_%s_Width%.3f_Mean_%.3f_PureIso_%s_WhichSmear_%d",bTMClusterRejection? "On" :"Off", TMdeta , TMdphi ,iIsoMethod,iEtIsoMethod,iUEMethod,bUseofTPC ? "Yes" : "No",iIsoConeRadius,bNLMCut ? "On": "Off",minNLM, NLMCut, iSmearingSS ? "On":"Off",iWidthSSsmear,iMean_SSsmear,iExtraIsoCuts?"On":"Off",bWhichToSmear)); // #### Define analysis task AliAnalysisTaskEMCALPhotonIsolation* task = new AliAnalysisTaskEMCALPhotonIsolation("Analysis",bHisto); TString configFile("config_PhotonIsolation.C"); //Name of config file // if(gSystem->AccessPathName(configFile.Data())){ //Check for exsisting file and delete it // gSystem->Exec(Form("rm %s",configFile.Data())); // } if(configBasePath.IsNull()){ //Check if a specific config should be used and copy appropriate file configBasePath="$ALICE_PHYSICS/PWGGA/EMCALTasks/macros"; gSystem->Exec(Form("cp %s/%s .",configBasePath.Data(),configFile.Data())); } else if(configBasePath.Contains("alien:///")){ gSystem->Exec(Form("alien_cp %s/%s .",configBasePath.Data(),configFile.Data())); } else{ gSystem->Exec(Form("cp %s/%s .",configBasePath.Data(),configFile.Data())); } configBasePath=Form("%s/",gSystem->pwd()); ifstream configIn; //Open config file for hash calculation configIn.open(configFile); TString configStr; configStr.ReadFile(configIn); TString configMD5 = configStr.MD5(); configMD5.Resize(5); //Short hash value for usable extension TString configFileMD5 = configFile; TDatime time; //Get timestamp Int_t timeStamp = time.GetTime(); configFileMD5.ReplaceAll(".C",Form("\_%s_%i.C",configMD5.Data(),timeStamp)); if(gSystem->AccessPathName(configFileMD5.Data())){ //Add additional identifier if file exists gSystem->Exec(Form("mv %s %s",configFile.Data(),configFileMD5.Data())); } else{ while(!gSystem->AccessPathName(configFileMD5.Data())){ configFileMD5.ReplaceAll(".C","_1.C"); } gSystem->Exec(Form("mv %s %s",configFile.Data(),configFileMD5.Data())); } TString configFilePath(configBasePath+"/"+configFileMD5); gROOT->LoadMacro(configFilePath.Data()); printf("Path of config file: %s\n",configFilePath.Data()); // #### Task preferences task->SetOutputFormat(iOutput); task->SetLCAnalysis(kFALSE); task->SetIsoConeRadius(iIsoConeRadius); task->SetEtIsoThreshold(EtIso); // after should be replace by EtIso task->SetCTMdeltaEta(TMdeta); // after should be replaced by TMdeta task->SetCTMdeltaPhi(TMdphi); // after should be replaced by TMdphi task->SetQA(isQA); task->SetIsoMethod(iIsoMethod); task->SetEtIsoMethod(iEtIsoMethod); task->SetUEMethod(iUEMethod); task->SetUSEofTPC(bUseofTPC); task->SetMC(bIsMC); task->SetM02Smearing(iSmearingSS); task->SetWidth4Smear(iWidthSSsmear); task->SetMean4Smear(iMean_SSsmear); task->SetExtraIsoCuts(iExtraIsoCuts); task->SetAnalysispPb(i_pPb); task->SetNLMCut(bNLMCut,NLMCut,minNLM); task->SetPtBinning(ptBin); task->SetM02Binning(M02Bin); task->SetEtisoBinning(EtisoBin); task->SetEtueBinning(EtueBin); task->SetEtaBinning(EtaBin); task->SetPhiBinning(PhiBin); task->SetLabelBinning(LabelBin); task->SetPDGBinning(PDGBin); task->SetMomPDGBinning(MomPDGBin); task->SetClustPDGBinning(ClustPDGBin); task->SetDxBinning(DxBin); task->SetDzBinning(DzBin); task->SetDecayBinning(DecayBin); task->SetSmearForClusters(bWhichToSmear); if(bIsMC && bMCNormalization) task->SetIsPythia(kTRUE); TString name(Form("PhotonIsolation_%s_%s", ntracks, nclusters)); cout<<"name of the containers "<<name.Data()<<endl; // tracks to be used for the track matching (already used in TM task, TPC only tracks) AliTrackContainer *trackCont = task->AddTrackContainer("tracks"); if(!trackCont) Printf("Error with TPCOnly!!"); trackCont->SetName("tpconlyMatch"); trackCont->SetTrackFilterType(AliEmcalTrackSelection::kTPCOnlyTracks); // clusters to be used in the analysis already filtered AliClusterContainer *clusterCont = task->AddClusterContainer(nclusters); // tracks to be used in the analysis (Hybrid tracks) AliTrackContainer * tracksForAnalysis = task->AddTrackContainer("tracks"); if(!tracksForAnalysis) Printf("Error with Hybrids!!"); tracksForAnalysis->SetName("filterTracksAna"); tracksForAnalysis->SetFilterHybridTracks(kTRUE); if(!bIsMC){ tracksForAnalysis->SetTrackCutsPeriod(periodstr); tracksForAnalysis->SetDefTrackCutsPeriod(periodstr); } Printf("Name of Tracks for matching: %s \n Name for Tracks for Isolation: %s",trackCont->GetName(),tracksForAnalysis->GetName()); printf("Task for neutral cluster analysis created and configured, pass it to AnalysisManager\n"); // #### Add analysis task manager->AddTask(task); AliAnalysisDataContainer *contHistos = manager->CreateContainer(myContName.Data(), TList::Class(), AliAnalysisManager::kOutputContainer,Form("%s:NeutralClusters",AliAnalysisManager::GetCommonFileName())); AliAnalysisDataContainer *cinput = manager->GetCommonInputContainer(); manager->ConnectInput(task, 0, cinput); manager->ConnectOutput(task, 1, contHistos); return task; } <commit_msg>Loading Geometry via the AliAnalysisTaskEmcal method (note that one should use the CDBConnect task first<commit_after> /////////////////////////////////////////////////////////////////////////// ///\file AddTaskEMCALPhotonIsolation.C ///\brief Configuration of AliAnalysisTaskEMCALPhotonIsolation /// /// Version to be used in lego train for testing on pp@7TeV /// /// \author Lucile Ronflette <lucile.ronflette@cern.ch>, SUBATECH, Nantes /// \author Davide Francesco Lodato <davide.francesco.lodato@cern.ch>, Utrecht University /// \author Marco Marquard <marco.marquard@cern.ch>, University Frankfurt am Main /////////////////////////////////////////////////////////////////////////// AliAnalysisTaskEMCALPhotonIsolation* AddTaskEMCALPhotonIsolation( const char* periodstr = "LHC11c", const char* ntracks = "EmcalTracks", const char* nclusters = "EmcCaloClusters", const UInt_t pSel = AliVEvent::kEMC7, const TString dType = "ESD", const Bool_t bHisto = kTRUE, const Int_t iOutput = 0, const Bool_t bIsMC = kFALSE, const Bool_t bMCNormalization = kFALSE, const Bool_t bNLMCut = kFALSE, const Int_t NLMCut = 0, const Double_t minPtCutCluster = 0.3, const Double_t EtIso = 2., const Int_t iIsoMethod = 1, const Int_t iEtIsoMethod = 0, const Int_t iUEMethod = 1, const Bool_t bUseofTPC = kFALSE, const Double_t TMdeta = 0.02, const Double_t TMdphi = 0.03, const Bool_t bTMClusterRejection = kTRUE, const Bool_t bTMClusterRejectionInCone = kTRUE, const Float_t iIsoConeRadius = 0.4, const Bool_t iSmearingSS = kFALSE, const Float_t iWidthSSsmear = 0., const Float_t iMean_SSsmear = 0., const Bool_t iExtraIsoCuts = kFALSE, const Bool_t i_pPb = kFALSE, const Bool_t isQA = kFALSE, TString configBasePath = "", const Int_t bWhichToSmear = 0, const Int_t minNLM = 1 ) { Printf("Preparing neutral cluster analysis\n"); // #### Define manager and data container names AliAnalysisManager *manager = AliAnalysisManager::GetAnalysisManager(); if (!manager) { ::Error("AddTaskEMCALPhotonIsolation", "No analysis manager to connect to."); return NULL; } printf("Creating container names for cluster analysis\n"); TString myContName(""); if(bIsMC) myContName = Form("Analysis_Neutrals_MC"); else myContName = Form("Analysis_Neutrals"); myContName.Append(Form("_TM_%s_CPVe%.2lf_CPVp%.2lf_IsoMet%d_EtIsoMet%d_UEMet%d_TPCbound_%s_IsoConeR%.1f_NLMCut_%s_minNLM%d_maxNLM%d_SSsmear_%s_Width%.3f_Mean_%.3f_PureIso_%s_WhichSmear_%d",bTMClusterRejection? "On" :"Off", TMdeta , TMdphi ,iIsoMethod,iEtIsoMethod,iUEMethod,bUseofTPC ? "Yes" : "No",iIsoConeRadius,bNLMCut ? "On": "Off",minNLM, NLMCut, iSmearingSS ? "On":"Off",iWidthSSsmear,iMean_SSsmear,iExtraIsoCuts?"On":"Off",bWhichToSmear)); // #### Define analysis task AliAnalysisTaskEMCALPhotonIsolation* task = new AliAnalysisTaskEMCALPhotonIsolation("Analysis",bHisto); TString configFile("config_PhotonIsolation.C"); //Name of config file // if(gSystem->AccessPathName(configFile.Data())){ //Check for exsisting file and delete it // gSystem->Exec(Form("rm %s",configFile.Data())); // } if(configBasePath.IsNull()){ //Check if a specific config should be used and copy appropriate file configBasePath="$ALICE_PHYSICS/PWGGA/EMCALTasks/macros"; gSystem->Exec(Form("cp %s/%s .",configBasePath.Data(),configFile.Data())); } else if(configBasePath.Contains("alien:///")){ gSystem->Exec(Form("alien_cp %s/%s .",configBasePath.Data(),configFile.Data())); } else{ gSystem->Exec(Form("cp %s/%s .",configBasePath.Data(),configFile.Data())); } configBasePath=Form("%s/",gSystem->pwd()); ifstream configIn; //Open config file for hash calculation configIn.open(configFile); TString configStr; configStr.ReadFile(configIn); TString configMD5 = configStr.MD5(); configMD5.Resize(5); //Short hash value for usable extension TString configFileMD5 = configFile; TDatime time; //Get timestamp Int_t timeStamp = time.GetTime(); configFileMD5.ReplaceAll(".C",Form("\_%s_%i.C",configMD5.Data(),timeStamp)); if(gSystem->AccessPathName(configFileMD5.Data())){ //Add additional identifier if file exists gSystem->Exec(Form("mv %s %s",configFile.Data(),configFileMD5.Data())); } else{ while(!gSystem->AccessPathName(configFileMD5.Data())){ configFileMD5.ReplaceAll(".C","_1.C"); } gSystem->Exec(Form("mv %s %s",configFile.Data(),configFileMD5.Data())); } TString configFilePath(configBasePath+"/"+configFileMD5); gROOT->LoadMacro(configFilePath.Data()); printf("Path of config file: %s\n",configFilePath.Data()); // #### Task preferences task->SetOutputFormat(iOutput); task->SetLCAnalysis(kFALSE); task->SetIsoConeRadius(iIsoConeRadius); task->SetEtIsoThreshold(EtIso); // after should be replace by EtIso task->SetCTMdeltaEta(TMdeta); // after should be replaced by TMdeta task->SetCTMdeltaPhi(TMdphi); // after should be replaced by TMdphi task->SetQA(isQA); task->SetIsoMethod(iIsoMethod); task->SetEtIsoMethod(iEtIsoMethod); task->SetUEMethod(iUEMethod); task->SetUSEofTPC(bUseofTPC); task->SetMC(bIsMC); task->SetM02Smearing(iSmearingSS); task->SetWidth4Smear(iWidthSSsmear); task->SetMean4Smear(iMean_SSsmear); task->SetExtraIsoCuts(iExtraIsoCuts); task->SetAnalysispPb(i_pPb); task->SetNLMCut(bNLMCut,NLMCut,minNLM); task->SetPtBinning(ptBin); task->SetM02Binning(M02Bin); task->SetEtisoBinning(EtisoBin); task->SetEtueBinning(EtueBin); task->SetEtaBinning(EtaBin); task->SetPhiBinning(PhiBin); task->SetLabelBinning(LabelBin); task->SetPDGBinning(PDGBin); task->SetMomPDGBinning(MomPDGBin); task->SetClustPDGBinning(ClustPDGBin); task->SetDxBinning(DxBin); task->SetDzBinning(DzBin); task->SetDecayBinning(DecayBin); task->SetSmearForClusters(bWhichToSmear); task->SetNeedEmcalGeom(kTRUE); if(bIsMC && bMCNormalization) task->SetIsPythia(kTRUE); TString name(Form("PhotonIsolation_%s_%s", ntracks, nclusters)); cout<<"name of the containers "<<name.Data()<<endl; // tracks to be used for the track matching (already used in TM task, TPC only tracks) AliTrackContainer *trackCont = task->AddTrackContainer("tracks"); if(!trackCont) Printf("Error with TPCOnly!!"); trackCont->SetName("tpconlyMatch"); trackCont->SetTrackFilterType(AliEmcalTrackSelection::kTPCOnlyTracks); // clusters to be used in the analysis already filtered AliClusterContainer *clusterCont = task->AddClusterContainer(nclusters); // tracks to be used in the analysis (Hybrid tracks) AliTrackContainer * tracksForAnalysis = task->AddTrackContainer("tracks"); if(!tracksForAnalysis) Printf("Error with Hybrids!!"); tracksForAnalysis->SetName("filterTracksAna"); tracksForAnalysis->SetFilterHybridTracks(kTRUE); if(!bIsMC){ tracksForAnalysis->SetTrackCutsPeriod(periodstr); tracksForAnalysis->SetDefTrackCutsPeriod(periodstr); } Printf("Name of Tracks for matching: %s \n Name for Tracks for Isolation: %s",trackCont->GetName(),tracksForAnalysis->GetName()); printf("Task for neutral cluster analysis created and configured, pass it to AnalysisManager\n"); // #### Add analysis task manager->AddTask(task); AliAnalysisDataContainer *contHistos = manager->CreateContainer(myContName.Data(), TList::Class(), AliAnalysisManager::kOutputContainer,Form("%s:NeutralClusters",AliAnalysisManager::GetCommonFileName())); AliAnalysisDataContainer *cinput = manager->GetCommonInputContainer(); manager->ConnectInput(task, 0, cinput); manager->ConnectOutput(task, 1, contHistos); return task; } <|endoftext|>
<commit_before>AliAnalysisTaskHFEFlow* ConfigHFE_FLOW_TOFTPC(Bool_t useMC, Int_t tpcCls, Double_t tpcClsr,Int_t tpcClspid, Double_t tpcsharedfraction, Int_t itsCls, Double_t chi2peritscl, Int_t pixellayer, Double_t dcaxy, Double_t dcaz, Double_t tofsig, Double_t tpcdedx0, Double_t tpcdedx1, Double_t tpcdedx2, Double_t tpcdedx3, Double_t tpcdedx4, Int_t vzero, Int_t debuglevel) { // // HFE flow task // printf("Summary settings flow task\n"); printf("TPC number of tracking clusters %d\n",tpcCls); printf("TPC ratio clusters %f\n",tpcClsr*0.01); printf("TPC number of pid clusters %d\n",tpcClspid); printf("Maximal fraction of TPC shared cluster %f\n",tpcsharedfraction*0.01); printf("ITS number of clusters %d\n",itsCls); printf("Maximal chi2 per ITS cluster %f\n",chi2peritscl); printf("Requirement on the pixel layer %d\n",pixellayer); printf("dcaxy %f\n",dcaxy*0.01); printf("dcaz %f\n",dcaz*0.01); printf("TOF sigma %f\n",tofsig*0.1); printf("TPC min sigma cut 0: %f\n",tpcdedx0*0.01); printf("TPC min sigma cut 1: %f\n",tpcdedx1*0.01); printf("TPC min sigma cut 2: %f\n",tpcdedx2*0.01); printf("TPC min sigma cut 3: %f\n",tpcdedx3*0.01); printf("TPC min sigma cut 4: %f\n",tpcdedx4*0.01); printf("VZERO event plane %d\n",vzero); printf("Debug level %d\n",debuglevel); // Cut HFE AliHFEcuts *hfecuts = new AliHFEcuts("hfeCuts","HFE Standard Cuts"); hfecuts->CreateStandardCuts(); hfecuts->SetMinNClustersTPC(tpcCls); hfecuts->SetMinNClustersTPCPID(tpcClspid); hfecuts->SetMinRatioTPCclusters(tpcClsr*0.01); hfecuts->SetTPCmodes(AliHFEextraCuts::kFound, AliHFEextraCuts::kFoundOverFindable); hfecuts->SetFractionOfSharedTPCClusters(tpcsharedfraction*0.01); hfecuts->SetMinNClustersITS(itsCls); hfecuts->SetCutITSpixel(pixellayer); hfecuts->SetCheckITSLayerStatus(kFALSE); hfecuts->SetMaxImpactParam(dcaxy*0.01,dcaz*0.01); //hfecuts->UnsetVertexRequirement(); hfecuts->SetVertexRange(10.); hfecuts->SetTOFPIDStep(kTRUE); // Name TString appendix(TString::Format("TPC%dTPCr%dTPCpid%dTPCShared%dITScl%dChi2perITS%dPixelLayer%dDCAr%dz%dTOFsig%dTPCmindedx0%dTPCmindedx1%dTPCmindedx2%dTPCmindedx3%dTPCmindedx4%dVZERO%dDebugLevel%decorr%d",tpcCls,(Int_t)tpcClsr,tpcClspid,(Int_t) tpcsharedfraction,itsCls,(Int_t) chi2peritscl,(Int_t) pixellayer,(Int_t)dcaxy,(Int_t)dcaz,(Int_t)tofsig,(Int_t)tpcdedx0,(Int_t)tpcdedx1,(Int_t)tpcdedx2,(Int_t)tpcdedx3,(Int_t)tpcdedx4,vzero,debuglevel,(Int_t)withetacorrection)); printf("appendix %s\n", appendix.Data()); // The task AliAnalysisTaskHFEFlow *task = new AliAnalysisTaskHFEFlow(Form("HFEFlowtask_%s", appendix.Data())); task->SelectCollisionCandidates(AliVEvent::kMB | AliVEvent::kCentral | AliVEvent::kSemiCentral); task->SetDebugLevel(1); task->GetPIDQAManager()->SetHighResolutionHistos(); task->SetHFECuts(hfecuts); if(useMC) { task->SetMCPID(kTRUE); //task->SetUseMCReactionPlane(kTRUE); task->SetAfterBurnerOn(kTRUE); task->SetV1V2V3V4V5(0.0,0.2,0.0,0.0,0.0); } if(vzero>=1) task->SetVZEROEventPlane(kTRUE); if(vzero==2) task->SetVZEROEventPlaneA(kTRUE); if(vzero==3) task->SetVZEROEventPlaneC(kTRUE); task->SetDebugLevel(debuglevel); // Define PID AliHFEpid *pid = task->GetPID(); if(useMC) pid->SetHasMCData(kTRUE); pid->AddDetector("TOF", 0); pid->AddDetector("TPC", 1); TString datatype=gSystem->Getenv("CONFIG_FILE"); if(!useMC) { Double_t params_centr_0_5[1]; Double_t params_centr_5_10[1]; Double_t params_centr_10_20[1]; Double_t params_centr_20_30[1]; Double_t params_centr_per[1]; params_centr_0_5[0]=tpcdedx0*0.01; // cut tuned for 0-10% params_centr_5_10[0]=tpcdedx1*0.01; // cut tuned for 0-10% params_centr_10_20[0]=tpcdedx2*0.01; params_centr_20_30[0]=tpcdedx3*0.01; params_centr_per[0]=tpcdedx4*0.01; char *cutmodel; cutmodel="pol0"; for(Int_t a=0;a<11;a++) { if(a>3) pid->ConfigureTPCcentralityCut(a,cutmodel,params_centr_per,3.0); if(a==0) pid->ConfigureTPCcentralityCut(a,cutmodel,params_centr_0_5,3.0); // 0-5% if(a==1) pid->ConfigureTPCcentralityCut(a,cutmodel,params_centr_5_10,3.0); // 5-10% if(a==2) pid->ConfigureTPCcentralityCut(a,cutmodel,params_centr_10_20,3.0); // 10-20% if(a==3) pid->ConfigureTPCcentralityCut(a,cutmodel,params_centr_20_30,3.0); // 20-30% } } pid->ConfigureTOF(tofsig*0.1); printf("*************************************\n"); printf("Configuring standard Task:\n"); task->Print(); pid->PrintStatus(); printf("*************************************\n"); return task; } <commit_msg>Fix of the config<commit_after>AliAnalysisTaskHFEFlow* ConfigHFE_FLOW_TOFTPC(Bool_t useMC, Int_t tpcCls, Double_t tpcClsr,Int_t tpcClspid, Double_t tpcsharedfraction, Int_t itsCls, Double_t chi2peritscl, Int_t pixellayer, Double_t dcaxy, Double_t dcaz, Double_t tofsig, Double_t tpcdedx0, Double_t tpcdedx1, Double_t tpcdedx2, Double_t tpcdedx3, Double_t tpcdedx4, Int_t vzero, Int_t debuglevel) { // // HFE flow task // printf("Summary settings flow task\n"); printf("TPC number of tracking clusters %d\n",tpcCls); printf("TPC ratio clusters %f\n",tpcClsr*0.01); printf("TPC number of pid clusters %d\n",tpcClspid); printf("Maximal fraction of TPC shared cluster %f\n",tpcsharedfraction*0.01); printf("ITS number of clusters %d\n",itsCls); printf("Maximal chi2 per ITS cluster %f\n",chi2peritscl); printf("Requirement on the pixel layer %d\n",pixellayer); printf("dcaxy %f\n",dcaxy*0.01); printf("dcaz %f\n",dcaz*0.01); printf("TOF sigma %f\n",tofsig*0.1); printf("TPC min sigma cut 0: %f\n",tpcdedx0*0.01); printf("TPC min sigma cut 1: %f\n",tpcdedx1*0.01); printf("TPC min sigma cut 2: %f\n",tpcdedx2*0.01); printf("TPC min sigma cut 3: %f\n",tpcdedx3*0.01); printf("TPC min sigma cut 4: %f\n",tpcdedx4*0.01); printf("VZERO event plane %d\n",vzero); printf("Debug level %d\n",debuglevel); // Cut HFE AliHFEcuts *hfecuts = new AliHFEcuts("hfeCuts","HFE Standard Cuts"); hfecuts->CreateStandardCuts(); hfecuts->SetMinNClustersTPC(tpcCls); hfecuts->SetMinNClustersTPCPID(tpcClspid); hfecuts->SetMinRatioTPCclusters(tpcClsr*0.01); hfecuts->SetTPCmodes(AliHFEextraCuts::kFound, AliHFEextraCuts::kFoundOverFindable); hfecuts->SetFractionOfSharedTPCClusters(tpcsharedfraction*0.01); hfecuts->SetMinNClustersITS(itsCls); hfecuts->SetCutITSpixel(pixellayer); hfecuts->SetCheckITSLayerStatus(kFALSE); hfecuts->SetMaxImpactParam(dcaxy*0.01,dcaz*0.01); //hfecuts->UnsetVertexRequirement(); hfecuts->SetVertexRange(10.); hfecuts->SetTOFPIDStep(kTRUE); // Name TString appendix(TString::Format("TPC%dTPCr%dTPCpid%dTPCShared%dITScl%dChi2perITS%dPixelLayer%dDCAr%dz%dTOFsig%dTPCmindedx0%dTPCmindedx1%dTPCmindedx2%dTPCmindedx3%dTPCmindedx4%dVZERO%dDebugLevel%d",tpcCls,(Int_t)tpcClsr,tpcClspid,(Int_t) tpcsharedfraction,itsCls,(Int_t) chi2peritscl,(Int_t) pixellayer,(Int_t)dcaxy,(Int_t)dcaz,(Int_t)tofsig,(Int_t)tpcdedx0,(Int_t)tpcdedx1,(Int_t)tpcdedx2,(Int_t)tpcdedx3,(Int_t)tpcdedx4,vzero,debuglevel)); printf("appendix %s\n", appendix.Data()); // The task AliAnalysisTaskHFEFlow *task = new AliAnalysisTaskHFEFlow(Form("HFEFlowtask_%s", appendix.Data())); task->SelectCollisionCandidates(AliVEvent::kMB | AliVEvent::kCentral | AliVEvent::kSemiCentral); task->SetDebugLevel(1); task->GetPIDQAManager()->SetHighResolutionHistos(); task->SetHFECuts(hfecuts); if(useMC) { task->SetMCPID(kTRUE); //task->SetUseMCReactionPlane(kTRUE); task->SetAfterBurnerOn(kTRUE); task->SetV1V2V3V4V5(0.0,0.2,0.0,0.0,0.0); } if(vzero>=1) task->SetVZEROEventPlane(kTRUE); if(vzero==2) task->SetVZEROEventPlaneA(kTRUE); if(vzero==3) task->SetVZEROEventPlaneC(kTRUE); task->SetDebugLevel(debuglevel); // Define PID AliHFEpid *pid = task->GetPID(); if(useMC) pid->SetHasMCData(kTRUE); pid->AddDetector("TOF", 0); pid->AddDetector("TPC", 1); TString datatype=gSystem->Getenv("CONFIG_FILE"); if(!useMC) { Double_t params_centr_0_5[1]; Double_t params_centr_5_10[1]; Double_t params_centr_10_20[1]; Double_t params_centr_20_30[1]; Double_t params_centr_per[1]; params_centr_0_5[0]=tpcdedx0*0.01; // cut tuned for 0-10% params_centr_5_10[0]=tpcdedx1*0.01; // cut tuned for 0-10% params_centr_10_20[0]=tpcdedx2*0.01; params_centr_20_30[0]=tpcdedx3*0.01; params_centr_per[0]=tpcdedx4*0.01; char *cutmodel; cutmodel="pol0"; for(Int_t a=0;a<11;a++) { if(a>3) pid->ConfigureTPCcentralityCut(a,cutmodel,params_centr_per,3.0); if(a==0) pid->ConfigureTPCcentralityCut(a,cutmodel,params_centr_0_5,3.0); // 0-5% if(a==1) pid->ConfigureTPCcentralityCut(a,cutmodel,params_centr_5_10,3.0); // 5-10% if(a==2) pid->ConfigureTPCcentralityCut(a,cutmodel,params_centr_10_20,3.0); // 10-20% if(a==3) pid->ConfigureTPCcentralityCut(a,cutmodel,params_centr_20_30,3.0); // 20-30% } } pid->ConfigureTOF(tofsig*0.1); printf("*************************************\n"); printf("Configuring standard Task:\n"); task->Print(); pid->PrintStatus(); printf("*************************************\n"); return task; } <|endoftext|>
<commit_before>/* * This source file is part of libRocket, the HTML/CSS Interface Middleware * * For the latest information, see http://www.librocket.com * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ #pragma once #include "LibRocketEventManagerSystem.h" #include <Rocket/Core/Context.h> #include <Rocket/Core/ElementDocument.h> #include <Rocket/Core/ElementUtilities.h> #include "EventHandler.h" #include "EventInstancer.h" #include <map> #include <Globals.h> #include <ToString.h> #include <DebugUtil.h> #include "libRocketBackendSystem.h" #include "ClientConnectToServerSystem.h" #include "GameState.h" #include <TcpClient.h> #include <Packet.h> #include "PacketType.h" #include "ClientStateSystem.h" #include "ChangeStatePacket.h" #include "SoundComponent.h" #include "DisconnectPacket.h" #include "ClientPacketHandlerSystem.h" LibRocketEventManagerSystem::LibRocketEventManagerSystem(TcpClient* p_client) : EntitySystem(SystemType::LibRocketEventManagerSystem, 1, ComponentType::GameState) { m_context = NULL; wantsToExit = false; m_eventHandler = NULL; m_currentDocId = ""; m_client = p_client; } LibRocketEventManagerSystem::~LibRocketEventManagerSystem() { shutdown(); } void LibRocketEventManagerSystem::initialize() { m_stateSystem = static_cast<ClientStateSystem*>(m_world->getSystem( SystemType::ClientStateSystem)); auto rocketBackend = static_cast<LibRocketBackendSystem*>( m_world->getSystem(SystemType::LibRocketBackendSystem)); m_context = rocketBackend->getContext(); EventInstancer* eventInstancer = new EventInstancer(this); Rocket::Core::Factory::RegisterEventListenerInstancer(eventInstancer); eventInstancer->RemoveReference(); m_menuEntity = m_world->createEntity(); SoundComponent* soundComp = new SoundComponent(); AudioHeader* header = new AudioHeader(AudioHeader::AMBIENT,"MenuOk"); header->file = "Mine_Blip_v2.wav"; header->volume = 0.3f; header->path = TESTSOUNDEFFECTPATH; soundComp->addAudioHeader(header); m_menuEntity->addComponent(soundComp); m_world->addEntity(m_menuEntity); } // Releases all event handlers registered with the manager. void LibRocketEventManagerSystem::shutdown() { m_eventHandlers.clear(); m_eventHandler = NULL; } void LibRocketEventManagerSystem::registerEventHandler( EventHandler* p_handler ) { registerEventHandler(p_handler->getName().c_str(), p_handler); } // Registers a new event handler with the manager. void LibRocketEventManagerSystem::registerEventHandler(const Rocket::Core::String& p_handlerName, EventHandler* p_handler) { p_handler->connectToManager(this); // Release any handler bound under the same name. EventHandlerMap::iterator iterator = m_eventHandlers.find(p_handlerName); if (iterator != m_eventHandlers.end()) { //delete (*iterator).second; DEBUGWARNING((( toString("LibRocketEventManagerSystem::registerEventHandler\nAttempting to register EventHandler[") + toString(p_handlerName.CString()) + toString("] which has already been registred in the EventManager.")).c_str())); } m_eventHandlers[p_handlerName] = p_handler; } EventHandler* LibRocketEventManagerSystem::unregisterEventHandler( const Rocket::Core::String& p_handlerName ) { EventHandlerMap::iterator iterator = m_eventHandlers.find(p_handlerName); EventHandler* handler = NULL; if (iterator != m_eventHandlers.end()) { handler = (*iterator).second; handler->connectToManager(NULL); m_eventHandlers[p_handlerName] = NULL; } return handler; } void LibRocketEventManagerSystem::clearDocumentStack() { while (!m_docIdStack.empty()) { auto document = m_context->GetDocument(m_docIdStack.top()); m_docIdStack.pop(); if (document->IsVisible()) { document->Show(Rocket::Core::ElementDocument::NONE); document->Hide(); } } m_currentDocId = ""; } // Processes an event coming through from Rocket. void LibRocketEventManagerSystem::processEvent(Rocket::Core::Event& p_event, const Rocket::Core::String& p_value) { Rocket::Core::StringList commands; Rocket::Core::StringUtilities::ExpandString(commands, p_value, ';'); for (size_t i = 0; i < commands.size(); ++i) { // Check for a generic 'load', 'exit' or 'modal' command. Rocket::Core::StringList values; Rocket::Core::StringUtilities::ExpandString(values, commands[i], ' '); if (values.empty()) return; auto ownerDocument = p_event.GetTargetElement()->GetOwnerDocument(); if (values[0] == "modal") { // if (!ownerDocument->IsModal() && m_currentDocId == ownerDocument->GetId()) // ownerDocument->Show(Rocket::Core::ElementDocument::MODAL); } else if (values[0] == "goto" && values.size() > 1) { playConfirmSound(); // Clear the stack from windows that are on top of the triggering one. clearStackUntilFoundDocId(ownerDocument->GetId()); // If goto previous is specified, then hide this window, and open the // previous one saved on the stack if (values[1] == "previous") { // Pop current document id from the stack. m_docIdStack.pop(); // Top and pop next document id. On loadWindow, it will be added again. // That's not pretty/efficient, but it isn't a problem either. // Alex Rocket::Core::String window = m_docIdStack.top(); m_docIdStack.pop(); if (loadWindow(window)) ownerDocument->Hide(); } // Load the window, and if successful hide the old window. else if (loadWindow(values[1])) { ownerDocument->Hide(); } } else if (values[0] == "open" && values.size() > 1) { playConfirmSound(); // Opens a window and pushes it to the stack, without hiding the parent window. // Clear other open windows on top. clearStackUntilFoundDocId(ownerDocument->GetId()); loadWindow(values[1]); ownerDocument->Show(Rocket::Core::ElementDocument::NONE); } else if (values[0] == "clearStack"){ clearDocumentStack(); } else if (values[0] == "exit") { wantsToExit = true; } else if (values[0] == "connectToServer") { // "server_host" is the name attribute specified in the input element in the rml file. // "localhost" simply is provided as a default value, if the host isn't set. This could be left as "" as well. string server_address = p_event.GetParameter<Rocket::Core::String> ("server_host", "localhost").CString(); string server_port = p_event.GetParameter<Rocket::Core::String> ("server_port", "1337").CString(); string playerName = p_event.GetParameter<Rocket::Core::String> ("player_name", "NotFound").CString(); m_client->setPlayerName(playerName); auto sys = static_cast<ClientConnectToServerSystem*>( m_world->getSystem(SystemType::ClientConnectoToServerSystem)); sys->setAddressAndConnect(server_address, server_port); } else if(values[0] == "start_game") { ChangeStatePacket letsRollPacket; letsRollPacket.m_gameState = GameStates::INITGAME; m_client->sendPacket(letsRollPacket.pack()); } else if(values[0] == "host_server"){ m_world->requestToHostServer(); string server_port = p_event.GetParameter<Rocket::Core::String> ("server_port", "1337").CString(); string playerName = p_event.GetParameter<Rocket::Core::String> ("player_name", "NotFound").CString(); m_client->setPlayerName(playerName); auto sys = static_cast<ClientConnectToServerSystem*>( m_world->getSystem(SystemType::ClientConnectoToServerSystem)); sys->setAddressAndConnect("127.0.0.1", server_port); } else if(values[0] == "leave_server"){ DisconnectPacket dcPacket; dcPacket.playerID = m_client->getPlayerID(); dcPacket.clientNetworkIdentity = m_client->getId(); m_client->sendPacket(dcPacket.pack()); } else if (values[0] == "reset_connection") { auto sys = static_cast<ClientPacketHandlerSystem*>( m_world->getSystem(SystemType::ClientPacketHandlerSystem)); sys->resetFromDisconnect(); } else if(values[0] == "play_confirm"){ playConfirmSound(); } } } void LibRocketEventManagerSystem::processEntities( const vector<Entity*>& p_entities ) { if (wantsToExit){ m_world->requestToShutDown(); } } void LibRocketEventManagerSystem::playConfirmSound() { auto soundComp = static_cast<SoundComponent*> (m_menuEntity->getComponent(ComponentType::SoundComponent)); soundComp->getSoundHeaderByName(AudioHeader::AMBIENT,"MenuOk")-> queuedPlayingState = AudioHeader::PLAY; } void LibRocketEventManagerSystem::playBackSound() { } // Loads a window and binds the event handler for it. bool LibRocketEventManagerSystem::loadWindow(const Rocket::Core::String& p_windowName) { // Set the event handler for the new screen, if one has been registered. EventHandler* old_event_handler = m_eventHandler; EventHandlerMap::iterator iterator = m_eventHandlers.find(p_windowName); if (iterator != m_eventHandlers.end()) m_eventHandler = (*iterator).second; else m_eventHandler = NULL; auto document = m_context->GetDocument(p_windowName); if (document == NULL) { DEBUGWARNING((( toString("LibRocketEventManagerSystem::loadWindow\nNo document with the body id\"") + toString(p_windowName.CString()) + toString("\" has been loaded.")).c_str())); m_eventHandler = old_event_handler; return false; } // Add this document to the stack! m_currentDocId = p_windowName; m_docIdStack.push(p_windowName); document->Show(); document->PullToFront(); // Remove the caller's reference. //document->RemoveReference(); return true; } void LibRocketEventManagerSystem::clearStackUntilFoundDocId( const Rocket::Core::String& p_docId ) { if(m_docIdStack.size()){ while (m_docIdStack.top() != p_docId) { auto document = m_context->GetDocument(m_docIdStack.top()); m_docIdStack.pop(); if (document->IsVisible()) { document->Show(Rocket::Core::ElementDocument::NONE); document->Hide(); } } } }<commit_msg>Dicsonnect popup should now vanish when pressing the button!<commit_after>/* * This source file is part of libRocket, the HTML/CSS Interface Middleware * * For the latest information, see http://www.librocket.com * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ #pragma once #include "LibRocketEventManagerSystem.h" #include <Rocket/Core/Context.h> #include <Rocket/Core/ElementDocument.h> #include <Rocket/Core/ElementUtilities.h> #include "EventHandler.h" #include "EventInstancer.h" #include <map> #include <Globals.h> #include <ToString.h> #include <DebugUtil.h> #include "libRocketBackendSystem.h" #include "ClientConnectToServerSystem.h" #include "GameState.h" #include <TcpClient.h> #include <Packet.h> #include "PacketType.h" #include "ClientStateSystem.h" #include "ChangeStatePacket.h" #include "SoundComponent.h" #include "DisconnectPacket.h" #include "ClientPacketHandlerSystem.h" LibRocketEventManagerSystem::LibRocketEventManagerSystem(TcpClient* p_client) : EntitySystem(SystemType::LibRocketEventManagerSystem, 1, ComponentType::GameState) { m_context = NULL; wantsToExit = false; m_eventHandler = NULL; m_currentDocId = ""; m_client = p_client; } LibRocketEventManagerSystem::~LibRocketEventManagerSystem() { shutdown(); } void LibRocketEventManagerSystem::initialize() { m_stateSystem = static_cast<ClientStateSystem*>(m_world->getSystem( SystemType::ClientStateSystem)); auto rocketBackend = static_cast<LibRocketBackendSystem*>( m_world->getSystem(SystemType::LibRocketBackendSystem)); m_context = rocketBackend->getContext(); EventInstancer* eventInstancer = new EventInstancer(this); Rocket::Core::Factory::RegisterEventListenerInstancer(eventInstancer); eventInstancer->RemoveReference(); m_menuEntity = m_world->createEntity(); SoundComponent* soundComp = new SoundComponent(); AudioHeader* header = new AudioHeader(AudioHeader::AMBIENT,"MenuOk"); header->file = "Mine_Blip_v2.wav"; header->volume = 0.3f; header->path = TESTSOUNDEFFECTPATH; soundComp->addAudioHeader(header); m_menuEntity->addComponent(soundComp); m_world->addEntity(m_menuEntity); } // Releases all event handlers registered with the manager. void LibRocketEventManagerSystem::shutdown() { m_eventHandlers.clear(); m_eventHandler = NULL; } void LibRocketEventManagerSystem::registerEventHandler( EventHandler* p_handler ) { registerEventHandler(p_handler->getName().c_str(), p_handler); } // Registers a new event handler with the manager. void LibRocketEventManagerSystem::registerEventHandler(const Rocket::Core::String& p_handlerName, EventHandler* p_handler) { p_handler->connectToManager(this); // Release any handler bound under the same name. EventHandlerMap::iterator iterator = m_eventHandlers.find(p_handlerName); if (iterator != m_eventHandlers.end()) { //delete (*iterator).second; DEBUGWARNING((( toString("LibRocketEventManagerSystem::registerEventHandler\nAttempting to register EventHandler[") + toString(p_handlerName.CString()) + toString("] which has already been registred in the EventManager.")).c_str())); } m_eventHandlers[p_handlerName] = p_handler; } EventHandler* LibRocketEventManagerSystem::unregisterEventHandler( const Rocket::Core::String& p_handlerName ) { EventHandlerMap::iterator iterator = m_eventHandlers.find(p_handlerName); EventHandler* handler = NULL; if (iterator != m_eventHandlers.end()) { handler = (*iterator).second; handler->connectToManager(NULL); m_eventHandlers[p_handlerName] = NULL; } return handler; } void LibRocketEventManagerSystem::clearDocumentStack() { while (!m_docIdStack.empty()) { auto document = m_context->GetDocument(m_docIdStack.top()); m_docIdStack.pop(); if (document->IsVisible()) { document->Show(Rocket::Core::ElementDocument::NONE); document->Hide(); } } m_currentDocId = ""; } // Processes an event coming through from Rocket. void LibRocketEventManagerSystem::processEvent(Rocket::Core::Event& p_event, const Rocket::Core::String& p_value) { Rocket::Core::StringList commands; Rocket::Core::StringUtilities::ExpandString(commands, p_value, ';'); for (size_t i = 0; i < commands.size(); ++i) { // Check for a generic 'load', 'exit' or 'modal' command. Rocket::Core::StringList values; Rocket::Core::StringUtilities::ExpandString(values, commands[i], ' '); if (values.empty()) return; auto ownerDocument = p_event.GetTargetElement()->GetOwnerDocument(); if (values[0] == "modal") { // if (!ownerDocument->IsModal() && m_currentDocId == ownerDocument->GetId()) // ownerDocument->Show(Rocket::Core::ElementDocument::MODAL); } else if (values[0] == "goto" && values.size() > 1) { playConfirmSound(); // Clear the stack from windows that are on top of the triggering one. clearStackUntilFoundDocId(ownerDocument->GetId()); // If goto previous is specified, then hide this window, and open the // previous one saved on the stack if (values[1] == "previous") { // Pop current document id from the stack. m_docIdStack.pop(); // Top and pop next document id. On loadWindow, it will be added again. // That's not pretty/efficient, but it isn't a problem either. // Alex Rocket::Core::String window = m_docIdStack.top(); m_docIdStack.pop(); if (loadWindow(window)) ownerDocument->Hide(); } // Load the window, and if successful hide the old window. else if (loadWindow(values[1])) { ownerDocument->Hide(); } } else if (values[0] == "open" && values.size() > 1) { playConfirmSound(); // Opens a window and pushes it to the stack, without hiding the parent window. // Clear other open windows on top. clearStackUntilFoundDocId(ownerDocument->GetId()); loadWindow(values[1]); ownerDocument->Show(Rocket::Core::ElementDocument::NONE); } else if (values[0] == "clearStack"){ clearDocumentStack(); } else if (values[0] == "exit") { wantsToExit = true; } else if (values[0] == "connectToServer") { // "server_host" is the name attribute specified in the input element in the rml file. // "localhost" simply is provided as a default value, if the host isn't set. This could be left as "" as well. string server_address = p_event.GetParameter<Rocket::Core::String> ("server_host", "localhost").CString(); string server_port = p_event.GetParameter<Rocket::Core::String> ("server_port", "1337").CString(); string playerName = p_event.GetParameter<Rocket::Core::String> ("player_name", "NotFound").CString(); m_client->setPlayerName(playerName); auto sys = static_cast<ClientConnectToServerSystem*>( m_world->getSystem(SystemType::ClientConnectoToServerSystem)); sys->setAddressAndConnect(server_address, server_port); } else if(values[0] == "start_game") { ChangeStatePacket letsRollPacket; letsRollPacket.m_gameState = GameStates::INITGAME; m_client->sendPacket(letsRollPacket.pack()); } else if(values[0] == "host_server"){ m_world->requestToHostServer(); string server_port = p_event.GetParameter<Rocket::Core::String> ("server_port", "1337").CString(); string playerName = p_event.GetParameter<Rocket::Core::String> ("player_name", "NotFound").CString(); m_client->setPlayerName(playerName); auto sys = static_cast<ClientConnectToServerSystem*>( m_world->getSystem(SystemType::ClientConnectoToServerSystem)); sys->setAddressAndConnect("127.0.0.1", server_port); } else if(values[0] == "leave_server"){ DisconnectPacket dcPacket; dcPacket.playerID = m_client->getPlayerID(); dcPacket.clientNetworkIdentity = m_client->getId(); m_client->sendPacket(dcPacket.pack()); } else if (values[0] == "reset_connection") { ownerDocument->Show(Rocket::Core::ElementDocument::MODAL); ownerDocument->Hide(); auto sys = static_cast<ClientPacketHandlerSystem*>( m_world->getSystem(SystemType::ClientPacketHandlerSystem)); sys->resetFromDisconnect(); } else if(values[0] == "play_confirm"){ playConfirmSound(); } } } void LibRocketEventManagerSystem::processEntities( const vector<Entity*>& p_entities ) { if (wantsToExit){ m_world->requestToShutDown(); } } void LibRocketEventManagerSystem::playConfirmSound() { auto soundComp = static_cast<SoundComponent*> (m_menuEntity->getComponent(ComponentType::SoundComponent)); soundComp->getSoundHeaderByName(AudioHeader::AMBIENT,"MenuOk")-> queuedPlayingState = AudioHeader::PLAY; } void LibRocketEventManagerSystem::playBackSound() { } // Loads a window and binds the event handler for it. bool LibRocketEventManagerSystem::loadWindow(const Rocket::Core::String& p_windowName) { // Set the event handler for the new screen, if one has been registered. EventHandler* old_event_handler = m_eventHandler; EventHandlerMap::iterator iterator = m_eventHandlers.find(p_windowName); if (iterator != m_eventHandlers.end()) m_eventHandler = (*iterator).second; else m_eventHandler = NULL; auto document = m_context->GetDocument(p_windowName); if (document == NULL) { DEBUGWARNING((( toString("LibRocketEventManagerSystem::loadWindow\nNo document with the body id\"") + toString(p_windowName.CString()) + toString("\" has been loaded.")).c_str())); m_eventHandler = old_event_handler; return false; } // Add this document to the stack! m_currentDocId = p_windowName; m_docIdStack.push(p_windowName); document->Show(); document->PullToFront(); // Remove the caller's reference. //document->RemoveReference(); return true; } void LibRocketEventManagerSystem::clearStackUntilFoundDocId( const Rocket::Core::String& p_docId ) { if(m_docIdStack.size()){ while (m_docIdStack.top() != p_docId) { auto document = m_context->GetDocument(m_docIdStack.top()); m_docIdStack.pop(); if (document->IsVisible()) { document->Show(Rocket::Core::ElementDocument::NONE); document->Hide(); } } } }<|endoftext|>
<commit_before>/****************************************************************************** nomlib - C++11 cross-platform game engine Copyright (c) 2013, 2014 Jeffrey Carpenter <i8degrees@gmail.com> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ******************************************************************************/ #include "nomlib/system/InputMapper/InputStateMapper.hpp" namespace nom { InputStateMapper::InputStateMapper( void ) { // NOM_LOG_TRACE( NOM ); } InputStateMapper::~InputStateMapper( void ) { // NOM_LOG_TRACE( NOM ); } bool InputStateMapper::active( const std::string& key ) const { InputStateMap::const_iterator itr = this->states_.find( key ); // No match found; do nothing. if( itr == this->states_.end() ) { NOM_LOG_ERR( NOM, "Could not check for active state on the specified key: " + key ); return false; } else { return itr->second.active; } } bool InputStateMapper::insert( const std::string& key, const InputActionMapper& map, bool active ) { InputActionState input_state; input_state.active = active; input_state.actions = map.get(); InputStateMapper::Pair p( key, input_state ); auto it = this->states_.insert( p ); // No dice; the insertion failed for some reason! if( it.second == false ) { NOM_LOG_ERR( NOM, "Could not insert state key: " + key ); return false; } return true; } bool InputStateMapper::erase( const std::string& key ) { InputStateMap::const_iterator itr = this->states_.find( key ); // No match found; do nothing. if( itr == this->states_.end() ) { NOM_LOG_ERR( NOM, "Could not remove specified state key: " + key ); return false; } else // Match found; remove the context mapping { this->states_.erase( itr ); return true; } return false; } bool InputStateMapper::activate( const std::string& key ) { InputStateMap::iterator itr = this->states_.find( key ); // No match found; do nothing. if( itr == this->states_.end() ) { NOM_LOG_ERR( NOM, "Could not activate specified state key: " + key ); return false; } else // Match found; set the input mapping as the active context. { itr->second.active = true; return true; } return false; } bool InputStateMapper::disable( const std::string& key ) { InputStateMap::iterator itr = this->states_.find( key ); // No match found; do nothing. if( itr == this->states_.end() ) { NOM_LOG_ERR( NOM, "Could not disable specified state key: " + key ); return false; } else // Match found; disable the requested state { itr->second.active = false; return true; } return false; } void InputStateMapper::disable( void ) { for( auto itr = this->states_.begin(); itr != this->states_.end(); ++itr ) { itr->second.active = false; } } bool InputStateMapper::activate_only( const std::string& key ) { // First, we need to make sure that the requested state even exists before we // flag anything inactive. InputStateMap::iterator it = this->states_.find( key ); if( it == this->states_.end() ) { NOM_LOG_ERR( NOM, "Could not find state key: " + key ); return false; } // Iterate through all of our action-to-states and flag them inactive. for( InputStateMap::iterator itr = this->states_.begin(); itr != this->states_.end(); ++itr ) { itr->second.active = false; } it = this->states_.find( key ); // No match found; do nothing more! if( it == this->states_.end() ) { NOM_LOG_ERR( NOM, "Could not activate only state key: " + key ); return false; } else // Match found; enable the requested state { it->second.active = true; return true; } return false; } void InputStateMapper::clear( void ) { this->states_.clear(); } void InputStateMapper::dump( void ) { for( auto itr = this->states_.begin(); itr != this->states_.end(); ++itr ) { if( itr->second.active == true ) { InputActionMapper::ActionMap& input_map = itr->second.actions; for( InputActionMapper::ActionMap::const_iterator itr = input_map.begin(); itr != input_map.end(); ++itr ) { NOM_DUMP( itr->first ); if ( itr->second != nullptr ) { itr->second->dump(); } else { NOM_LOG_ERR( NOM, "Invalid input mapping state." ); } } } } } void InputStateMapper::on_event( const Event& ev ) { for( auto itr = this->states_.begin(); itr != this->states_.end(); ++itr ) { if( itr->second.active == true ) { InputActionMapper::ActionMap input_map = itr->second.actions; for( InputActionMapper::ActionMap::const_iterator itr = input_map.begin(); itr != input_map.end(); ++itr ) { if( ev.type == SDL_KEYDOWN || ev.type == SDL_KEYUP ) { if( this->on_key_press( *itr->second, ev ) ) { itr->second->operator()( ev ); } } else if( ev.type == SDL_MOUSEBUTTONDOWN || ev.type == SDL_MOUSEBUTTONUP ) { if( this->on_mouse_button( *itr->second, ev ) ) { itr->second->operator()( ev ); } } else if( ev.type == SDL_MOUSEWHEEL || ev.type == SDL_MOUSEWHEEL ) { if( this->on_mouse_wheel( *itr->second, ev ) ) { itr->second->operator()( ev ); } } else if( ev.type == SDL_JOYBUTTONDOWN || ev.type == SDL_JOYBUTTONUP ) { if( this->on_joystick_button( *itr->second, ev ) ) { itr->second->operator()( ev ); } } else if( ev.type == SDL_JOYAXISMOTION ) { if( this->on_joystick_axis( *itr->second, ev ) ) { itr->second->operator()( ev ); } } } // end input_map iteration } // end conditional active input state } } bool InputStateMapper::on_key_press( const InputAction& mapping, const Event& ev ) { Event evt = mapping.event(); if( evt.type != ev.type ) return false; // Handle matching the set keyboard actions to the user's input if( evt.key.sym == ev.key.sym && evt.key.mod == ev.key.mod && evt.key.repeat == ev.key.repeat ) { // Matched return true; } // No match to any mapped action return false; } bool InputStateMapper::on_mouse_button( const InputAction& mapping, const Event& ev ) { Event evt = mapping.event(); if( evt.type != ev.type ) return false; // Successful match is a mouse click that matches both the button used // (left, middle, right, ...) and its number of clicks (single, double, ...) if( evt.mouse.clicks == ev.mouse.clicks && evt.mouse.button == ev.mouse.button ) { // Match return true; } // No match; number of clicks mismatch return false; } bool InputStateMapper::on_mouse_wheel( const InputAction& mapping, const Event& ev ) { Event evt = mapping.event(); // if( mapping.wheel == nullptr ) return false; if( evt.type != ev.type ) return false; // NOTE: X & Y coordinate values depend on the construction of a WheelAction // object. // if( evt.wheel.axis == MouseWheelAction::AXIS_X ) if( evt.wheel.x != MouseWheelAction::null ) { // Left if( evt.wheel.x >= MouseWheelAction::LEFT && ev.wheel.x >= MouseWheelAction::LEFT ) { return true; } // Right if( evt.wheel.x <= MouseWheelAction::RIGHT && ev.wheel.x <= MouseWheelAction::RIGHT ) { return true; } } // else if( evt.wheel.axis == MouseWheelAction::AXIS_Y ) else if( evt.wheel.y != MouseWheelAction::null ) { // Up if( evt.wheel.y >= MouseWheelAction::UP && ev.wheel.y >= MouseWheelAction::UP ) { return true; } // Down if( evt.wheel.y <= MouseWheelAction::DOWN && ev.wheel.y <= MouseWheelAction::DOWN ) { return true; } } // Initialized to an invalid state! NOM_ASSERT( evt.wheel.x == 0 || evt.wheel.y == 0 ); return false; } bool InputStateMapper::on_joystick_button( const InputAction& mapping, const Event& ev ) { Event evt = mapping.event(); // if( mapping.jbutton == nullptr ) return false; if( evt.type != ev.type ) return false; if( evt.jbutton.id != ev.jbutton.id ) return false; if( evt.jbutton.button == ev.jbutton.button ) return true; return false; } // FIXME: Implementation is incomplete! bool InputStateMapper::on_joystick_axis( const InputAction& mapping, const Event& ev ) { Event evt = mapping.event(); // if( mapping.jaxis == nullptr ) return false; if( evt.type != ev.type ) return false; if( evt.jaxis.id != ev.jaxis.id ) return false; if( evt.jaxis.axis != ev.jaxis.axis ) return false; // Within dead-zone tolerance if( ( ev.jaxis.value < -3200 ) || ( ev.jaxis.value > 3200 ) ) { // Up-down axis (Sony PS3 game controller) if( evt.jaxis.axis == 0 ) { // Up if( evt.jaxis.value < 0 ) return true; // Down if( evt.jaxis.value > 0 ) return true; } // Left-right axis (Sony PS3 game controller) if( evt.jaxis.axis == 1 ) { // Left if( evt.jaxis.value < 0 ) return true; // Right if( evt.jaxis.value > 0 ) return true; } } return false; } } // namespace nom <commit_msg>InputStateMapper: Ignore key repeat logic unless non-zero (explicit)<commit_after>/****************************************************************************** nomlib - C++11 cross-platform game engine Copyright (c) 2013, 2014 Jeffrey Carpenter <i8degrees@gmail.com> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ******************************************************************************/ #include "nomlib/system/InputMapper/InputStateMapper.hpp" namespace nom { InputStateMapper::InputStateMapper( void ) { // NOM_LOG_TRACE( NOM ); } InputStateMapper::~InputStateMapper( void ) { // NOM_LOG_TRACE( NOM ); } bool InputStateMapper::active( const std::string& key ) const { InputStateMap::const_iterator itr = this->states_.find( key ); // No match found; do nothing. if( itr == this->states_.end() ) { NOM_LOG_ERR( NOM, "Could not check for active state on the specified key: " + key ); return false; } else { return itr->second.active; } } bool InputStateMapper::insert( const std::string& key, const InputActionMapper& map, bool active ) { InputActionState input_state; input_state.active = active; input_state.actions = map.get(); InputStateMapper::Pair p( key, input_state ); auto it = this->states_.insert( p ); // No dice; the insertion failed for some reason! if( it.second == false ) { NOM_LOG_ERR( NOM, "Could not insert state key: " + key ); return false; } return true; } bool InputStateMapper::erase( const std::string& key ) { InputStateMap::const_iterator itr = this->states_.find( key ); // No match found; do nothing. if( itr == this->states_.end() ) { NOM_LOG_ERR( NOM, "Could not remove specified state key: " + key ); return false; } else // Match found; remove the context mapping { this->states_.erase( itr ); return true; } return false; } bool InputStateMapper::activate( const std::string& key ) { InputStateMap::iterator itr = this->states_.find( key ); // No match found; do nothing. if( itr == this->states_.end() ) { NOM_LOG_ERR( NOM, "Could not activate specified state key: " + key ); return false; } else // Match found; set the input mapping as the active context. { itr->second.active = true; return true; } return false; } bool InputStateMapper::disable( const std::string& key ) { InputStateMap::iterator itr = this->states_.find( key ); // No match found; do nothing. if( itr == this->states_.end() ) { NOM_LOG_ERR( NOM, "Could not disable specified state key: " + key ); return false; } else // Match found; disable the requested state { itr->second.active = false; return true; } return false; } void InputStateMapper::disable( void ) { for( auto itr = this->states_.begin(); itr != this->states_.end(); ++itr ) { itr->second.active = false; } } bool InputStateMapper::activate_only( const std::string& key ) { // First, we need to make sure that the requested state even exists before we // flag anything inactive. InputStateMap::iterator it = this->states_.find( key ); if( it == this->states_.end() ) { NOM_LOG_ERR( NOM, "Could not find state key: " + key ); return false; } // Iterate through all of our action-to-states and flag them inactive. for( InputStateMap::iterator itr = this->states_.begin(); itr != this->states_.end(); ++itr ) { itr->second.active = false; } it = this->states_.find( key ); // No match found; do nothing more! if( it == this->states_.end() ) { NOM_LOG_ERR( NOM, "Could not activate only state key: " + key ); return false; } else // Match found; enable the requested state { it->second.active = true; return true; } return false; } void InputStateMapper::clear( void ) { this->states_.clear(); } void InputStateMapper::dump( void ) { for( auto itr = this->states_.begin(); itr != this->states_.end(); ++itr ) { if( itr->second.active == true ) { InputActionMapper::ActionMap& input_map = itr->second.actions; for( InputActionMapper::ActionMap::const_iterator itr = input_map.begin(); itr != input_map.end(); ++itr ) { NOM_DUMP( itr->first ); if ( itr->second != nullptr ) { itr->second->dump(); } else { NOM_LOG_ERR( NOM, "Invalid input mapping state." ); } } } } } void InputStateMapper::on_event( const Event& ev ) { for( auto itr = this->states_.begin(); itr != this->states_.end(); ++itr ) { if( itr->second.active == true ) { InputActionMapper::ActionMap input_map = itr->second.actions; for( InputActionMapper::ActionMap::const_iterator itr = input_map.begin(); itr != input_map.end(); ++itr ) { if( ev.type == SDL_KEYDOWN || ev.type == SDL_KEYUP ) { if( this->on_key_press( *itr->second, ev ) ) { itr->second->operator()( ev ); } } else if( ev.type == SDL_MOUSEBUTTONDOWN || ev.type == SDL_MOUSEBUTTONUP ) { if( this->on_mouse_button( *itr->second, ev ) ) { itr->second->operator()( ev ); } } else if( ev.type == SDL_MOUSEWHEEL || ev.type == SDL_MOUSEWHEEL ) { if( this->on_mouse_wheel( *itr->second, ev ) ) { itr->second->operator()( ev ); } } else if( ev.type == SDL_JOYBUTTONDOWN || ev.type == SDL_JOYBUTTONUP ) { if( this->on_joystick_button( *itr->second, ev ) ) { itr->second->operator()( ev ); } } else if( ev.type == SDL_JOYAXISMOTION ) { if( this->on_joystick_axis( *itr->second, ev ) ) { itr->second->operator()( ev ); } } } // end input_map iteration } // end conditional active input state } } bool InputStateMapper::on_key_press( const InputAction& mapping, const Event& ev ) { Event evt = mapping.event(); if( evt.type != ev.type ) return false; // Handle a keyboard action with repeat; only trigger if the event is a // repeating one if( evt.key.repeat != 0 ) { if( evt.key.sym == ev.key.sym && evt.key.mod == ev.key.mod && evt.key.repeat == ev.key.repeat ) { // Matched return true; } } else // Handle normal keyboard action; repeating makes no difference to us { if( evt.key.sym == ev.key.sym && evt.key.mod == ev.key.mod ) { // Matched return true; } } // No match to any mapped action return false; } bool InputStateMapper::on_mouse_button( const InputAction& mapping, const Event& ev ) { Event evt = mapping.event(); if( evt.type != ev.type ) return false; // Successful match is a mouse click that matches both the button used // (left, middle, right, ...) and its number of clicks (single, double, ...) if( evt.mouse.clicks == ev.mouse.clicks && evt.mouse.button == ev.mouse.button ) { // Match return true; } // No match; number of clicks mismatch return false; } bool InputStateMapper::on_mouse_wheel( const InputAction& mapping, const Event& ev ) { Event evt = mapping.event(); // if( mapping.wheel == nullptr ) return false; if( evt.type != ev.type ) return false; // NOTE: X & Y coordinate values depend on the construction of a WheelAction // object. // if( evt.wheel.axis == MouseWheelAction::AXIS_X ) if( evt.wheel.x != MouseWheelAction::null ) { // Left if( evt.wheel.x >= MouseWheelAction::LEFT && ev.wheel.x >= MouseWheelAction::LEFT ) { return true; } // Right if( evt.wheel.x <= MouseWheelAction::RIGHT && ev.wheel.x <= MouseWheelAction::RIGHT ) { return true; } } // else if( evt.wheel.axis == MouseWheelAction::AXIS_Y ) else if( evt.wheel.y != MouseWheelAction::null ) { // Up if( evt.wheel.y >= MouseWheelAction::UP && ev.wheel.y >= MouseWheelAction::UP ) { return true; } // Down if( evt.wheel.y <= MouseWheelAction::DOWN && ev.wheel.y <= MouseWheelAction::DOWN ) { return true; } } // Initialized to an invalid state! NOM_ASSERT( evt.wheel.x == 0 || evt.wheel.y == 0 ); return false; } bool InputStateMapper::on_joystick_button( const InputAction& mapping, const Event& ev ) { Event evt = mapping.event(); // if( mapping.jbutton == nullptr ) return false; if( evt.type != ev.type ) return false; if( evt.jbutton.id != ev.jbutton.id ) return false; if( evt.jbutton.button == ev.jbutton.button ) return true; return false; } // FIXME: Implementation is incomplete! bool InputStateMapper::on_joystick_axis( const InputAction& mapping, const Event& ev ) { Event evt = mapping.event(); // if( mapping.jaxis == nullptr ) return false; if( evt.type != ev.type ) return false; if( evt.jaxis.id != ev.jaxis.id ) return false; if( evt.jaxis.axis != ev.jaxis.axis ) return false; // Within dead-zone tolerance if( ( ev.jaxis.value < -3200 ) || ( ev.jaxis.value > 3200 ) ) { // Up-down axis (Sony PS3 game controller) if( evt.jaxis.axis == 0 ) { // Up if( evt.jaxis.value < 0 ) return true; // Down if( evt.jaxis.value > 0 ) return true; } // Left-right axis (Sony PS3 game controller) if( evt.jaxis.axis == 1 ) { // Left if( evt.jaxis.value < 0 ) return true; // Right if( evt.jaxis.value > 0 ) return true; } } return false; } } // namespace nom <|endoftext|>
<commit_before>// Copyright 2017 Global Phasing Ltd. // // This program analyses PDB or mmCIF files, printing similar things // as CCP4 RWCONTENTS: weight, Matthews coefficient, etc. #include <cassert> #include <cstdio> #include <gemmi/symmetry.hpp> #include <gemmi/resinfo.hpp> #include <gemmi/calculate.hpp> #include <gemmi/gzread.hpp> #include <gemmi/polyheur.hpp> // for setup_entities, calculate_sequence_weight #include "histogram.h" // for print_histogram #define GEMMI_PROG contents #include "options.h" using namespace gemmi; using std::printf; enum OptionIndex { Dihedrals=4, Bfactors, NoContentInfo }; static const option::Descriptor Usage[] = { { NoOp, 0, "", "", Arg::None, "Usage:\n " EXE_NAME " [options] INPUT[...]" "\nAnalyses content of a PDB or mmCIF."}, CommonUsage[Help], CommonUsage[Version], CommonUsage[Verbose], { Bfactors, 0, "b", "", Arg::None, " -b \tPrint statistics of isotropic ADPs (B-factors)." }, { Dihedrals, 0, "", "dihedrals", Arg::None, " --dihedrals \tPrint peptide dihedral angles." }, { NoContentInfo, 0, "n", "", Arg::None, " -n \tDo not print content (for use with other options)." }, { 0, 0, 0, 0, 0, 0 } }; static void print_atoms_on_special_positions(const Structure& st) { printf(" Atoms on special positions:"); bool found = false; for (const Chain& chain : st.first_model().chains) for (const Residue& res : chain.residues) for (const Atom& atom : res.atoms) if (int n = st.cell.is_special_position(atom.pos)) { found = true; SymImage im = st.cell.find_nearest_image(atom.pos, atom.pos, Asu::Different); printf("\n %s %4d%c %3s %-3s %c fold=%d occ=%.2f d_image=%.4f", chain.name.c_str(), *res.seqid.num, res.seqid.icode, res.name.c_str(), atom.name.c_str(), (atom.altloc | 0x20), n+1, atom.occ, im.dist()); } if (!found) printf(" none"); printf("\n"); } static void print_content_info(const Structure& st, bool /*verbose*/) { printf(" Spacegroup %s\n", st.spacegroup_hm.c_str()); int order = 1; const SpaceGroup* sg = st.find_spacegroup(); if (sg) { order = sg->operations().order(); printf(" Group no. %d with %d operations.\n", sg->number, order); } else { std::fprintf(stderr, "%s space group name! Assuming P1.\n", st.spacegroup_hm.empty() ? "No" : "Unrecognized"); } if (!st.origx.is_identity()) printf(" The ORIGX matrix is not identity.\n"); if (st.cell.explicit_matrices) printf(" Non-standard fractionalization matrix is given.\n"); print_atoms_on_special_positions(st); double n_molecules = order * st.get_ncs_multiplier(); printf(" Number of images (symmetry * strict NCS): %5g\n", n_molecules); assert(n_molecules == st.cell.images.size() + 1); printf(" Cell volume [A^3]: %30.1f\n", st.cell.volume); printf(" ASU volume [A^3]: %30.1f\n", st.cell.volume / order); double water_count = 0; int residue_count = 0; int mol_h_count = 0; double mol_weight = 0; double mol_atom_count = 0; double buffer_atom_count = 0; double file_h_count = 0; const Model& model = st.first_model(); for (const Chain& chain : model.chains) { for (const Residue& res : chain.residues) { ResidueInfo res_info = find_tabulated_residue(res.name); bool is_buffer = res_info.is_buffer_or_water(); if (!is_buffer && chain.is_first_in_group(res)) { residue_count++; mol_h_count += std::max(res_info.hydrogen_count - 2, 0); } for (const Atom& atom : res.atoms) { if (atom.is_hydrogen()) { file_h_count += atom.occ; } else if (is_buffer) { if (res_info.is_water()) water_count += atom.occ; buffer_atom_count += atom.occ; } else { mol_atom_count += atom.occ; mol_weight += atom.occ * atom.element.weight(); } } } } // add weight of hydrogens mol_weight += mol_h_count * Element(El::H).weight(); printf(" Residue count excl. solvent and buffer: %7d\n", residue_count); printf(" Water count: %38.3f\n", water_count); printf(" Heavy (not H) atom count: %25.3f\n", mol_atom_count + buffer_atom_count); printf(" in macromolecules and ligands: %16.3f\n", mol_atom_count); printf(" in solvent and buffer: %24.3f\n", buffer_atom_count); printf(" Hydrogens in the file: %28.3f\n", file_h_count); printf("Solvent content based on the model (excl. solvent and buffer)\n"); printf(" Estimated hydrogen count: %21d\n", mol_h_count); printf(" Estimated molecular weight: %23.3f\n", mol_weight); if (st.cell.is_crystal()) { double Vm = st.cell.volume_per_image() / mol_weight; printf(" Matthews coefficient: %29.3f\n", Vm); double Na = 0.602214; // Avogadro number x 10^-24 (cm^3->A^3) // rwcontents uses 1.34, Rupp's papers 1.35 for (double ro : { 1.35, 1.34 }) printf(" Solvent %% (for protein density %g): %13.3f\n", ro, 100. * (1. - 1. / (ro * Vm * Na))); } else { printf(" Not a crystal / unit cell not known.\n"); } printf("Solvent content based on SEQRES\n"); mol_weight = 0.; bool missing = false; for (const Chain& chain : model.chains) if (ConstResidueSpan polymer = chain.get_polymer()) { const Entity* entity = st.get_entity_of(polymer); if (!entity || entity->full_sequence.empty()) { printf(" Missing sequence for chain %s.\n", chain.name.c_str()); missing = true; } mol_weight += calculate_sequence_weight(entity->full_sequence, 100.); } if (missing) return; printf(" Molecular weight from sequence: %19.3f\n", mol_weight); if (st.cell.is_crystal()) { double Vm = st.cell.volume_per_image() / mol_weight; printf(" Matthews coefficient: %29.3f\n", Vm); double Na = 0.602214; // Avogadro number x 10^-24 (cm^3->A^3) // rwcontents uses 1.34, Rupp's papers 1.35 for (double ro : { 1.35, 1.34 }) printf(" Solvent %% (for protein density %g): %13.3f\n", ro, 100. * (1. - 1. / (ro * Vm * Na))); } else { printf(" Not a crystal / unit cell not known.\n"); } } static void print_dihedrals(const Structure& st) { printf(" Chain Residue Psi Phi Omega\n"); const Model& model = st.first_model(); for (const Chain& chain : model.chains) { for (const Residue& res : chain.residues) { printf("%3s %4d%c %5s", chain.name.c_str(), *res.seqid.num, res.seqid.icode, res.name.c_str()); const Residue* prev = chain.previous_bonded_aa(res); const Residue* next = chain.next_bonded_aa(res); double omega = next ? calculate_omega(res, *next) : NAN; auto phi_psi = calculate_phi_psi(prev, res, next); if (prev || next) printf(" % 8.2f % 8.2f % 8.2f\n", deg(phi_psi[0]), deg(phi_psi[1]), deg(omega)); else printf("\n"); } } printf("\n"); } static void print_bfactor_info(const gemmi::Model& model) { std::vector<double> bfactors; for (const Chain& chain : model.chains) for (const Residue& res : chain.residues) for (const Atom& atom : res.atoms) if (atom.occ > 0) bfactors.push_back(atom.b_iso); gemmi::DataStats stats = gemmi::calculate_data_statistics(bfactors); printf("\nIsotropic ADPs: %zu values\n", bfactors.size()); printf(" min: %.2f max: %.2f mean: %.2f std.dev: %.2f\n", stats.dmin, stats.dmax, stats.dmean, stats.rms); if (stats.dmin < stats.dmax) print_histogram(bfactors, stats.dmin, stats.dmax); } int GEMMI_MAIN(int argc, char **argv) { OptParser p(EXE_NAME); p.simple_parse(argc, argv, Usage); p.require_input_files_as_args(); bool verbose = p.options[Verbose]; try { for (int i = 0; i < p.nonOptionsCount(); ++i) { std::string input = p.coordinate_input_file(i); if (i > 0) std::printf("\n"); if (verbose || p.nonOptionsCount() > 1) std::printf("File: %s\n", input.c_str()); Structure st = read_structure_gz(input); setup_entities(st); if (st.models.size() > 1) std::fprintf(stderr, "Warning: using only the first model out of %zu.\n", st.models.size()); if (!p.options[NoContentInfo]) print_content_info(st, verbose); if (p.options[Bfactors]) print_bfactor_info(st.first_model()); if (p.options[Dihedrals]) print_dihedrals(st); } } catch (std::runtime_error& e) { std::fprintf(stderr, "ERROR: %s\n", e.what()); return 1; } return 0; } // vim:sw=2:ts=2:et:path^=../include,../third_party <commit_msg>refactoring src/contents.cpp<commit_after>// Copyright 2017 Global Phasing Ltd. // // This program analyses PDB or mmCIF files, printing similar things // as CCP4 RWCONTENTS: weight, Matthews coefficient, etc. #include <cassert> #include <cstdio> #include <gemmi/symmetry.hpp> #include <gemmi/resinfo.hpp> #include <gemmi/calculate.hpp> #include <gemmi/gzread.hpp> #include <gemmi/polyheur.hpp> // for setup_entities, calculate_sequence_weight #include "histogram.h" // for print_histogram #define GEMMI_PROG contents #include "options.h" using namespace gemmi; using std::printf; enum OptionIndex { Dihedrals=4, Bfactors, NoContentInfo }; static const option::Descriptor Usage[] = { { NoOp, 0, "", "", Arg::None, "Usage:\n " EXE_NAME " [options] INPUT[...]" "\nAnalyses content of a PDB or mmCIF."}, CommonUsage[Help], CommonUsage[Version], CommonUsage[Verbose], { Bfactors, 0, "b", "", Arg::None, " -b \tPrint statistics of isotropic ADPs (B-factors)." }, { Dihedrals, 0, "", "dihedrals", Arg::None, " --dihedrals \tPrint peptide dihedral angles." }, { NoContentInfo, 0, "n", "", Arg::None, " -n \tDo not print content (for use with other options)." }, { 0, 0, 0, 0, 0, 0 } }; static void print_atoms_on_special_positions(const Structure& st) { printf(" Atoms on special positions:"); bool found = false; for (const Chain& chain : st.first_model().chains) for (const Residue& res : chain.residues) for (const Atom& atom : res.atoms) if (int n = st.cell.is_special_position(atom.pos)) { found = true; SymImage im = st.cell.find_nearest_image(atom.pos, atom.pos, Asu::Different); printf("\n %s %4d%c %3s %-3s %c fold=%d occ=%.2f d_image=%.4f", chain.name.c_str(), *res.seqid.num, res.seqid.icode, res.name.c_str(), atom.name.c_str(), (atom.altloc | 0x20), n+1, atom.occ, im.dist()); } if (!found) printf(" none"); printf("\n"); } static void print_solvent_content(const UnitCell& cell, double mol_weight) { if (cell.is_crystal()) { double Vm = cell.volume_per_image() / mol_weight; printf(" Matthews coefficient: %29.3f\n", Vm); double Na = 0.602214; // Avogadro number x 10^-24 (cm^3->A^3) // rwcontents uses 1.34, Rupp's papers 1.35 for (double ro : { 1.35, 1.34 }) printf(" Solvent %% (for protein density %g): %13.3f\n", ro, 100. * (1. - 1. / (ro * Vm * Na))); } else { printf(" Not a crystal / unit cell not known.\n"); } } static void print_content_info(const Structure& st, bool /*verbose*/) { printf(" Spacegroup %s\n", st.spacegroup_hm.c_str()); int order = 1; const SpaceGroup* sg = st.find_spacegroup(); if (sg) { order = sg->operations().order(); printf(" Group no. %d with %d operations.\n", sg->number, order); } else { std::fprintf(stderr, "%s space group name! Assuming P1.\n", st.spacegroup_hm.empty() ? "No" : "Unrecognized"); } if (!st.origx.is_identity()) printf(" The ORIGX matrix is not identity.\n"); if (st.cell.explicit_matrices) printf(" Non-standard fractionalization matrix is given.\n"); print_atoms_on_special_positions(st); double n_molecules = order * st.get_ncs_multiplier(); printf(" Number of images (symmetry * strict NCS): %5g\n", n_molecules); assert(n_molecules == st.cell.images.size() + 1); printf(" Cell volume [A^3]: %30.1f\n", st.cell.volume); printf(" ASU volume [A^3]: %30.1f\n", st.cell.volume / order); double water_count = 0; int residue_count = 0; int mol_h_count = 0; double mol_weight = 0; double mol_atom_count = 0; double buffer_atom_count = 0; double file_h_count = 0; const Model& model = st.first_model(); for (const Chain& chain : model.chains) { for (const Residue& res : chain.residues) { ResidueInfo res_info = find_tabulated_residue(res.name); bool is_buffer = res_info.is_buffer_or_water(); if (!is_buffer && chain.is_first_in_group(res)) { residue_count++; mol_h_count += std::max(res_info.hydrogen_count - 2, 0); } for (const Atom& atom : res.atoms) { if (atom.is_hydrogen()) { file_h_count += atom.occ; } else if (is_buffer) { if (res_info.is_water()) water_count += atom.occ; buffer_atom_count += atom.occ; } else { mol_atom_count += atom.occ; mol_weight += atom.occ * atom.element.weight(); } } } } // add weight of hydrogens mol_weight += mol_h_count * Element(El::H).weight(); printf(" Residue count excl. solvent and buffer: %7d\n", residue_count); printf(" Water count: %38.3f\n", water_count); printf(" Heavy (not H) atom count: %25.3f\n", mol_atom_count + buffer_atom_count); printf(" in macromolecules and ligands: %16.3f\n", mol_atom_count); printf(" in solvent and buffer: %24.3f\n", buffer_atom_count); printf(" Hydrogens in the file: %28.3f\n", file_h_count); printf("Solvent content based on the model (excl. solvent and buffer)\n"); printf(" Estimated hydrogen count: %21d\n", mol_h_count); printf(" Estimated molecular weight: %23.3f\n", mol_weight); print_solvent_content(st.cell, mol_weight); printf("Solvent content based on SEQRES\n"); mol_weight = 0.; bool missing = false; for (const Chain& chain : model.chains) if (ConstResidueSpan polymer = chain.get_polymer()) { const Entity* entity = st.get_entity_of(polymer); if (!entity || entity->full_sequence.empty()) { printf(" Missing sequence for chain %s.\n", chain.name.c_str()); missing = true; } mol_weight += calculate_sequence_weight(entity->full_sequence, 100.); } if (missing) return; printf(" Molecular weight from sequence: %19.3f\n", mol_weight); print_solvent_content(st.cell, mol_weight); } static void print_dihedrals(const Structure& st) { printf(" Chain Residue Psi Phi Omega\n"); const Model& model = st.first_model(); for (const Chain& chain : model.chains) { for (const Residue& res : chain.residues) { printf("%3s %4d%c %5s", chain.name.c_str(), *res.seqid.num, res.seqid.icode, res.name.c_str()); const Residue* prev = chain.previous_bonded_aa(res); const Residue* next = chain.next_bonded_aa(res); double omega = next ? calculate_omega(res, *next) : NAN; auto phi_psi = calculate_phi_psi(prev, res, next); if (prev || next) printf(" % 8.2f % 8.2f % 8.2f\n", deg(phi_psi[0]), deg(phi_psi[1]), deg(omega)); else printf("\n"); } } printf("\n"); } static void print_bfactor_info(const gemmi::Model& model) { std::vector<double> bfactors; for (const Chain& chain : model.chains) for (const Residue& res : chain.residues) for (const Atom& atom : res.atoms) if (atom.occ > 0) bfactors.push_back(atom.b_iso); gemmi::DataStats stats = gemmi::calculate_data_statistics(bfactors); printf("\nIsotropic ADPs: %zu values\n", bfactors.size()); printf(" min: %.2f max: %.2f mean: %.2f std.dev: %.2f\n", stats.dmin, stats.dmax, stats.dmean, stats.rms); if (stats.dmin < stats.dmax) print_histogram(bfactors, stats.dmin, stats.dmax); } int GEMMI_MAIN(int argc, char **argv) { OptParser p(EXE_NAME); p.simple_parse(argc, argv, Usage); p.require_input_files_as_args(); bool verbose = p.options[Verbose]; try { for (int i = 0; i < p.nonOptionsCount(); ++i) { std::string input = p.coordinate_input_file(i); if (i > 0) std::printf("\n"); if (verbose || p.nonOptionsCount() > 1) std::printf("File: %s\n", input.c_str()); Structure st = read_structure_gz(input); setup_entities(st); if (st.models.size() > 1) std::fprintf(stderr, "Warning: using only the first model out of %zu.\n", st.models.size()); if (!p.options[NoContentInfo]) print_content_info(st, verbose); if (p.options[Bfactors]) print_bfactor_info(st.first_model()); if (p.options[Dihedrals]) print_dihedrals(st); } } catch (std::runtime_error& e) { std::fprintf(stderr, "ERROR: %s\n", e.what()); return 1; } return 0; } // vim:sw=2:ts=2:et:path^=../include,../third_party <|endoftext|>
<commit_before>#include "VertexShader.h" using namespace Device; using namespace Rendering::Shader; VertexShader::VertexShader(ID3DBlob* blob, const std::string& key) : ShaderForm(blob, key), _shader(nullptr), _layout(nullptr) { _type = Type::Vertex; } VertexShader::~VertexShader(void) { SAFE_RELEASE(_shader); SAFE_RELEASE(_layout); } bool VertexShader::Create( const Device::DirectX* dx, const std::vector<D3D11_INPUT_ELEMENT_DESC>& vertexDeclations) { if(_blob == nullptr) return false; uint count = vertexDeclations.size(); ID3D11Device* device = dx->GetDevice(); HRESULT hr = device->CreateVertexShader( _blob->GetBufferPointer(), _blob->GetBufferSize(), nullptr, &_shader ); if( FAILED( hr ) ) return false; if(vertexDeclations.size() == 0) return true; hr = device->CreateInputLayout(vertexDeclations.data(), count, _blob->GetBufferPointer(), _blob->GetBufferSize(), &_layout); _blob->Release(); if( FAILED( hr ) ) return false; for(unsigned int i=0; i<count; ++i) { const D3D11_INPUT_ELEMENT_DESC& desc = vertexDeclations[i]; SemanticInfo info; { info.name = desc.SemanticName; info.semanticIndex = desc.SemanticIndex; if( (i+1) != count ) info.size = vertexDeclations[i+1].AlignedByteOffset - desc.AlignedByteOffset; } _semanticInfo.push_back(info); } _semanticInfo.back().size = dx->CalcFormatSize(vertexDeclations[count-1].Format); return true; } void VertexShader::BindShaderToContext(ID3D11DeviceContext* context) { context->VSSetShader(_shader, nullptr, 0); } void VertexShader::BindInputLayoutToContext(ID3D11DeviceContext* context) { context->IASetInputLayout(_layout); } void VertexShader::BindResourcesToContext( ID3D11DeviceContext* context, const std::vector<InputConstBuffer>* constBuffers, const std::vector<InputTexture>* textures, const std::vector<InputShaderResourceBuffer>* srBuffers) { if(constBuffers) { for(auto iter = constBuffers->begin(); iter != constBuffers->end(); ++iter) { ID3D11Buffer* buffer = (*iter).buffer->GetBuffer(); if(buffer && iter->useVS) context->VSSetConstantBuffers( (*iter).bindIndex, 1, &buffer ); } } if(textures) { for(auto iter = textures->begin(); iter != textures->end(); ++iter) { auto srv = iter->texture->GetShaderResourceView()->GetView(); if(srv && iter->useVS) context->VSSetShaderResources( iter->bindIndex, 1, &srv ); } } if(srBuffers) { for(auto iter = srBuffers->begin(); iter != srBuffers->end(); ++iter) { auto srv = iter->srBuffer->GetShaderResourceView(); if(srv && iter->useVS) context->VSSetShaderResources( iter->bindIndex, 1, srv ); } } } void VertexShader::Clear( ID3D11DeviceContext* context, const std::vector<InputConstBuffer>* constBuffers, const std::vector<InputTexture>* textures, const std::vector<InputShaderResourceBuffer>* srBuffers) { if(textures) { ID3D11ShaderResourceView* nullSrv = nullptr; for(auto iter = textures->begin(); iter != textures->end(); ++iter) { if(iter->useVS) context->VSSetShaderResources( iter->bindIndex, 1, &nullSrv ); } } if(srBuffers) { ID3D11ShaderResourceView* nullSrv = nullptr; for(auto iter = srBuffers->begin(); iter != srBuffers->end(); ++iter) { if(iter->useVS) context->VSSetShaderResources( iter->bindIndex, 1, &nullSrv ); } } if(constBuffers) { ID3D11Buffer* nullBuffer = nullptr; for(auto iter = constBuffers->begin(); iter != constBuffers->end(); ++iter) { if(iter->useVS) context->VSSetConstantBuffers( iter->bindIndex, 1, &nullBuffer ); } } } void VertexShader::BindTexture(ID3D11DeviceContext* context, TextureBindIndex bind, const Texture::Texture2D* tex) { ID3D11ShaderResourceView* srv = tex ? tex->GetShaderResourceView()->GetView() : nullptr; context->VSSetShaderResources(uint(bind), 1, &srv); } void VertexShader::BindSamplerState(ID3D11DeviceContext* context, SamplerStateBindIndex bind, ID3D11SamplerState* samplerState) { context->VSSetSamplers(uint(bind), 1, &samplerState); } void VertexShader::BindConstBuffer(ID3D11DeviceContext* context, ConstBufferBindIndex bind, const Buffer::ConstBuffer* cb) { ID3D11Buffer* buf = cb ? cb->GetBuffer() : nullptr; context->VSSetConstantBuffers(uint(bind), 1, &buf); } void VertexShader::BindShaderResourceBuffer(ID3D11DeviceContext* context, TextureBindIndex bind, const Buffer::ShaderResourceBuffer* srBuffer) { ID3D11ShaderResourceView* srv = srBuffer ? srBuffer->GetShaderResourceView() : nullptr; context->VSSetShaderResources(uint(bind), 1, &srv); } <commit_msg>VertexShader- BindTexture에서 Texture2D 대신 TextureForm을 사용하도록 수정 #32<commit_after>#include "VertexShader.h" using namespace Device; using namespace Rendering::Shader; VertexShader::VertexShader(ID3DBlob* blob, const std::string& key) : ShaderForm(blob, key), _shader(nullptr), _layout(nullptr) { _type = Type::Vertex; } VertexShader::~VertexShader(void) { SAFE_RELEASE(_shader); SAFE_RELEASE(_layout); } bool VertexShader::Create( const Device::DirectX* dx, const std::vector<D3D11_INPUT_ELEMENT_DESC>& vertexDeclations) { if(_blob == nullptr) return false; uint count = vertexDeclations.size(); ID3D11Device* device = dx->GetDevice(); HRESULT hr = device->CreateVertexShader( _blob->GetBufferPointer(), _blob->GetBufferSize(), nullptr, &_shader ); if( FAILED( hr ) ) return false; if(vertexDeclations.size() == 0) return true; hr = device->CreateInputLayout(vertexDeclations.data(), count, _blob->GetBufferPointer(), _blob->GetBufferSize(), &_layout); _blob->Release(); if( FAILED( hr ) ) return false; for(unsigned int i=0; i<count; ++i) { const D3D11_INPUT_ELEMENT_DESC& desc = vertexDeclations[i]; SemanticInfo info; { info.name = desc.SemanticName; info.semanticIndex = desc.SemanticIndex; if( (i+1) != count ) info.size = vertexDeclations[i+1].AlignedByteOffset - desc.AlignedByteOffset; } _semanticInfo.push_back(info); } _semanticInfo.back().size = dx->CalcFormatSize(vertexDeclations[count-1].Format); return true; } void VertexShader::BindShaderToContext(ID3D11DeviceContext* context) { context->VSSetShader(_shader, nullptr, 0); } void VertexShader::BindInputLayoutToContext(ID3D11DeviceContext* context) { context->IASetInputLayout(_layout); } void VertexShader::BindResourcesToContext( ID3D11DeviceContext* context, const std::vector<InputConstBuffer>* constBuffers, const std::vector<InputTexture>* textures, const std::vector<InputShaderResourceBuffer>* srBuffers) { if(constBuffers) { for(auto iter = constBuffers->begin(); iter != constBuffers->end(); ++iter) { ID3D11Buffer* buffer = (*iter).buffer->GetBuffer(); if(buffer && iter->useVS) context->VSSetConstantBuffers( (*iter).bindIndex, 1, &buffer ); } } if(textures) { for(auto iter = textures->begin(); iter != textures->end(); ++iter) { auto srv = iter->texture->GetShaderResourceView()->GetView(); if(srv && iter->useVS) context->VSSetShaderResources( iter->bindIndex, 1, &srv ); } } if(srBuffers) { for(auto iter = srBuffers->begin(); iter != srBuffers->end(); ++iter) { auto srv = iter->srBuffer->GetShaderResourceView(); if(srv && iter->useVS) context->VSSetShaderResources( iter->bindIndex, 1, srv ); } } } void VertexShader::Clear( ID3D11DeviceContext* context, const std::vector<InputConstBuffer>* constBuffers, const std::vector<InputTexture>* textures, const std::vector<InputShaderResourceBuffer>* srBuffers) { if(textures) { ID3D11ShaderResourceView* nullSrv = nullptr; for(auto iter = textures->begin(); iter != textures->end(); ++iter) { if(iter->useVS) context->VSSetShaderResources( iter->bindIndex, 1, &nullSrv ); } } if(srBuffers) { ID3D11ShaderResourceView* nullSrv = nullptr; for(auto iter = srBuffers->begin(); iter != srBuffers->end(); ++iter) { if(iter->useVS) context->VSSetShaderResources( iter->bindIndex, 1, &nullSrv ); } } if(constBuffers) { ID3D11Buffer* nullBuffer = nullptr; for(auto iter = constBuffers->begin(); iter != constBuffers->end(); ++iter) { if(iter->useVS) context->VSSetConstantBuffers( iter->bindIndex, 1, &nullBuffer ); } } } void VertexShader::BindTexture(ID3D11DeviceContext* context, TextureBindIndex bind, const Texture::TextureForm* tex) { ID3D11ShaderResourceView* srv = tex ? tex->GetShaderResourceView()->GetView() : nullptr; context->VSSetShaderResources(uint(bind), 1, &srv); } void VertexShader::BindSamplerState(ID3D11DeviceContext* context, SamplerStateBindIndex bind, ID3D11SamplerState* samplerState) { context->VSSetSamplers(uint(bind), 1, &samplerState); } void VertexShader::BindConstBuffer(ID3D11DeviceContext* context, ConstBufferBindIndex bind, const Buffer::ConstBuffer* cb) { ID3D11Buffer* buf = cb ? cb->GetBuffer() : nullptr; context->VSSetConstantBuffers(uint(bind), 1, &buf); } void VertexShader::BindShaderResourceBuffer(ID3D11DeviceContext* context, TextureBindIndex bind, const Buffer::ShaderResourceBuffer* srBuffer) { ID3D11ShaderResourceView* srv = srBuffer ? srBuffer->GetShaderResourceView() : nullptr; context->VSSetShaderResources(uint(bind), 1, &srv); } <|endoftext|>
<commit_before>#include "VertexRenderer.hpp" #include "FAST/SceneGraph.hpp" namespace fast { void VertexRenderer::draw(Matrix4f perspectiveMatrix, Matrix4f viewingMatrix) { std::lock_guard<std::mutex> lock(mMutex); glEnable(GL_POINT_SPRITE); // Circles created in fragment shader will not work without this glEnable(GL_VERTEX_PROGRAM_POINT_SIZE); activateShader(); setShaderUniform("perspectiveTransform", perspectiveMatrix); setShaderUniform("viewTransform", viewingMatrix); for(auto it : mDataToRender) { Mesh::pointer points = it.second; float pointSize = mDefaultPointSize; if(mInputSizes.count(it.first) > 0) { pointSize = mInputSizes[it.first]; } bool useGlobalColor = false; Color color = Color::Green(); if(mInputColors.count(it.first) > 0) { color = mInputColors[it.first]; useGlobalColor = true; } else if(mDefaultColorSet) { color = mDefaultColor; useGlobalColor = true; } bool drawOnTop; if(mInputDrawOnTop.count(it.first) > 0) { drawOnTop = mInputDrawOnTop[it.first]; } else { drawOnTop = mDefaultDrawOnTop; } if(drawOnTop) glDisable(GL_DEPTH_TEST); AffineTransformation::pointer transform = SceneGraph::getAffineTransformationFromData(points); setShaderUniform("transform", transform->getTransform()); setShaderUniform("pointSize", pointSize); VertexBufferObjectAccess::pointer access = points->getVertexBufferObjectAccess(ACCESS_READ); GLuint* coordinateVBO = access->getCoordinateVBO(); // Coordinates buffer glBindBuffer(GL_ARRAY_BUFFER, *coordinateVBO); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0); glEnableVertexAttribArray(0); // Color buffer if(access->hasColorVBO() && !useGlobalColor) { GLuint *colorVBO = access->getColorVBO(); glBindBuffer(GL_ARRAY_BUFFER, *colorVBO); glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0); glEnableVertexAttribArray(1); } else { useGlobalColor = true; } setShaderUniform("useGlobalColor", useGlobalColor); setShaderUniform("globalColor", color.asVector()); glDrawArrays(GL_POINTS, 0, points->getNrOfVertices()*3); glBindBuffer(GL_ARRAY_BUFFER, 0); if(drawOnTop) glEnable(GL_DEPTH_TEST); } deactivateShader(); } void VertexRenderer::draw2D( cl::BufferGL PBO, uint width, uint height, Eigen::Transform<float, 3, Eigen::Affine> pixelToViewportTransform, float PBOspacing, Vector2f translation ) { std::lock_guard<std::mutex> lock(mMutex); OpenCLDevice::pointer device = getMainDevice(); cl::CommandQueue queue = device->getCommandQueue(); std::vector<cl::Memory> v; v.push_back(PBO); queue.enqueueAcquireGLObjects(&v); // Map would probably be better here, but doesn't work on NVIDIA, segfault surprise! //float* pixels = (float*)queue.enqueueMapBuffer(PBO, CL_TRUE, CL_MAP_WRITE, 0, width*height*sizeof(float)*4); UniquePointer<float[]> pixels(new float[width*height*sizeof(float)*4]); queue.enqueueReadBuffer(PBO, CL_TRUE, 0, width*height*4*sizeof(float), pixels.get()); for(auto it : mDataToRender) { Mesh::pointer points = it.second; Color color = mDefaultColor; if(mInputColors.count(it.first) > 0) { color = mInputColors[it.first]; } MeshAccess::pointer access = points->getMeshAccess(ACCESS_READ); std::vector<MeshVertex> vertices = access->getVertices(); // Draw each line int size = 3; for(int i = 0; i < vertices.size(); ++i) { Vector2f position = vertices[i].getPosition().head(2); // In mm Vector2i positinInPixles( round(position.x() / PBOspacing), round(position.y() / PBOspacing) ); // Draw the line for(int j = -size; j <= size; ++j) { for(int k = -size; k <= size; ++k) { int x = positinInPixles.x() + j; int y = positinInPixles.y() + k; y = height - 1 - y; if(x < 0 || y < 0 || x >= width || y >= height) continue; pixels[4*(x + y*width)] = color.getRedValue(); pixels[4*(x + y*width) + 1] = color.getGreenValue(); pixels[4*(x + y*width) + 2] = color.getBlueValue(); }} } } //queue.enqueueUnmapMemObject(PBO, pixels); queue.enqueueWriteBuffer(PBO, CL_TRUE, 0, width*height*4*sizeof(float), pixels.get()); queue.enqueueReleaseGLObjects(&v); } VertexRenderer::VertexRenderer() { mDefaultPointSize = 10; mDefaultColorSet = false; mDefaultDrawOnTop = false; createInputPort<Mesh>(0, false); createShaderProgram({ Config::getKernelSourcePath() + "Visualization/VertexRenderer/VertexRenderer.vert", Config::getKernelSourcePath() + "Visualization/VertexRenderer/VertexRenderer.frag", }); } uint VertexRenderer::addInputConnection(DataPort::pointer port) { return Renderer::addInputConnection(port); } uint VertexRenderer::addInputConnection(DataPort::pointer port, Color color, float size) { uint nr = addInputConnection(port); setColor(nr, color); setSize(nr, size); return nr; } uint VertexRenderer::addInputData(DataObject::pointer data) { return Renderer::addInputData(data); } uint VertexRenderer::addInputData(Mesh::pointer data, Color color, float size) { uint nr = addInputData(data); setColor(nr, color); setSize(nr, size); } void VertexRenderer::setDefaultColor(Color color) { mDefaultColor = color; mDefaultColorSet = true; } void VertexRenderer::setDefaultSize(float size) { mDefaultPointSize = size; } void VertexRenderer::setDefaultDrawOnTop(bool drawOnTop) { mDefaultDrawOnTop = drawOnTop; } void VertexRenderer::setDrawOnTop(uint inputNr, bool drawOnTop) { mInputDrawOnTop[inputNr] = drawOnTop; } void VertexRenderer::setColor(uint inputNr, Color color) { mInputColors[inputNr] = color; } void VertexRenderer::setSize(uint inputNr, float size) { mInputSizes[inputNr] = size; } } // end namespace fast <commit_msg>Function must return a value.<commit_after>#include "VertexRenderer.hpp" #include "FAST/SceneGraph.hpp" namespace fast { void VertexRenderer::draw(Matrix4f perspectiveMatrix, Matrix4f viewingMatrix) { std::lock_guard<std::mutex> lock(mMutex); glEnable(GL_POINT_SPRITE); // Circles created in fragment shader will not work without this glEnable(GL_VERTEX_PROGRAM_POINT_SIZE); activateShader(); setShaderUniform("perspectiveTransform", perspectiveMatrix); setShaderUniform("viewTransform", viewingMatrix); for(auto it : mDataToRender) { Mesh::pointer points = it.second; float pointSize = mDefaultPointSize; if(mInputSizes.count(it.first) > 0) { pointSize = mInputSizes[it.first]; } bool useGlobalColor = false; Color color = Color::Green(); if(mInputColors.count(it.first) > 0) { color = mInputColors[it.first]; useGlobalColor = true; } else if(mDefaultColorSet) { color = mDefaultColor; useGlobalColor = true; } bool drawOnTop; if(mInputDrawOnTop.count(it.first) > 0) { drawOnTop = mInputDrawOnTop[it.first]; } else { drawOnTop = mDefaultDrawOnTop; } if(drawOnTop) glDisable(GL_DEPTH_TEST); AffineTransformation::pointer transform = SceneGraph::getAffineTransformationFromData(points); setShaderUniform("transform", transform->getTransform()); setShaderUniform("pointSize", pointSize); VertexBufferObjectAccess::pointer access = points->getVertexBufferObjectAccess(ACCESS_READ); GLuint* coordinateVBO = access->getCoordinateVBO(); // Coordinates buffer glBindBuffer(GL_ARRAY_BUFFER, *coordinateVBO); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0); glEnableVertexAttribArray(0); // Color buffer if(access->hasColorVBO() && !useGlobalColor) { GLuint *colorVBO = access->getColorVBO(); glBindBuffer(GL_ARRAY_BUFFER, *colorVBO); glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0); glEnableVertexAttribArray(1); } else { useGlobalColor = true; } setShaderUniform("useGlobalColor", useGlobalColor); setShaderUniform("globalColor", color.asVector()); glDrawArrays(GL_POINTS, 0, points->getNrOfVertices()*3); glBindBuffer(GL_ARRAY_BUFFER, 0); if(drawOnTop) glEnable(GL_DEPTH_TEST); } deactivateShader(); } void VertexRenderer::draw2D( cl::BufferGL PBO, uint width, uint height, Eigen::Transform<float, 3, Eigen::Affine> pixelToViewportTransform, float PBOspacing, Vector2f translation ) { std::lock_guard<std::mutex> lock(mMutex); OpenCLDevice::pointer device = getMainDevice(); cl::CommandQueue queue = device->getCommandQueue(); std::vector<cl::Memory> v; v.push_back(PBO); queue.enqueueAcquireGLObjects(&v); // Map would probably be better here, but doesn't work on NVIDIA, segfault surprise! //float* pixels = (float*)queue.enqueueMapBuffer(PBO, CL_TRUE, CL_MAP_WRITE, 0, width*height*sizeof(float)*4); UniquePointer<float[]> pixels(new float[width*height*sizeof(float)*4]); queue.enqueueReadBuffer(PBO, CL_TRUE, 0, width*height*4*sizeof(float), pixels.get()); for(auto it : mDataToRender) { Mesh::pointer points = it.second; Color color = mDefaultColor; if(mInputColors.count(it.first) > 0) { color = mInputColors[it.first]; } MeshAccess::pointer access = points->getMeshAccess(ACCESS_READ); std::vector<MeshVertex> vertices = access->getVertices(); // Draw each line int size = 3; for(int i = 0; i < vertices.size(); ++i) { Vector2f position = vertices[i].getPosition().head(2); // In mm Vector2i positinInPixles( round(position.x() / PBOspacing), round(position.y() / PBOspacing) ); // Draw the line for(int j = -size; j <= size; ++j) { for(int k = -size; k <= size; ++k) { int x = positinInPixles.x() + j; int y = positinInPixles.y() + k; y = height - 1 - y; if(x < 0 || y < 0 || x >= width || y >= height) continue; pixels[4*(x + y*width)] = color.getRedValue(); pixels[4*(x + y*width) + 1] = color.getGreenValue(); pixels[4*(x + y*width) + 2] = color.getBlueValue(); }} } } //queue.enqueueUnmapMemObject(PBO, pixels); queue.enqueueWriteBuffer(PBO, CL_TRUE, 0, width*height*4*sizeof(float), pixels.get()); queue.enqueueReleaseGLObjects(&v); } VertexRenderer::VertexRenderer() { mDefaultPointSize = 10; mDefaultColorSet = false; mDefaultDrawOnTop = false; createInputPort<Mesh>(0, false); createShaderProgram({ Config::getKernelSourcePath() + "Visualization/VertexRenderer/VertexRenderer.vert", Config::getKernelSourcePath() + "Visualization/VertexRenderer/VertexRenderer.frag", }); } uint VertexRenderer::addInputConnection(DataPort::pointer port) { return Renderer::addInputConnection(port); } uint VertexRenderer::addInputConnection(DataPort::pointer port, Color color, float size) { uint nr = addInputConnection(port); setColor(nr, color); setSize(nr, size); return nr; } uint VertexRenderer::addInputData(DataObject::pointer data) { return Renderer::addInputData(data); } uint VertexRenderer::addInputData(Mesh::pointer data, Color color, float size) { uint nr = addInputData(data); setColor(nr, color); setSize(nr, size); return nr; } void VertexRenderer::setDefaultColor(Color color) { mDefaultColor = color; mDefaultColorSet = true; } void VertexRenderer::setDefaultSize(float size) { mDefaultPointSize = size; } void VertexRenderer::setDefaultDrawOnTop(bool drawOnTop) { mDefaultDrawOnTop = drawOnTop; } void VertexRenderer::setDrawOnTop(uint inputNr, bool drawOnTop) { mInputDrawOnTop[inputNr] = drawOnTop; } void VertexRenderer::setColor(uint inputNr, Color color) { mInputColors[inputNr] = color; } void VertexRenderer::setSize(uint inputNr, float size) { mInputSizes[inputNr] = size; } } // end namespace fast <|endoftext|>
<commit_before>#include "xchainer/numerical_gradient.h" #include <algorithm> #include <functional> #include <vector> #ifdef XCHAINER_ENABLE_CUDA #include <cuda_runtime.h> #endif // XCHAINER_ENABLE_CUDA #include "xchainer/array.h" #include "xchainer/array_repr.h" #include "xchainer/error.h" #include "xchainer/indexable_array.h" #include "xchainer/indexer.h" #ifdef XCHAINER_ENABLE_CUDA #include "xchainer/cuda/cuda_runtime.h" #endif // XCHAINER_ENABLE_CUDA #include "xchainer/device.h" namespace xchainer { namespace numerical_gradient_internal { Array& Subtract(const Array& lhs, const Array& rhs, Array& out) { lhs.device().Synchronize(); rhs.device().Synchronize(); out.device().Synchronize(); VisitDtype(lhs.dtype(), [&](auto pt) { using T = typename decltype(pt)::type; IndexableArray<const T> lhs_iarray{lhs}; IndexableArray<const T> rhs_iarray{rhs}; IndexableArray<T> out_iarray{out}; Indexer<> indexer{lhs.shape()}; for (int64_t i = 0; i < indexer.total_size(); i++) { indexer.Set(i); out_iarray[indexer] = lhs_iarray[indexer] - rhs_iarray[indexer]; } }); return out; } Array& Divide(const Array& lhs, const Array& rhs, Array& out) { lhs.device().Synchronize(); rhs.device().Synchronize(); out.device().Synchronize(); VisitDtype(lhs.dtype(), [&](auto pt) { using T = typename decltype(pt)::type; IndexableArray<const T> lhs_iarray{lhs}; IndexableArray<const T> rhs_iarray{rhs}; IndexableArray<T> out_iarray{out}; Indexer<> indexer{lhs.shape()}; for (int64_t i = 0; i < indexer.total_size(); i++) { indexer.Set(i); out_iarray[indexer] = lhs_iarray[indexer] / rhs_iarray[indexer]; } }); return out; } Array operator-(const Array& lhs, const Array& rhs) { Array out = Array::EmptyLike(lhs); Subtract(lhs, rhs, out); return out; } Array operator/(const Array& lhs, const Array& rhs) { Array out = Array::EmptyLike(lhs); Divide(lhs, rhs, out); return out; } Scalar Sum(const Array& array) { array.device().Synchronize(); return VisitDtype(array.dtype(), [&](auto pt) { using T = typename decltype(pt)::type; IndexableArray<const T> iarray{array}; Indexer<> indexer{array.shape()}; T s = 0; for (int64_t i = 0; i < indexer.total_size(); i++) { indexer.Set(i); s += iarray[indexer]; } return Scalar{s}; }); } Scalar Norm(const Array& x) { Scalar s = Sum(x * x); return Scalar(std::sqrt(static_cast<double>(s)), x.dtype()); } Scalar VectorDot(const Array& x, const Array& y) { return Sum(x * y); } void Set(Array& out, int64_t flat_index, Scalar value) { out.device().Synchronize(); VisitDtype(out.dtype(), [&](auto pt) { using T = typename decltype(pt)::type; IndexableArray<T> iarray{out}; Indexer<> indexer{out.shape()}; indexer.Set(flat_index); iarray[indexer] = static_cast<T>(value); }); } Scalar Get(const Array& out, int64_t flat_index) { out.device().Synchronize(); return VisitDtype(out.dtype(), [&](auto pt) { using T = typename decltype(pt)::type; IndexableArray<const T> iarray{out}; Indexer<> indexer{out.shape()}; indexer.Set(flat_index); return Scalar{iarray[indexer]}; }); } Arrays CalculateNumericalGradient( std::function<Arrays(const Arrays&)> func, const Arrays& inputs, const Arrays& grad_outputs, const Arrays& eps, const GraphId& graph_id) { // TODO(niboshi): Currently only elementwise functions are supported. // TODO(niboshi): Implement arithmetic operations and avoid manual synchronize const int nin = inputs.size(); const int nout = grad_outputs.size(); if (eps.size() != static_cast<size_t>(nin)) { throw XchainerError( "Invalid number of eps arrays where number of inputs: " + std::to_string(nin) + ", eps: " + std::to_string(eps.size())); } for (int i = 0; i < nin; ++i) { if (inputs.at(i).shape() != eps.at(i).shape()) { throw XchainerError("Invalid eps shape"); } if (inputs.at(i).dtype() != eps.at(i).dtype()) { throw XchainerError("Invalid eps dtype"); } // TODO(niboshi): Check: eps must not contain zeros. } Dtype dtype = inputs[0].dtype(); auto eval = [&, graph_id](int i_in, int64_t in_flat_index, Scalar eps_scalar, float multiplier) -> Arrays { Arrays xs; std::transform(inputs.begin(), inputs.end(), std::back_inserter(xs), [graph_id](const Array& x) { return x.AsConstant(CopyKind::kCopy).RequireGrad(graph_id); }); Set(xs.at(i_in), in_flat_index, Get(xs.at(i_in), in_flat_index) + Scalar(static_cast<float>(eps_scalar) * multiplier, dtype)); return func(xs); }; Arrays grads; for (int i = 0; i < nin; ++i) { Array grad_i = Array::ZerosLike(inputs.at(i)); int64_t size = grad_i.GetTotalSize(); for (int64_t in_flat_index = 0; in_flat_index < size; ++in_flat_index) { Scalar eps_scalar = Get(eps.at(i), in_flat_index); Arrays ys0 = eval(i, in_flat_index, eps_scalar, -1); Arrays ys1 = eval(i, in_flat_index, eps_scalar, 1); for (int j = 0; j < nout; ++j) { Array dy = ys1.at(j) - ys0.at(j); Array denom = Array::FullLike(dy, eps_scalar) * Array::FullLike(dy, Scalar(2, dtype)); Scalar g = VectorDot((ys1.at(j) - ys0.at(j)) / denom, grad_outputs.at(j)); Scalar g_ij = Get(grad_i, in_flat_index) + g; Set(grad_i, in_flat_index, g_ij); } } grads.push_back(grad_i); } return grads; } } // namespace numerical_gradient_internal } // namespace xchainer <commit_msg>Cosmetics<commit_after>#include "xchainer/numerical_gradient.h" #include <algorithm> #include <functional> #include <vector> #ifdef XCHAINER_ENABLE_CUDA #include <cuda_runtime.h> #endif // XCHAINER_ENABLE_CUDA #include "xchainer/array.h" #include "xchainer/array_repr.h" #include "xchainer/error.h" #include "xchainer/indexable_array.h" #include "xchainer/indexer.h" #ifdef XCHAINER_ENABLE_CUDA #include "xchainer/cuda/cuda_runtime.h" #endif // XCHAINER_ENABLE_CUDA #include "xchainer/device.h" namespace xchainer { namespace numerical_gradient_internal { Array& Subtract(const Array& lhs, const Array& rhs, Array& out) { lhs.device().Synchronize(); rhs.device().Synchronize(); out.device().Synchronize(); VisitDtype(lhs.dtype(), [&](auto pt) { using T = typename decltype(pt)::type; IndexableArray<const T> lhs_iarray{lhs}; IndexableArray<const T> rhs_iarray{rhs}; IndexableArray<T> out_iarray{out}; Indexer<> indexer{out.shape()}; for (int64_t i = 0; i < indexer.total_size(); i++) { indexer.Set(i); out_iarray[indexer] = lhs_iarray[indexer] - rhs_iarray[indexer]; } }); return out; } Array& Divide(const Array& lhs, const Array& rhs, Array& out) { lhs.device().Synchronize(); rhs.device().Synchronize(); out.device().Synchronize(); VisitDtype(lhs.dtype(), [&](auto pt) { using T = typename decltype(pt)::type; IndexableArray<const T> lhs_iarray{lhs}; IndexableArray<const T> rhs_iarray{rhs}; IndexableArray<T> out_iarray{out}; Indexer<> indexer{out.shape()}; for (int64_t i = 0; i < indexer.total_size(); i++) { indexer.Set(i); out_iarray[indexer] = lhs_iarray[indexer] / rhs_iarray[indexer]; } }); return out; } Array operator-(const Array& lhs, const Array& rhs) { Array out = Array::EmptyLike(lhs); Subtract(lhs, rhs, out); return out; } Array operator/(const Array& lhs, const Array& rhs) { Array out = Array::EmptyLike(lhs); Divide(lhs, rhs, out); return out; } Scalar Sum(const Array& array) { array.device().Synchronize(); return VisitDtype(array.dtype(), [&](auto pt) { using T = typename decltype(pt)::type; IndexableArray<const T> iarray{array}; Indexer<> indexer{array.shape()}; T s = 0; for (int64_t i = 0; i < indexer.total_size(); i++) { indexer.Set(i); s += iarray[indexer]; } return Scalar{s}; }); } Scalar Norm(const Array& x) { Scalar s = Sum(x * x); return Scalar(std::sqrt(static_cast<double>(s)), x.dtype()); } Scalar VectorDot(const Array& x, const Array& y) { return Sum(x * y); } void Set(Array& out, int64_t flat_index, Scalar value) { out.device().Synchronize(); VisitDtype(out.dtype(), [&](auto pt) { using T = typename decltype(pt)::type; IndexableArray<T> iarray{out}; Indexer<> indexer{out.shape()}; indexer.Set(flat_index); iarray[indexer] = static_cast<T>(value); }); } Scalar Get(const Array& out, int64_t flat_index) { out.device().Synchronize(); return VisitDtype(out.dtype(), [&](auto pt) { using T = typename decltype(pt)::type; IndexableArray<const T> iarray{out}; Indexer<> indexer{out.shape()}; indexer.Set(flat_index); return Scalar{iarray[indexer]}; }); } Arrays CalculateNumericalGradient( std::function<Arrays(const Arrays&)> func, const Arrays& inputs, const Arrays& grad_outputs, const Arrays& eps, const GraphId& graph_id) { // TODO(niboshi): Currently only elementwise functions are supported. // TODO(niboshi): Implement arithmetic operations and avoid manual synchronize const int nin = inputs.size(); const int nout = grad_outputs.size(); if (eps.size() != static_cast<size_t>(nin)) { throw XchainerError( "Invalid number of eps arrays where number of inputs: " + std::to_string(nin) + ", eps: " + std::to_string(eps.size())); } for (int i = 0; i < nin; ++i) { if (inputs.at(i).shape() != eps.at(i).shape()) { throw XchainerError("Invalid eps shape"); } if (inputs.at(i).dtype() != eps.at(i).dtype()) { throw XchainerError("Invalid eps dtype"); } // TODO(niboshi): Check: eps must not contain zeros. } Dtype dtype = inputs[0].dtype(); auto eval = [&, graph_id](int i_in, int64_t in_flat_index, Scalar eps_scalar, float multiplier) -> Arrays { Arrays xs; std::transform(inputs.begin(), inputs.end(), std::back_inserter(xs), [graph_id](const Array& x) { return x.AsConstant(CopyKind::kCopy).RequireGrad(graph_id); }); Set(xs.at(i_in), in_flat_index, Get(xs.at(i_in), in_flat_index) + Scalar(static_cast<float>(eps_scalar) * multiplier, dtype)); return func(xs); }; Arrays grads; for (int i = 0; i < nin; ++i) { Array grad_i = Array::ZerosLike(inputs.at(i)); int64_t size = grad_i.GetTotalSize(); for (int64_t in_flat_index = 0; in_flat_index < size; ++in_flat_index) { Scalar eps_scalar = Get(eps.at(i), in_flat_index); Arrays ys0 = eval(i, in_flat_index, eps_scalar, -1); Arrays ys1 = eval(i, in_flat_index, eps_scalar, 1); for (int j = 0; j < nout; ++j) { Array dy = ys1.at(j) - ys0.at(j); Array denom = Array::FullLike(dy, eps_scalar) * Array::FullLike(dy, Scalar(2, dtype)); Scalar g = VectorDot((ys1.at(j) - ys0.at(j)) / denom, grad_outputs.at(j)); Scalar g_ij = Get(grad_i, in_flat_index) + g; Set(grad_i, in_flat_index, g_ij); } } grads.push_back(grad_i); } return grads; } } // namespace numerical_gradient_internal } // namespace xchainer <|endoftext|>
<commit_before>/** @file clientapitest.cpp @brief Automatic tests for sensor client interfaces <p> Copyright (C) 2009-2010 Nokia Corporation @author Timo Rongas <ext-timo.2.rongas@nokia.com> @author Ustun Ergenoglu <ext-ustun.ergenoglu@nokia.com> This file is part of Sensord. Sensord is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License version 2.1 as published by the Free Software Foundation. Sensord is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with Sensord. If not, see <http://www.gnu.org/licenses/>. </p> */ #include "qt-api/sensormanagerinterface.h" #include "qt-api/orientationsensor_i.h" #include "qt-api/accelerometersensor_i.h" #include "qt-api/compasssensor_i.h" #include "qt-api/tapsensor_i.h" #include "qt-api/alssensor_i.h" #include "qt-api/proximitysensor_i.h" #include "qt-api/rotationsensor_i.h" #include "qt-api/magnetometersensor_i.h" #include "clientapitest.h" void ClientApiTest::initTestCase() { qDBusRegisterMetaType<XYZ>(); qDBusRegisterMetaType<Compass>(); qDBusRegisterMetaType<MagneticField>(); qDBusRegisterMetaType<Tap>(); qDBusRegisterMetaType<Unsigned>(); SensorManagerInterface& remoteSensorManager = SensorManagerInterface::instance(); QVERIFY( remoteSensorManager.isValid() ); // Load plugins (should test running depend on plug-in load result?) qDebug() << remoteSensorManager.loadPlugin("orientationsensor"); remoteSensorManager.loadPlugin("accelerometersensor"); remoteSensorManager.loadPlugin("compasssensor"); remoteSensorManager.loadPlugin("tapsensor"); remoteSensorManager.loadPlugin("alssensor"); remoteSensorManager.loadPlugin("proximitysensor"); remoteSensorManager.loadPlugin("rotationsensor"); remoteSensorManager.loadPlugin("magnetometersensor"); // Register interfaces (can this be done inside the plugins? remoteSensorManager.registerSensorInterface<OrientationSensorChannelInterface>("orientationsensor"); remoteSensorManager.registerSensorInterface<AccelerometerSensorChannelInterface>("accelerometersensor"); remoteSensorManager.registerSensorInterface<CompassSensorChannelInterface>("compasssensor"); remoteSensorManager.registerSensorInterface<TapSensorChannelInterface>("tapsensor"); remoteSensorManager.registerSensorInterface<ALSSensorChannelInterface>("alssensor"); remoteSensorManager.registerSensorInterface<ProximitySensorChannelInterface>("proximitysensor"); remoteSensorManager.registerSensorInterface<RotationSensorChannelInterface>("rotationsensor"); remoteSensorManager.registerSensorInterface<MagnetometerSensorChannelInterface>("magnetometersensor"); } void ClientApiTest::init() { //qDebug() << "Run before each test"; //TODO: Verify that sensord has not crashed. } void ClientApiTest::cleanup() { //qDebug() << "Run after each test"; //TODO: Verify that sensord has not crashed. } void ClientApiTest::cleanupTestCase() { //qDebug() << "Run after all test cases"; } void ClientApiTest::testOrientationSensor() { QString sensorName("orientationsensor"); SensorManagerInterface& sm = SensorManagerInterface::instance(); QVERIFY( sm.isValid() ); // Get control session OrientationSensorChannelInterface* sensorIfc = OrientationSensorChannelInterface::controlInterface(sensorName); QVERIFY2(sensorIfc && sensorIfc->isValid(), "Failed to get control session"); // Attempt to get another control session OrientationSensorChannelInterface* failIfc = OrientationSensorChannelInterface::controlInterface(sensorName); QVERIFY2(!failIfc, "Got another control session"); // Get listen session const OrientationSensorChannelInterface* listenIfc = OrientationSensorChannelInterface::listenInterface(sensorName); QVERIFY2(listenIfc && listenIfc->isValid(), "Failed to get listen session"); delete listenIfc; // Test properties sensorIfc->setInterval(100); QVERIFY(sensorIfc->orientation() == qvariant_cast<Unsigned>(sensorIfc->property("orientation"))); QVERIFY(sensorIfc->threshold() == sensorIfc->property("threshold")); int offset = 200; int threshold = sensorIfc->threshold(); sensorIfc->setThreshold(threshold + offset); QVERIFY(threshold+offset == sensorIfc->threshold()); sensorIfc->setThreshold(threshold); // test start QDBusReply<void> reply = sensorIfc->start(); QVERIFY(reply.isValid()); // test stop reply = sensorIfc->stop(); QVERIFY(reply.isValid()); delete sensorIfc; } void ClientApiTest::testAccelerometerSensor() { QString sensorName("accelerometersensor"); SensorManagerInterface& sm = SensorManagerInterface::instance(); QVERIFY( sm.isValid() ); // Get control session AccelerometerSensorChannelInterface* sensorIfc = AccelerometerSensorChannelInterface::controlInterface(sensorName); QVERIFY2(sensorIfc && sensorIfc->isValid(), "Failed to get control session"); // Attempt to get another control session AccelerometerSensorChannelInterface* failIfc = AccelerometerSensorChannelInterface::controlInterface(sensorName); QVERIFY2(!failIfc, "Got another control session"); // Get listen session const AccelerometerSensorChannelInterface* listenIfc = AccelerometerSensorChannelInterface::listenInterface(sensorName); QVERIFY2(listenIfc && listenIfc->isValid(), "Failed to get listen session"); delete listenIfc; // Test properties sensorIfc->setInterval(100); // test start QDBusReply<void> reply = sensorIfc->start(); QVERIFY(reply.isValid()); // test stop reply = sensorIfc->stop(); QVERIFY(reply.isValid()); XYZ sample1 = sensorIfc->get(); XYZ sample2 = qvariant_cast<XYZ>(sensorIfc->property("value")); QVERIFY(sample1 == sample2); delete sensorIfc; } void ClientApiTest::testMagnetometerSensor() { QString sensorName("magnetometersensor"); SensorManagerInterface& sm = SensorManagerInterface::instance(); QVERIFY( sm.isValid() ); // Get control session MagnetometerSensorChannelInterface* sensorIfc = MagnetometerSensorChannelInterface::controlInterface(sensorName); QVERIFY2(sensorIfc && sensorIfc->isValid(), "Failed to get control session"); // Attempt to get another control session MagnetometerSensorChannelInterface* failIfc = MagnetometerSensorChannelInterface::controlInterface(sensorName); QVERIFY2(!failIfc, "Got another control session"); // Get listen session const MagnetometerSensorChannelInterface* listenIfc = MagnetometerSensorChannelInterface::listenInterface(sensorName); QVERIFY2(listenIfc && listenIfc->isValid(), "Failed to get listen session"); delete listenIfc; // Test properties sensorIfc->setInterval(100); // Need simulated data to make sensible test ouf of this. MagneticField sample1 = sensorIfc->magneticField(); MagneticField sample2 = qvariant_cast<MagneticField>(sensorIfc->property("magneticField")); // Background process keeps magnetometer on -- values are changing, and subsequent // calls are likely to give different values. This makes thus no sense. // QVERIFY(sample1 == sample2); // test start QDBusReply<void> reply = sensorIfc->start(); QVERIFY(reply.isValid()); // test stop reply = sensorIfc->stop(); QVERIFY(reply.isValid()); delete sensorIfc; } void ClientApiTest::testCompassSensor() { QString sensorName("compasssensor"); SensorManagerInterface& sm = SensorManagerInterface::instance(); QVERIFY( sm.isValid() ); // Get control session CompassSensorChannelInterface* sensorIfc = CompassSensorChannelInterface::controlInterface(sensorName); QVERIFY2(sensorIfc && sensorIfc->isValid(), "Failed to get control session"); // Attempt to get another control session CompassSensorChannelInterface* failIfc = CompassSensorChannelInterface::controlInterface(sensorName); QVERIFY2(!failIfc, "Got another control session"); // Get listen session const CompassSensorChannelInterface* listenIfc = CompassSensorChannelInterface::listenInterface(sensorName); QVERIFY2(listenIfc && listenIfc->isValid(), "Failed to get listen session"); delete listenIfc; // Test properties sensorIfc->setInterval(100); QVERIFY(sensorIfc->get() == qvariant_cast<Compass>(sensorIfc->property("value"))); QVERIFY(sensorIfc->useDeclination() == sensorIfc->property("usedeclination")); QVERIFY(sensorIfc->declinationValue() == sensorIfc->property("declinationvalue")); // Check declination on/off bool declinationInUse = sensorIfc->useDeclination(); sensorIfc->setUseDeclination(!declinationInUse); QVERIFY(declinationInUse != sensorIfc->useDeclination()); sensorIfc->setUseDeclination(!declinationInUse); // TODO: Compare declination value against value in gconf // test start QDBusReply<void> reply = sensorIfc->start(); QVERIFY(reply.isValid()); // test stop reply = sensorIfc->stop(); QVERIFY(reply.isValid()); delete sensorIfc; } void ClientApiTest::testTapSensor() { QString sensorName("tapsensor"); SensorManagerInterface& sm = SensorManagerInterface::instance(); QVERIFY( sm.isValid() ); // Get control session TapSensorChannelInterface* sensorIfc = TapSensorChannelInterface::controlInterface(sensorName); QVERIFY2(sensorIfc && sensorIfc->isValid(), "Failed to get control session"); // Attempt to get another control session TapSensorChannelInterface* failIfc = TapSensorChannelInterface::controlInterface(sensorName); QVERIFY2(!failIfc, "Got another control session"); // Get listen session const TapSensorChannelInterface* listenIfc = TapSensorChannelInterface::listenInterface(sensorName); QVERIFY2(listenIfc && listenIfc->isValid(), "Failed to get listen session"); delete listenIfc; // Test properties sensorIfc->setInterval(100); // test start QDBusReply<void> reply = sensorIfc->start(); QVERIFY(reply.isValid()); // test stop reply = sensorIfc->stop(); QVERIFY(reply.isValid()); delete sensorIfc; } void ClientApiTest::testALSSensor() { QString sensorName("alssensor"); SensorManagerInterface& sm = SensorManagerInterface::instance(); QVERIFY( sm.isValid() ); // Get control session // TODO: Because context takes control over ALS in sensord::main(), // we can't test this. (applies to all other possible open // sessions too...) //ALSSensorChannelInterface* sensorIfc = ALSSensorChannelInterface::controlInterface(sensorName); //QVERIFY2(sensorIfc && sensorIfc->isValid(), "Failed to get control session"); // Attempt to get another control session ALSSensorChannelInterface* failIfc = ALSSensorChannelInterface::controlInterface(sensorName); QVERIFY2(!failIfc, "Got another control session"); // Get listen session const ALSSensorChannelInterface* listenIfc = ALSSensorChannelInterface::listenInterface(sensorName); QVERIFY2(listenIfc && listenIfc->isValid(), "Failed to get listen session"); delete listenIfc; // Test properties //sensorIfc->setInterval(100); // test start //QDBusReply<void> reply = sensorIfc->start(); //QVERIFY(reply.isValid()); // test stop //reply = sensorIfc->stop(); //QVERIFY(reply.isValid()); //delete sensorIfc; } void ClientApiTest::testProximitySensor() { QString sensorName("proximitysensor"); SensorManagerInterface& sm = SensorManagerInterface::instance(); QVERIFY( sm.isValid() ); // Get control session ProximitySensorChannelInterface* sensorIfc = ProximitySensorChannelInterface::controlInterface(sensorName); QVERIFY2(sensorIfc && sensorIfc->isValid(), "Failed to get control session"); // Attempt to get another control session ProximitySensorChannelInterface* failIfc = ProximitySensorChannelInterface::controlInterface(sensorName); QVERIFY2(!failIfc, "Got another control session"); // Get listen session const ProximitySensorChannelInterface* listenIfc = ProximitySensorChannelInterface::listenInterface(sensorName); QVERIFY2(listenIfc && listenIfc->isValid(), "Failed to get listen session"); delete listenIfc; // Test properties sensorIfc->setInterval(100); // test start QDBusReply<void> reply = sensorIfc->start(); QVERIFY(reply.isValid()); // test stop reply = sensorIfc->stop(); QVERIFY(reply.isValid()); delete sensorIfc; } void ClientApiTest::testRotationSensor() { QString sensorName("rotationsensor"); SensorManagerInterface& sm = SensorManagerInterface::instance(); QVERIFY( sm.isValid() ); // Get control session RotationSensorChannelInterface* sensorIfc = RotationSensorChannelInterface::controlInterface(sensorName); QVERIFY2(sensorIfc && sensorIfc->isValid(), "Failed to get control session"); // Attempt to get another control session RotationSensorChannelInterface* failIfc = RotationSensorChannelInterface::controlInterface(sensorName); QVERIFY2(!failIfc, "Got another control session"); // Get listen session const RotationSensorChannelInterface* listenIfc = RotationSensorChannelInterface::listenInterface(sensorName); QVERIFY2(listenIfc && listenIfc->isValid(), "Failed to get listen session"); delete listenIfc; // Test properties sensorIfc->setInterval(100); bool hasz = sensorIfc->hasZ(); qDebug() << "Z-axis rotation calculations in use:" << hasz; // Need simulated data to make sensible test ouf of this. XYZ sample1 = sensorIfc->rotation(); XYZ sample2 = qvariant_cast<XYZ>(sensorIfc->property("rotation")); QVERIFY(sample1 == sample2); // test start QDBusReply<void> reply = sensorIfc->start(); QVERIFY(reply.isValid()); // test stop reply = sensorIfc->stop(); QVERIFY(reply.isValid()); delete sensorIfc; } /** * Runs two sensors using the same adaptor/chain simultaneously. * * For the sake of testing, OrientationSensor and AccelerometerSensor are * used. AccelerometerChain is shared. * * @note Sensord hacks starting context framework things might affect this by * adding other sensors that use the same adaptor. */ void ClientApiTest::testCommonAdaptorPipeline() { int DELAY = 250; OrientationSensorChannelInterface *orientation; AccelerometerSensorChannelInterface *accelerometer; orientation = OrientationSensorChannelInterface::controlInterface("orientationsensor"); QVERIFY2(orientation && orientation->isValid(), "Could not get orientation sensor control channel"); orientation->setInterval(100); orientation->start(); qDebug() << "Orientation sensor started, waiting for" << DELAY << "ms."; QTest::qWait(DELAY); accelerometer = AccelerometerSensorChannelInterface::controlInterface("accelerometersensor"); QVERIFY2(accelerometer && accelerometer->isValid(), "Could not get accelerometer sensor control channel"); accelerometer->setInterval(100); accelerometer->start(); qDebug() << "Accelerometer sensor started, waiting for" << DELAY << "ms."; QTest::qWait(DELAY); orientation->stop(); qDebug() << "Orientation sensor stopped, waiting for" << DELAY << "ms."; QTest::qWait(DELAY); delete orientation; qDebug() << "Orientation sensor destroyed, waiting for" << DELAY << "ms."; QTest::qWait(DELAY); accelerometer->stop(); qDebug() << "Accelerometer sensor stopped."; delete accelerometer; } void ClientApiTest::testListenSessionInitiation() { const OrientationSensorChannelInterface *orientation; orientation = OrientationSensorChannelInterface::listenInterface("orientationsensor"); QVERIFY2(orientation && orientation->isValid(), "Could not get orientation sensor listen channel"); } QTEST_MAIN(ClientApiTest) <commit_msg>fixed client api tests.<commit_after>/** @file clientapitest.cpp @brief Automatic tests for sensor client interfaces <p> Copyright (C) 2009-2010 Nokia Corporation @author Timo Rongas <ext-timo.2.rongas@nokia.com> @author Ustun Ergenoglu <ext-ustun.ergenoglu@nokia.com> This file is part of Sensord. Sensord is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License version 2.1 as published by the Free Software Foundation. Sensord is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with Sensord. If not, see <http://www.gnu.org/licenses/>. </p> */ #include "qt-api/sensormanagerinterface.h" #include "qt-api/orientationsensor_i.h" #include "qt-api/accelerometersensor_i.h" #include "qt-api/compasssensor_i.h" #include "qt-api/tapsensor_i.h" #include "qt-api/alssensor_i.h" #include "qt-api/proximitysensor_i.h" #include "qt-api/rotationsensor_i.h" #include "qt-api/magnetometersensor_i.h" #include "clientapitest.h" void ClientApiTest::initTestCase() { qDBusRegisterMetaType<XYZ>(); qDBusRegisterMetaType<Compass>(); qDBusRegisterMetaType<MagneticField>(); qDBusRegisterMetaType<Tap>(); qDBusRegisterMetaType<Unsigned>(); SensorManagerInterface& remoteSensorManager = SensorManagerInterface::instance(); QVERIFY( remoteSensorManager.isValid() ); // Load plugins (should test running depend on plug-in load result?) qDebug() << remoteSensorManager.loadPlugin("orientationsensor"); remoteSensorManager.loadPlugin("accelerometersensor"); remoteSensorManager.loadPlugin("compasssensor"); remoteSensorManager.loadPlugin("tapsensor"); remoteSensorManager.loadPlugin("alssensor"); remoteSensorManager.loadPlugin("proximitysensor"); remoteSensorManager.loadPlugin("rotationsensor"); remoteSensorManager.loadPlugin("magnetometersensor"); // Register interfaces (can this be done inside the plugins? remoteSensorManager.registerSensorInterface<OrientationSensorChannelInterface>("orientationsensor"); remoteSensorManager.registerSensorInterface<AccelerometerSensorChannelInterface>("accelerometersensor"); remoteSensorManager.registerSensorInterface<CompassSensorChannelInterface>("compasssensor"); remoteSensorManager.registerSensorInterface<TapSensorChannelInterface>("tapsensor"); remoteSensorManager.registerSensorInterface<ALSSensorChannelInterface>("alssensor"); remoteSensorManager.registerSensorInterface<ProximitySensorChannelInterface>("proximitysensor"); remoteSensorManager.registerSensorInterface<RotationSensorChannelInterface>("rotationsensor"); remoteSensorManager.registerSensorInterface<MagnetometerSensorChannelInterface>("magnetometersensor"); } void ClientApiTest::init() { //qDebug() << "Run before each test"; //TODO: Verify that sensord has not crashed. } void ClientApiTest::cleanup() { //qDebug() << "Run after each test"; //TODO: Verify that sensord has not crashed. } void ClientApiTest::cleanupTestCase() { //qDebug() << "Run after all test cases"; } void ClientApiTest::testOrientationSensor() { QString sensorName("orientationsensor"); SensorManagerInterface& sm = SensorManagerInterface::instance(); QVERIFY( sm.isValid() ); // Get control session OrientationSensorChannelInterface* sensorIfc = OrientationSensorChannelInterface::controlInterface(sensorName); QVERIFY2(sensorIfc && sensorIfc->isValid(), "Failed to get control session"); // Attempt to get another control session OrientationSensorChannelInterface* failIfc = OrientationSensorChannelInterface::controlInterface(sensorName); QVERIFY2(!failIfc, "Got another control session"); // Get listen session const OrientationSensorChannelInterface* listenIfc = OrientationSensorChannelInterface::listenInterface(sensorName); QVERIFY2(listenIfc && listenIfc->isValid(), "Failed to get listen session"); delete listenIfc; // Test properties sensorIfc->setInterval(100); QVERIFY(sensorIfc->orientation() == qvariant_cast<Unsigned>(sensorIfc->property("orientation"))); // test start QDBusReply<void> reply = sensorIfc->start(); QVERIFY(reply.isValid()); // test stop reply = sensorIfc->stop(); QVERIFY(reply.isValid()); delete sensorIfc; } void ClientApiTest::testAccelerometerSensor() { QString sensorName("accelerometersensor"); SensorManagerInterface& sm = SensorManagerInterface::instance(); QVERIFY( sm.isValid() ); // Get control session AccelerometerSensorChannelInterface* sensorIfc = AccelerometerSensorChannelInterface::controlInterface(sensorName); QVERIFY2(sensorIfc && sensorIfc->isValid(), "Failed to get control session"); // Attempt to get another control session AccelerometerSensorChannelInterface* failIfc = AccelerometerSensorChannelInterface::controlInterface(sensorName); QVERIFY2(!failIfc, "Got another control session"); // Get listen session const AccelerometerSensorChannelInterface* listenIfc = AccelerometerSensorChannelInterface::listenInterface(sensorName); QVERIFY2(listenIfc && listenIfc->isValid(), "Failed to get listen session"); delete listenIfc; // Test properties sensorIfc->setInterval(100); // test start QDBusReply<void> reply = sensorIfc->start(); QVERIFY(reply.isValid()); // test stop reply = sensorIfc->stop(); QVERIFY(reply.isValid()); XYZ sample1 = sensorIfc->get(); XYZ sample2 = qvariant_cast<XYZ>(sensorIfc->property("value")); QVERIFY(sample1 == sample2); delete sensorIfc; } void ClientApiTest::testMagnetometerSensor() { QString sensorName("magnetometersensor"); SensorManagerInterface& sm = SensorManagerInterface::instance(); QVERIFY( sm.isValid() ); // Get control session MagnetometerSensorChannelInterface* sensorIfc = MagnetometerSensorChannelInterface::controlInterface(sensorName); QVERIFY2(sensorIfc && sensorIfc->isValid(), "Failed to get control session"); // Attempt to get another control session MagnetometerSensorChannelInterface* failIfc = MagnetometerSensorChannelInterface::controlInterface(sensorName); QVERIFY2(!failIfc, "Got another control session"); // Get listen session const MagnetometerSensorChannelInterface* listenIfc = MagnetometerSensorChannelInterface::listenInterface(sensorName); QVERIFY2(listenIfc && listenIfc->isValid(), "Failed to get listen session"); delete listenIfc; // Test properties sensorIfc->setInterval(100); // Need simulated data to make sensible test ouf of this. MagneticField sample1 = sensorIfc->magneticField(); MagneticField sample2 = qvariant_cast<MagneticField>(sensorIfc->property("magneticField")); // Background process keeps magnetometer on -- values are changing, and subsequent // calls are likely to give different values. This makes thus no sense. // QVERIFY(sample1 == sample2); // test start QDBusReply<void> reply = sensorIfc->start(); QVERIFY(reply.isValid()); // test stop reply = sensorIfc->stop(); QVERIFY(reply.isValid()); delete sensorIfc; } void ClientApiTest::testCompassSensor() { QString sensorName("compasssensor"); SensorManagerInterface& sm = SensorManagerInterface::instance(); QVERIFY( sm.isValid() ); // Get control session CompassSensorChannelInterface* sensorIfc = CompassSensorChannelInterface::controlInterface(sensorName); QVERIFY2(sensorIfc && sensorIfc->isValid(), "Failed to get control session"); // Attempt to get another control session CompassSensorChannelInterface* failIfc = CompassSensorChannelInterface::controlInterface(sensorName); QVERIFY2(!failIfc, "Got another control session"); // Get listen session const CompassSensorChannelInterface* listenIfc = CompassSensorChannelInterface::listenInterface(sensorName); QVERIFY2(listenIfc && listenIfc->isValid(), "Failed to get listen session"); delete listenIfc; // Test properties sensorIfc->setInterval(100); QVERIFY(sensorIfc->get() == qvariant_cast<Compass>(sensorIfc->property("value"))); QVERIFY(sensorIfc->useDeclination() == sensorIfc->property("usedeclination")); QVERIFY(sensorIfc->declinationValue() == sensorIfc->property("declinationvalue")); // Check declination on/off bool declinationInUse = sensorIfc->useDeclination(); sensorIfc->setUseDeclination(!declinationInUse); QVERIFY(declinationInUse != sensorIfc->useDeclination()); sensorIfc->setUseDeclination(!declinationInUse); // TODO: Compare declination value against value in gconf // test start QDBusReply<void> reply = sensorIfc->start(); QVERIFY(reply.isValid()); // test stop reply = sensorIfc->stop(); QVERIFY(reply.isValid()); delete sensorIfc; } void ClientApiTest::testTapSensor() { QString sensorName("tapsensor"); SensorManagerInterface& sm = SensorManagerInterface::instance(); QVERIFY( sm.isValid() ); // Get control session TapSensorChannelInterface* sensorIfc = TapSensorChannelInterface::controlInterface(sensorName); QVERIFY2(sensorIfc && sensorIfc->isValid(), "Failed to get control session"); // Attempt to get another control session TapSensorChannelInterface* failIfc = TapSensorChannelInterface::controlInterface(sensorName); QVERIFY2(!failIfc, "Got another control session"); // Get listen session const TapSensorChannelInterface* listenIfc = TapSensorChannelInterface::listenInterface(sensorName); QVERIFY2(listenIfc && listenIfc->isValid(), "Failed to get listen session"); delete listenIfc; // Test properties sensorIfc->setInterval(100); // test start QDBusReply<void> reply = sensorIfc->start(); QVERIFY(reply.isValid()); // test stop reply = sensorIfc->stop(); QVERIFY(reply.isValid()); delete sensorIfc; } void ClientApiTest::testALSSensor() { QString sensorName("alssensor"); SensorManagerInterface& sm = SensorManagerInterface::instance(); QVERIFY( sm.isValid() ); // Get control session // TODO: Because context takes control over ALS in sensord::main(), // we can't test this. (applies to all other possible open // sessions too...) //ALSSensorChannelInterface* sensorIfc = ALSSensorChannelInterface::controlInterface(sensorName); //QVERIFY2(sensorIfc && sensorIfc->isValid(), "Failed to get control session"); // Attempt to get another control session ALSSensorChannelInterface* failIfc = ALSSensorChannelInterface::controlInterface(sensorName); QVERIFY2(!failIfc, "Got another control session"); // Get listen session const ALSSensorChannelInterface* listenIfc = ALSSensorChannelInterface::listenInterface(sensorName); QVERIFY2(listenIfc && listenIfc->isValid(), "Failed to get listen session"); delete listenIfc; // Test properties //sensorIfc->setInterval(100); // test start //QDBusReply<void> reply = sensorIfc->start(); //QVERIFY(reply.isValid()); // test stop //reply = sensorIfc->stop(); //QVERIFY(reply.isValid()); //delete sensorIfc; } void ClientApiTest::testProximitySensor() { QString sensorName("proximitysensor"); SensorManagerInterface& sm = SensorManagerInterface::instance(); QVERIFY( sm.isValid() ); // Get control session ProximitySensorChannelInterface* sensorIfc = ProximitySensorChannelInterface::controlInterface(sensorName); QVERIFY2(sensorIfc && sensorIfc->isValid(), "Failed to get control session"); // Attempt to get another control session ProximitySensorChannelInterface* failIfc = ProximitySensorChannelInterface::controlInterface(sensorName); QVERIFY2(!failIfc, "Got another control session"); // Get listen session const ProximitySensorChannelInterface* listenIfc = ProximitySensorChannelInterface::listenInterface(sensorName); QVERIFY2(listenIfc && listenIfc->isValid(), "Failed to get listen session"); delete listenIfc; // Test properties sensorIfc->setInterval(100); // test start QDBusReply<void> reply = sensorIfc->start(); QVERIFY(reply.isValid()); // test stop reply = sensorIfc->stop(); QVERIFY(reply.isValid()); delete sensorIfc; } void ClientApiTest::testRotationSensor() { QString sensorName("rotationsensor"); SensorManagerInterface& sm = SensorManagerInterface::instance(); QVERIFY( sm.isValid() ); // Get control session RotationSensorChannelInterface* sensorIfc = RotationSensorChannelInterface::controlInterface(sensorName); QVERIFY2(sensorIfc && sensorIfc->isValid(), "Failed to get control session"); // Attempt to get another control session RotationSensorChannelInterface* failIfc = RotationSensorChannelInterface::controlInterface(sensorName); QVERIFY2(!failIfc, "Got another control session"); // Get listen session const RotationSensorChannelInterface* listenIfc = RotationSensorChannelInterface::listenInterface(sensorName); QVERIFY2(listenIfc && listenIfc->isValid(), "Failed to get listen session"); delete listenIfc; // Test properties sensorIfc->setInterval(100); bool hasz = sensorIfc->hasZ(); qDebug() << "Z-axis rotation calculations in use:" << hasz; // Need simulated data to make sensible test ouf of this. XYZ sample1 = sensorIfc->rotation(); XYZ sample2 = qvariant_cast<XYZ>(sensorIfc->property("rotation")); QVERIFY(sample1 == sample2); // test start QDBusReply<void> reply = sensorIfc->start(); QVERIFY(reply.isValid()); // test stop reply = sensorIfc->stop(); QVERIFY(reply.isValid()); delete sensorIfc; } /** * Runs two sensors using the same adaptor/chain simultaneously. * * For the sake of testing, OrientationSensor and AccelerometerSensor are * used. AccelerometerChain is shared. * * @note Sensord hacks starting context framework things might affect this by * adding other sensors that use the same adaptor. */ void ClientApiTest::testCommonAdaptorPipeline() { int DELAY = 250; OrientationSensorChannelInterface *orientation; AccelerometerSensorChannelInterface *accelerometer; orientation = OrientationSensorChannelInterface::controlInterface("orientationsensor"); QVERIFY2(orientation && orientation->isValid(), "Could not get orientation sensor control channel"); orientation->setInterval(100); orientation->start(); qDebug() << "Orientation sensor started, waiting for" << DELAY << "ms."; QTest::qWait(DELAY); accelerometer = AccelerometerSensorChannelInterface::controlInterface("accelerometersensor"); QVERIFY2(accelerometer && accelerometer->isValid(), "Could not get accelerometer sensor control channel"); accelerometer->setInterval(100); accelerometer->start(); qDebug() << "Accelerometer sensor started, waiting for" << DELAY << "ms."; QTest::qWait(DELAY); orientation->stop(); qDebug() << "Orientation sensor stopped, waiting for" << DELAY << "ms."; QTest::qWait(DELAY); delete orientation; qDebug() << "Orientation sensor destroyed, waiting for" << DELAY << "ms."; QTest::qWait(DELAY); accelerometer->stop(); qDebug() << "Accelerometer sensor stopped."; delete accelerometer; } void ClientApiTest::testListenSessionInitiation() { const OrientationSensorChannelInterface *orientation; orientation = OrientationSensorChannelInterface::listenInterface("orientationsensor"); QVERIFY2(orientation && orientation->isValid(), "Could not get orientation sensor listen channel"); } QTEST_MAIN(ClientApiTest) <|endoftext|>
<commit_before>#include <map> #include <unistd.h> #include "database.hpp" #include "cmap.hpp" #define MAX_COLLECTIONS 100 #define WRITE_INTERVAL 30 using namespace std; static int backup = -1; struct Coll { pthread_mutex_t mutex; string name; cmap<int,JSON> documents; Coll() : mutex(PTHREAD_MUTEX_INITIALIZER) {} void read() { // this function is called only once, by a locked piece of code JSON tmp; if (!tmp.read_file("database/"+name+".json")) return; for (auto& doc : tmp.arr()) documents[doc("_id")] = doc("document"); } void write() { JSON tmp(vector<JSON>{}); pthread_mutex_lock(&mutex); for (auto& kv : documents) tmp.emplace_back(move(map<string,JSON>{ {"_id" , kv.first}, {"document" , kv.second} })); pthread_mutex_unlock(&mutex); tmp.write_file("database/"+name+".json"); } int create(JSON&& doc) { int id = 1; pthread_mutex_lock(&mutex); if (documents.size() > 0) id += documents.max_key(); documents[id] = move(doc); pthread_mutex_unlock(&mutex); return id; } bool retrieve(int id, JSON& doc) { pthread_mutex_lock(&mutex); auto it = documents.find(id); if (it == documents.end()) { doc.setnull(); pthread_mutex_unlock(&mutex); return false; } doc = it->second; pthread_mutex_unlock(&mutex); return true; } JSON retrieve(const JSON& filter) { JSON ans(vector<JSON>{}); pthread_mutex_lock(&mutex); for (auto& kv : documents) if (filter.issubobj(kv.second)) { JSON tmp = kv.second; tmp["id"] = kv.first; ans.push_back(move(tmp)); } pthread_mutex_unlock(&mutex); return ans; } JSON retrieve_page(unsigned p, unsigned ps) { JSON ans(vector<JSON>{}); pthread_mutex_lock(&mutex); if (!ps) p = 0, ps = documents.size(); auto it = documents.at(p*ps); for (int i = 0; i < ps && it != documents.end(); i++, it++) { JSON tmp = it->second; tmp["id"] = it->first; ans.push_back(move(tmp)); } pthread_mutex_unlock(&mutex); return ans; } bool update(int id, JSON&& doc) { pthread_mutex_lock(&mutex); auto it = documents.find(id); if (it == documents.end()) { pthread_mutex_unlock(&mutex); return false; } it->second = move(doc); pthread_mutex_unlock(&mutex); return true; } bool update(const Database::Updater& upd, int id) { bool ans = false; pthread_mutex_lock(&mutex); auto it = documents.find(id); if (it != documents.end()) { ans = upd(*it); pthread_mutex_unlock(&mutex); return ans; } for (auto& kv : documents) ans = ans || upd(kv); pthread_mutex_unlock(&mutex); return ans; } bool destroy(int id) { pthread_mutex_lock(&mutex); auto it = documents.find(id); if (it == documents.end()) { pthread_mutex_unlock(&mutex); return false; } documents.erase(it); pthread_mutex_unlock(&mutex); return true; } }; static Coll collection[MAX_COLLECTIONS]; static int ncolls = 0; static pthread_mutex_t colls_mutex = PTHREAD_MUTEX_INITIALIZER; static int get(const string& name) { static map<string,int> colls; int i; pthread_mutex_lock(&colls_mutex); auto it = colls.find(name); if (it != colls.end()) { i = it->second; pthread_mutex_unlock(&colls_mutex); return i; } i = ncolls++; colls[name] = i; collection[i].name = name; collection[i].read(); pthread_mutex_unlock(&colls_mutex); return i; } // thread static bool quit = false; static pthread_t db; static void do_backup() { stringstream ss; ss << "backup" << backup; system(("mkdir -p database/"+ss.str()).c_str()); system(("cp database/*.json database/"+ss.str()).c_str()); } static void update() { int nc; pthread_mutex_lock(&colls_mutex); nc = ncolls; pthread_mutex_unlock(&colls_mutex); for (int i = 0; i < nc; i++) collection[i].write(); if (backup < 0) return; do_backup(); backup = 1-backup; } static void* thread(void*) { static time_t upd = 0; while (!quit) { if (upd <= time(nullptr)) { update(); upd = time(nullptr)+WRITE_INTERVAL; } usleep(100000); } } namespace Database { Collection::Collection(const string& name) : collid(get(name)) { } int Collection::create(const JSON& document) { JSON tmp(document); return collection[collid].create(move(tmp)); } int Collection::create(JSON&& document) { return collection[collid].create(move(document)); } JSON Collection::retrieve(int docid) { JSON ans; collection[collid].retrieve(docid,ans); return ans; } bool Collection::retrieve(int docid, JSON& document) { return collection[collid].retrieve(docid,document); } JSON Collection::retrieve(const JSON& filter) { return collection[collid].retrieve(filter); } JSON Collection::retrieve_page(unsigned page,unsigned page_size) { return collection[collid].retrieve_page(page,page_size); } bool Collection::update(int docid, const JSON& document) { JSON tmp(document); return collection[collid].update(docid,move(tmp)); } bool Collection::update(int docid, JSON&& document) { return collection[collid].update(docid,move(document)); } bool Collection::update(const Updater& upd, int docid) { return collection[collid].update(upd,docid); } bool Collection::destroy(int docid) { return collection[collid].destroy(docid); } void init(bool backup) { if (backup) ::backup = 0; system("mkdir -p database"); pthread_create(&db,nullptr,thread,nullptr); } void close() { quit = true; pthread_join(db,nullptr); update(); } } // namespace Database <commit_msg>Flushing disk after database write<commit_after>#include <map> #include <unistd.h> #include "database.hpp" #include "cmap.hpp" #define MAX_COLLECTIONS 100 #define WRITE_INTERVAL 30 using namespace std; static int backup = -1; struct Coll { pthread_mutex_t mutex; string name; cmap<int,JSON> documents; Coll() : mutex(PTHREAD_MUTEX_INITIALIZER) {} void read() { // this function is called only once, by a locked piece of code JSON tmp; if (!tmp.read_file("database/"+name+".json")) return; for (auto& doc : tmp.arr()) documents[doc("_id")] = doc("document"); } void write() { JSON tmp(vector<JSON>{}); pthread_mutex_lock(&mutex); for (auto& kv : documents) tmp.emplace_back(move(map<string,JSON>{ {"_id" , kv.first}, {"document" , kv.second} })); pthread_mutex_unlock(&mutex); tmp.write_file("database/"+name+".json"); } int create(JSON&& doc) { int id = 1; pthread_mutex_lock(&mutex); if (documents.size() > 0) id += documents.max_key(); documents[id] = move(doc); pthread_mutex_unlock(&mutex); return id; } bool retrieve(int id, JSON& doc) { pthread_mutex_lock(&mutex); auto it = documents.find(id); if (it == documents.end()) { doc.setnull(); pthread_mutex_unlock(&mutex); return false; } doc = it->second; pthread_mutex_unlock(&mutex); return true; } JSON retrieve(const JSON& filter) { JSON ans(vector<JSON>{}); pthread_mutex_lock(&mutex); for (auto& kv : documents) if (filter.issubobj(kv.second)) { JSON tmp = kv.second; tmp["id"] = kv.first; ans.push_back(move(tmp)); } pthread_mutex_unlock(&mutex); return ans; } JSON retrieve_page(unsigned p, unsigned ps) { JSON ans(vector<JSON>{}); pthread_mutex_lock(&mutex); if (!ps) p = 0, ps = documents.size(); auto it = documents.at(p*ps); for (int i = 0; i < ps && it != documents.end(); i++, it++) { JSON tmp = it->second; tmp["id"] = it->first; ans.push_back(move(tmp)); } pthread_mutex_unlock(&mutex); return ans; } bool update(int id, JSON&& doc) { pthread_mutex_lock(&mutex); auto it = documents.find(id); if (it == documents.end()) { pthread_mutex_unlock(&mutex); return false; } it->second = move(doc); pthread_mutex_unlock(&mutex); return true; } bool update(const Database::Updater& upd, int id) { bool ans = false; pthread_mutex_lock(&mutex); auto it = documents.find(id); if (it != documents.end()) { ans = upd(*it); pthread_mutex_unlock(&mutex); return ans; } for (auto& kv : documents) ans = ans || upd(kv); pthread_mutex_unlock(&mutex); return ans; } bool destroy(int id) { pthread_mutex_lock(&mutex); auto it = documents.find(id); if (it == documents.end()) { pthread_mutex_unlock(&mutex); return false; } documents.erase(it); pthread_mutex_unlock(&mutex); return true; } }; static Coll collection[MAX_COLLECTIONS]; static int ncolls = 0; static pthread_mutex_t colls_mutex = PTHREAD_MUTEX_INITIALIZER; static int get(const string& name) { static map<string,int> colls; int i; pthread_mutex_lock(&colls_mutex); auto it = colls.find(name); if (it != colls.end()) { i = it->second; pthread_mutex_unlock(&colls_mutex); return i; } i = ncolls++; colls[name] = i; collection[i].name = name; collection[i].read(); pthread_mutex_unlock(&colls_mutex); return i; } // thread static bool quit = false; static pthread_t db; static void do_backup() { if (backup < 0) return; stringstream ss; ss << "backup" << backup; system(("mkdir -p database/"+ss.str()).c_str()); system(("cp database/*.json database/"+ss.str()).c_str()); backup = 1-backup; } static void update() { int nc; pthread_mutex_lock(&colls_mutex); nc = ncolls; pthread_mutex_unlock(&colls_mutex); for (int i = 0; i < nc; i++) collection[i].write(); do_backup(); sync(); } static void* thread(void*) { static time_t upd = 0; while (!quit) { if (upd <= time(nullptr)) { update(); upd = time(nullptr)+WRITE_INTERVAL; } usleep(100000); } } namespace Database { Collection::Collection(const string& name) : collid(get(name)) { } int Collection::create(const JSON& document) { JSON tmp(document); return collection[collid].create(move(tmp)); } int Collection::create(JSON&& document) { return collection[collid].create(move(document)); } JSON Collection::retrieve(int docid) { JSON ans; collection[collid].retrieve(docid,ans); return ans; } bool Collection::retrieve(int docid, JSON& document) { return collection[collid].retrieve(docid,document); } JSON Collection::retrieve(const JSON& filter) { return collection[collid].retrieve(filter); } JSON Collection::retrieve_page(unsigned page,unsigned page_size) { return collection[collid].retrieve_page(page,page_size); } bool Collection::update(int docid, const JSON& document) { JSON tmp(document); return collection[collid].update(docid,move(tmp)); } bool Collection::update(int docid, JSON&& document) { return collection[collid].update(docid,move(document)); } bool Collection::update(const Updater& upd, int docid) { return collection[collid].update(upd,docid); } bool Collection::destroy(int docid) { return collection[collid].destroy(docid); } void init(bool backup) { if (backup) ::backup = 0; system("mkdir -p database"); pthread_create(&db,nullptr,thread,nullptr); } void close() { quit = true; pthread_join(db,nullptr); update(); } } // namespace Database <|endoftext|>
<commit_before>#include "rubymotion.h" #include "motion-game.h" /// @class Director < Object /// Director is a shared object that takes care of the scene graph. VALUE rb_cDirector = Qnil; static VALUE mc_director_instance = Qnil; static std::vector<VALUE> director_using_scene(3); /// @group Constructors /// @method .shared /// @return [Director] the shared Director instance. static VALUE director_instance(VALUE rcv, SEL sel) { if (mc_director_instance == Qnil) { VALUE obj = rb_cocos2d_object_new(cocos2d::Director::getInstance(), rb_cDirector); mc_director_instance = rb_retain(obj); } return mc_director_instance; } #if CC_TARGET_OS_IPHONE || CC_TARGET_OS_APPLETV static VALUE director_view_set(VALUE rcv, SEL sel, VALUE obj) { cocos2d::GLView *glview = cocos2d::GLViewImpl::createWithEAGLView((void *)obj); DIRECTOR(rcv)->setOpenGLView(glview); return obj; } static VALUE director_view_get(VALUE rcv, SEL sel) { return (VALUE)DIRECTOR(rcv)->getOpenGLView()->getEAGLView(); } #endif /// @group Managing Scenes /// @method #run(scene) /// Runs the given scene object. /// @param scene [Scene] the scene to run. /// @return [Director] the receiver. static VALUE director_run(VALUE rcv, SEL sel, VALUE obj) { director_using_scene[0] = rb_retain(obj); DIRECTOR(rcv)->runWithScene(rb_any_to_scene(obj)); return rcv; } /// @method #replace(scene) /// Replaces the current scene with a new one. The running scene will be /// terminated. /// @param scene [Scene] the scene to replace the current one with. /// @return [Director] the receiver. static VALUE director_replace(VALUE rcv, SEL sel, VALUE obj) { rb_release(director_using_scene[0]); director_using_scene[0] = rb_retain(obj); DIRECTOR(rcv)->replaceScene(rb_any_to_scene(obj)); return rcv; } /// @method #push(scene) /// Suspends the execution of the running scene, and starts running the given /// scene instead. /// @param scene [Scene] the new scene to run. /// @return [Director] the receiver. static VALUE director_push(VALUE rcv, SEL sel, VALUE obj) { director_using_scene.push_back(rb_retain(obj)); DIRECTOR(rcv)->pushScene(rb_any_to_scene(obj)); return rcv; } /// @method #pop /// Pops the running scene from the stack, and starts running the previous /// scene. If there are no more scenes to run, the execution will be stopped. /// @return [Director] the receiver. static VALUE director_pop(VALUE rcv, SEL sel) { VALUE last_scene = director_using_scene.back(); director_using_scene.pop_back(); rb_release(last_scene); DIRECTOR(rcv)->popScene(); return rcv; } /// @method #end /// Ends the execution of the running scene. /// @return [Director] the receiver. static VALUE director_end(VALUE rcv, SEL sel) { for (auto iter = director_using_scene.begin(); iter != director_using_scene.end(); ++iter) { if (*iter != 0) { rb_release(*iter); *iter = 0; } } DIRECTOR(rcv)->end(); return rcv; } /// @method #pause /// Pauses the execution of the running scene. /// @return [Director] the receiver. static VALUE director_pause(VALUE rcv, SEL sel) { DIRECTOR(rcv)->pause(); return rcv; } /// @method #resume /// Resumes the execution of the current paused scene. /// @return [Director] the receiver. static VALUE director_resume(VALUE rcv, SEL sel) { DIRECTOR(rcv)->resume(); return rcv; } /// @method #start_animation /// The main loop is triggered again. /// @return [Director] the receiver. static VALUE director_start_animation(VALUE rcv, SEL sel) { DIRECTOR(rcv)->startAnimation(); return rcv; } /// @method #stop_animation /// Stops the animation. /// @return [Director] the receiver. static VALUE director_stop_animation(VALUE rcv, SEL sel) { DIRECTOR(rcv)->stopAnimation(); return rcv; } /// @group Properties /// @property-readonly #origin /// @return [Point] the visible origin of the director view in points. static VALUE director_origin(VALUE rcv, SEL sel) { return rb_ccvec2_to_obj(DIRECTOR(rcv)->getVisibleOrigin()); } /// @property-readonly #size /// @return [Size] the visible size of the director view in points. static VALUE director_size(VALUE rcv, SEL sel) { return rb_ccsize_to_obj(DIRECTOR(rcv)->getVisibleSize()); } /// @property #show_stats? /// Controls whether the FPS (frame-per-second) statistic label is displayed /// in the bottom-left corner of the director view. By default it is hidden. /// @return [Boolean] whether the FPS label is displayed. static VALUE director_show_stats_set(VALUE rcv, SEL sel, VALUE val) { DIRECTOR(rcv)->setDisplayStats(RTEST(val)); return val; } static VALUE director_show_stats(VALUE rcv, SEL sel) { return DIRECTOR(rcv)->isDisplayStats() ? Qtrue : Qfalse; } extern "C" void Init_Director(void) { rb_cDirector = rb_define_class_under(rb_mMC, "Director", rb_cObject); rb_define_singleton_method(rb_cDirector, "shared", director_instance, 0); rb_define_method(rb_cDirector, "run", director_run, 1); rb_define_method(rb_cDirector, "replace", director_replace, 1); rb_define_method(rb_cDirector, "push", director_push, 1); rb_define_method(rb_cDirector, "pop", director_pop, 0); rb_define_method(rb_cDirector, "end", director_end, 0); rb_define_method(rb_cDirector, "pause", director_pause, 0); rb_define_method(rb_cDirector, "resume", director_resume, 0); rb_define_method(rb_cDirector, "start_animation", director_start_animation, 0); rb_define_method(rb_cDirector, "stop_animation", director_stop_animation, 0); rb_define_method(rb_cDirector, "origin", director_origin, 0); rb_define_method(rb_cDirector, "size", director_size, 0); rb_define_method(rb_cDirector, "show_stats=", director_show_stats_set, 1); rb_define_method(rb_cDirector, "show_stats?", director_show_stats, 0); // Internal. #if CC_TARGET_OS_IPHONE || CC_TARGET_OS_APPLETV rb_define_method(rb_cDirector, "_set_glview", director_view_set, 1); rb_define_method(rb_cDirector, "_get_glview", director_view_get, 0); #endif } <commit_msg>add missing documents<commit_after>#include "rubymotion.h" #include "motion-game.h" /// @class Director < Object /// Director is a shared object that takes care of the scene graph. VALUE rb_cDirector = Qnil; static VALUE mc_director_instance = Qnil; static std::vector<VALUE> director_using_scene(3); /// @group Constructors /// @method .shared /// @return [Director] the shared Director instance. static VALUE director_instance(VALUE rcv, SEL sel) { if (mc_director_instance == Qnil) { VALUE obj = rb_cocos2d_object_new(cocos2d::Director::getInstance(), rb_cDirector); mc_director_instance = rb_retain(obj); } return mc_director_instance; } #if CC_TARGET_OS_IPHONE || CC_TARGET_OS_APPLETV static VALUE director_view_set(VALUE rcv, SEL sel, VALUE obj) { cocos2d::GLView *glview = cocos2d::GLViewImpl::createWithEAGLView((void *)obj); DIRECTOR(rcv)->setOpenGLView(glview); return obj; } static VALUE director_view_get(VALUE rcv, SEL sel) { return (VALUE)DIRECTOR(rcv)->getOpenGLView()->getEAGLView(); } #endif /// @group Managing Scenes /// @method #run(scene) /// Runs the given scene object. /// @param scene [Scene] the scene to run. /// @return [Director] the receiver. static VALUE director_run(VALUE rcv, SEL sel, VALUE obj) { director_using_scene[0] = rb_retain(obj); DIRECTOR(rcv)->runWithScene(rb_any_to_scene(obj)); return rcv; } /// @method #replace(scene) /// Replaces the current scene with a new one. The running scene will be /// terminated. /// @param scene [Scene] the scene to replace the current one with. /// @return [Director] the receiver. static VALUE director_replace(VALUE rcv, SEL sel, VALUE obj) { rb_release(director_using_scene[0]); director_using_scene[0] = rb_retain(obj); DIRECTOR(rcv)->replaceScene(rb_any_to_scene(obj)); return rcv; } /// @method #push(scene) /// Suspends the execution of the running scene, and starts running the given /// scene instead. /// @param scene [Scene] the new scene to run. /// @return [Director] the receiver. static VALUE director_push(VALUE rcv, SEL sel, VALUE obj) { director_using_scene.push_back(rb_retain(obj)); DIRECTOR(rcv)->pushScene(rb_any_to_scene(obj)); return rcv; } /// @method #pop /// Pops the running scene from the stack, and starts running the previous /// scene. If there are no more scenes to run, the execution will be stopped. /// @return [Director] the receiver. static VALUE director_pop(VALUE rcv, SEL sel) { VALUE last_scene = director_using_scene.back(); director_using_scene.pop_back(); rb_release(last_scene); DIRECTOR(rcv)->popScene(); return rcv; } /// @method #end /// Ends the execution of the running scene. /// @return [Director] the receiver. static VALUE director_end(VALUE rcv, SEL sel) { for (auto iter = director_using_scene.begin(); iter != director_using_scene.end(); ++iter) { if (*iter != 0) { rb_release(*iter); *iter = 0; } } DIRECTOR(rcv)->end(); return rcv; } /// @method #pause /// Pauses the execution of the running scene. /// @return [Director] the receiver. static VALUE director_pause(VALUE rcv, SEL sel) { DIRECTOR(rcv)->pause(); return rcv; } /// @method #resume /// Resumes the execution of the current paused scene. /// @return [Director] the receiver. static VALUE director_resume(VALUE rcv, SEL sel) { DIRECTOR(rcv)->resume(); return rcv; } /// @method #start_animation /// The main loop is triggered again. /// @return [Director] the receiver. static VALUE director_start_animation(VALUE rcv, SEL sel) { DIRECTOR(rcv)->startAnimation(); return rcv; } /// @method #stop_animation /// Stops the animation. /// @return [Director] the receiver. static VALUE director_stop_animation(VALUE rcv, SEL sel) { DIRECTOR(rcv)->stopAnimation(); return rcv; } /// @group Properties /// @property-readonly #origin /// @return [Point] the visible origin of the director view in points. static VALUE director_origin(VALUE rcv, SEL sel) { return rb_ccvec2_to_obj(DIRECTOR(rcv)->getVisibleOrigin()); } /// @property-readonly #size /// @return [Size] the visible size of the director view in points. static VALUE director_size(VALUE rcv, SEL sel) { return rb_ccsize_to_obj(DIRECTOR(rcv)->getVisibleSize()); } /// @method #show_stats=(value) /// @param value [Boolean] true if display the FPS label. /// Controls whether the FPS (frame-per-second) statistic label is displayed /// in the bottom-left corner of the director view. By default it is hidden. static VALUE director_show_stats_set(VALUE rcv, SEL sel, VALUE val) { DIRECTOR(rcv)->setDisplayStats(RTEST(val)); return val; } /// @property-readonly #show_stats? /// Controls whether the FPS (frame-per-second) statistic label is displayed /// in the bottom-left corner of the director view. By default it is hidden. /// @return [Boolean] whether the FPS label is displayed. static VALUE director_show_stats(VALUE rcv, SEL sel) { return DIRECTOR(rcv)->isDisplayStats() ? Qtrue : Qfalse; } extern "C" void Init_Director(void) { rb_cDirector = rb_define_class_under(rb_mMC, "Director", rb_cObject); rb_define_singleton_method(rb_cDirector, "shared", director_instance, 0); rb_define_method(rb_cDirector, "run", director_run, 1); rb_define_method(rb_cDirector, "replace", director_replace, 1); rb_define_method(rb_cDirector, "push", director_push, 1); rb_define_method(rb_cDirector, "pop", director_pop, 0); rb_define_method(rb_cDirector, "end", director_end, 0); rb_define_method(rb_cDirector, "pause", director_pause, 0); rb_define_method(rb_cDirector, "resume", director_resume, 0); rb_define_method(rb_cDirector, "start_animation", director_start_animation, 0); rb_define_method(rb_cDirector, "stop_animation", director_stop_animation, 0); rb_define_method(rb_cDirector, "origin", director_origin, 0); rb_define_method(rb_cDirector, "size", director_size, 0); rb_define_method(rb_cDirector, "show_stats=", director_show_stats_set, 1); rb_define_method(rb_cDirector, "show_stats?", director_show_stats, 0); // Internal. #if CC_TARGET_OS_IPHONE || CC_TARGET_OS_APPLETV rb_define_method(rb_cDirector, "_set_glview", director_view_set, 1); rb_define_method(rb_cDirector, "_get_glview", director_view_get, 0); #endif } <|endoftext|>
<commit_before>// // Copyright © 2017 Arm Ltd. All rights reserved. // SPDX-License-Identifier: MIT // #include <boost/test/unit_test.hpp> #include <armnn/ArmNN.hpp> #include <Graph.hpp> #include <SubgraphView.hpp> #include <SubgraphViewSelector.hpp> #include <backendsCommon/OptimizationViews.hpp> #include <Network.hpp> #include "CommonTestUtils.hpp" using namespace armnn; BOOST_AUTO_TEST_SUITE(OptimizationViewsTestSuite) BOOST_AUTO_TEST_CASE(OptimizedViewsSubgraphLayerCount) { OptimizationViews view; // Construct a graph with 3 layers Graph& baseGraph = view.GetGraph(); Layer* const inputLayer = baseGraph.AddLayer<InputLayer>(0, "input"); Convolution2dDescriptor convDescriptor; PreCompiledDescriptor substitutionLayerDescriptor(1, 1); Layer* const convLayer1 = baseGraph.AddLayer<Convolution2dLayer>(convDescriptor, "conv1"); Layer* const convLayer2 = baseGraph.AddLayer<Convolution2dLayer>(convDescriptor, "conv2"); Layer* const substitutableCompiledLayer = baseGraph.AddLayer<PreCompiledLayer>(substitutionLayerDescriptor, "pre-compiled"); Layer* const outputLayer = baseGraph.AddLayer<OutputLayer>(0, "output"); inputLayer->GetOutputSlot(0).Connect(convLayer1->GetInputSlot(0)); convLayer1->GetOutputSlot(0).Connect(convLayer2->GetInputSlot(0)); convLayer2->GetOutputSlot(0).Connect(outputLayer->GetInputSlot(0)); // Subgraph for a failed layer SubgraphViewSelector::SubgraphViewPtr failedSubgraph = CreateSubgraphViewFrom(CreateInputsFrom({convLayer1}), CreateOutputsFrom({convLayer1}), {convLayer1}); // Subgraph for an untouched layer SubgraphViewSelector::SubgraphViewPtr untouchedSubgraph = CreateSubgraphViewFrom(CreateInputsFrom({convLayer2}), CreateOutputsFrom({convLayer2}), {convLayer2}); // Subgraph for a substitutable layer SubgraphViewSelector::SubgraphViewPtr substitutableSubgraph = CreateSubgraphViewFrom(CreateInputsFrom({convLayer1}), CreateOutputsFrom({convLayer2}), {substitutableCompiledLayer}); // Create a Graph containing a layer to substitute in Graph substitutableGraph; Layer* const substitutionpreCompiledLayer = substitutableGraph.AddLayer<PreCompiledLayer>(substitutionLayerDescriptor, "pre-compiled"); // Subgraph for a substitution layer SubgraphViewSelector::SubgraphViewPtr substitutionSubgraph = CreateSubgraphViewFrom(CreateInputsFrom({substitutionpreCompiledLayer}), CreateOutputsFrom({substitutionpreCompiledLayer}), {substitutionpreCompiledLayer}); // Sub in the graph baseGraph.SubstituteSubgraph(*substitutableSubgraph, *substitutionSubgraph); view.AddFailedSubgraph(SubgraphView(*failedSubgraph)); view.AddUntouchedSubgraph(SubgraphView(*untouchedSubgraph)); SubgraphViewSelector::SubgraphViewPtr baseSubgraph = CreateSubgraphViewFrom(CreateInputsFrom({convLayer1}), CreateOutputsFrom({convLayer2}), {substitutionpreCompiledLayer}); view.AddSubstitution({*baseSubgraph, *substitutionSubgraph}); // Construct original subgraph to compare against SubgraphViewSelector::SubgraphViewPtr originalSubgraph = CreateSubgraphViewFrom(CreateInputsFrom({convLayer1}), CreateOutputsFrom({convLayer2}), {convLayer1, convLayer2, substitutionpreCompiledLayer}); BOOST_CHECK(view.Validate(*originalSubgraph)); } BOOST_AUTO_TEST_CASE(OptimizedViewsSubgraphLayerCountFailValidate) { OptimizationViews view; // Construct a graph with 3 layers Graph& baseGraph = view.GetGraph(); Layer* const inputLayer = baseGraph.AddLayer<InputLayer>(0, "input"); Convolution2dDescriptor convDescriptor; PreCompiledDescriptor substitutionLayerDescriptor(1, 1); Layer* const convLayer1 = baseGraph.AddLayer<Convolution2dLayer>(convDescriptor, "conv1"); Layer* const convLayer2 = baseGraph.AddLayer<Convolution2dLayer>(convDescriptor, "conv2"); Layer* const substitutableCompiledLayer = baseGraph.AddLayer<PreCompiledLayer>(substitutionLayerDescriptor, "pre-compiled"); Layer* const outputLayer = baseGraph.AddLayer<OutputLayer>(0, "output"); inputLayer->GetOutputSlot(0).Connect(convLayer1->GetInputSlot(0)); convLayer1->GetOutputSlot(0).Connect(convLayer2->GetInputSlot(0)); convLayer2->GetOutputSlot(0).Connect(outputLayer->GetInputSlot(0)); // Subgraph for an untouched layer SubgraphViewSelector::SubgraphViewPtr untouchedSubgraph = CreateSubgraphViewFrom(CreateInputsFrom({convLayer2}), CreateOutputsFrom({convLayer2}), {convLayer2}); // Subgraph for a substitutable layer SubgraphViewSelector::SubgraphViewPtr substitutableSubgraph = CreateSubgraphViewFrom(CreateInputsFrom({convLayer1}), CreateOutputsFrom({convLayer2}), {substitutableCompiledLayer}); // Create a Graph containing a layer to substitute in Graph substitutableGraph; Layer* const substitutionpreCompiledLayer = substitutableGraph.AddLayer<PreCompiledLayer>(substitutionLayerDescriptor, "pre-compiled"); // Subgraph for a substitution layer SubgraphViewSelector::SubgraphViewPtr substitutionSubgraph = CreateSubgraphViewFrom(CreateInputsFrom({substitutionpreCompiledLayer}), CreateOutputsFrom({substitutionpreCompiledLayer}), {substitutionpreCompiledLayer}); // Sub in the graph baseGraph.SubstituteSubgraph(*substitutableSubgraph, *substitutionSubgraph); view.AddUntouchedSubgraph(SubgraphView(*untouchedSubgraph)); SubgraphViewSelector::SubgraphViewPtr baseSubgraph = CreateSubgraphViewFrom(CreateInputsFrom({convLayer1}), CreateOutputsFrom({convLayer2}), {substitutionpreCompiledLayer}); view.AddSubstitution({*baseSubgraph, *substitutionSubgraph}); // Construct original subgraph to compare against SubgraphViewSelector::SubgraphViewPtr originalSubgraph = CreateSubgraphViewFrom(CreateInputsFrom({convLayer1}), CreateOutputsFrom({convLayer2}), {convLayer1, convLayer2, substitutionpreCompiledLayer}); // Validate should fail as convLayer1 is not counted BOOST_CHECK(!view.Validate(*originalSubgraph)); } BOOST_AUTO_TEST_SUITE_END()<commit_msg>IVGCVSW-3033 Unit test using a MockBackend to validate Optimizer<commit_after>// // Copyright © 2017 Arm Ltd. All rights reserved. // SPDX-License-Identifier: MIT // #include <boost/test/unit_test.hpp> #include <armnn/ArmNN.hpp> #include <Graph.hpp> #include <SubgraphView.hpp> #include <SubgraphViewSelector.hpp> #include <backendsCommon/OptimizationViews.hpp> #include <Network.hpp> #include "CommonTestUtils.hpp" #include "MockBackend.hpp" using namespace armnn; void CheckLayers(Graph& graph) { unsigned int m_inputLayerCount = 0, m_outputLayerCount = 0, m_addLayerCount = 0; for(auto layer : graph) { switch(layer->GetType()) { case LayerType::Input: ++m_inputLayerCount; if (layer->GetGuid() == 0) { BOOST_TEST(layer->GetName() == "inLayer0"); } else if (layer->GetGuid() == 1) { BOOST_TEST(layer->GetName() == "inLayer1"); } break; // The Addition layer should become a PreCompiled Layer after Optimisation case LayerType::PreCompiled: ++m_addLayerCount; BOOST_TEST(layer->GetName() == "pre-compiled"); break; case LayerType::Output: ++m_outputLayerCount; BOOST_TEST(layer->GetName() == "outLayer"); break; default: //Fail for anything else BOOST_TEST(false); } } BOOST_TEST(m_inputLayerCount == 2); BOOST_TEST(m_outputLayerCount == 1); BOOST_TEST(m_addLayerCount == 1); } BOOST_AUTO_TEST_SUITE(OptimizationViewsTestSuite) BOOST_AUTO_TEST_CASE(OptimizedViewsSubgraphLayerCount) { OptimizationViews view; // Construct a graph with 3 layers Graph& baseGraph = view.GetGraph(); Layer* const inputLayer = baseGraph.AddLayer<InputLayer>(0, "input"); Convolution2dDescriptor convDescriptor; PreCompiledDescriptor substitutionLayerDescriptor(1, 1); Layer* const convLayer1 = baseGraph.AddLayer<Convolution2dLayer>(convDescriptor, "conv1"); Layer* const convLayer2 = baseGraph.AddLayer<Convolution2dLayer>(convDescriptor, "conv2"); Layer* const substitutableCompiledLayer = baseGraph.AddLayer<PreCompiledLayer>(substitutionLayerDescriptor, "pre-compiled"); Layer* const outputLayer = baseGraph.AddLayer<OutputLayer>(0, "output"); inputLayer->GetOutputSlot(0).Connect(convLayer1->GetInputSlot(0)); convLayer1->GetOutputSlot(0).Connect(convLayer2->GetInputSlot(0)); convLayer2->GetOutputSlot(0).Connect(outputLayer->GetInputSlot(0)); // Subgraph for a failed layer SubgraphViewSelector::SubgraphViewPtr failedSubgraph = CreateSubgraphViewFrom(CreateInputsFrom({convLayer1}), CreateOutputsFrom({convLayer1}), {convLayer1}); // Subgraph for an untouched layer SubgraphViewSelector::SubgraphViewPtr untouchedSubgraph = CreateSubgraphViewFrom(CreateInputsFrom({convLayer2}), CreateOutputsFrom({convLayer2}), {convLayer2}); // Subgraph for a substitutable layer SubgraphViewSelector::SubgraphViewPtr substitutableSubgraph = CreateSubgraphViewFrom(CreateInputsFrom({convLayer1}), CreateOutputsFrom({convLayer2}), {substitutableCompiledLayer}); // Create a Graph containing a layer to substitute in Graph substitutableGraph; Layer* const substitutionpreCompiledLayer = substitutableGraph.AddLayer<PreCompiledLayer>(substitutionLayerDescriptor, "pre-compiled"); // Subgraph for a substitution layer SubgraphViewSelector::SubgraphViewPtr substitutionSubgraph = CreateSubgraphViewFrom(CreateInputsFrom({substitutionpreCompiledLayer}), CreateOutputsFrom({substitutionpreCompiledLayer}), {substitutionpreCompiledLayer}); // Sub in the graph baseGraph.SubstituteSubgraph(*substitutableSubgraph, *substitutionSubgraph); view.AddFailedSubgraph(SubgraphView(*failedSubgraph)); view.AddUntouchedSubgraph(SubgraphView(*untouchedSubgraph)); SubgraphViewSelector::SubgraphViewPtr baseSubgraph = CreateSubgraphViewFrom(CreateInputsFrom({convLayer1}), CreateOutputsFrom({convLayer2}), {substitutionpreCompiledLayer}); view.AddSubstitution({*baseSubgraph, *substitutionSubgraph}); // Construct original subgraph to compare against SubgraphViewSelector::SubgraphViewPtr originalSubgraph = CreateSubgraphViewFrom(CreateInputsFrom({convLayer1}), CreateOutputsFrom({convLayer2}), {convLayer1, convLayer2, substitutionpreCompiledLayer}); BOOST_CHECK(view.Validate(*originalSubgraph)); } BOOST_AUTO_TEST_CASE(OptimizedViewsSubgraphLayerCountFailValidate) { OptimizationViews view; // Construct a graph with 3 layers Graph& baseGraph = view.GetGraph(); Layer* const inputLayer = baseGraph.AddLayer<InputLayer>(0, "input"); Convolution2dDescriptor convDescriptor; PreCompiledDescriptor substitutionLayerDescriptor(1, 1); Layer* const convLayer1 = baseGraph.AddLayer<Convolution2dLayer>(convDescriptor, "conv1"); Layer* const convLayer2 = baseGraph.AddLayer<Convolution2dLayer>(convDescriptor, "conv2"); Layer* const substitutableCompiledLayer = baseGraph.AddLayer<PreCompiledLayer>(substitutionLayerDescriptor, "pre-compiled"); Layer* const outputLayer = baseGraph.AddLayer<OutputLayer>(0, "output"); inputLayer->GetOutputSlot(0).Connect(convLayer1->GetInputSlot(0)); convLayer1->GetOutputSlot(0).Connect(convLayer2->GetInputSlot(0)); convLayer2->GetOutputSlot(0).Connect(outputLayer->GetInputSlot(0)); // Subgraph for an untouched layer SubgraphViewSelector::SubgraphViewPtr untouchedSubgraph = CreateSubgraphViewFrom(CreateInputsFrom({convLayer2}), CreateOutputsFrom({convLayer2}), {convLayer2}); // Subgraph for a substitutable layer SubgraphViewSelector::SubgraphViewPtr substitutableSubgraph = CreateSubgraphViewFrom(CreateInputsFrom({convLayer1}), CreateOutputsFrom({convLayer2}), {substitutableCompiledLayer}); // Create a Graph containing a layer to substitute in Graph substitutableGraph; Layer* const substitutionpreCompiledLayer = substitutableGraph.AddLayer<PreCompiledLayer>(substitutionLayerDescriptor, "pre-compiled"); // Subgraph for a substitution layer SubgraphViewSelector::SubgraphViewPtr substitutionSubgraph = CreateSubgraphViewFrom(CreateInputsFrom({substitutionpreCompiledLayer}), CreateOutputsFrom({substitutionpreCompiledLayer}), {substitutionpreCompiledLayer}); // Sub in the graph baseGraph.SubstituteSubgraph(*substitutableSubgraph, *substitutionSubgraph); view.AddUntouchedSubgraph(SubgraphView(*untouchedSubgraph)); SubgraphViewSelector::SubgraphViewPtr baseSubgraph = CreateSubgraphViewFrom(CreateInputsFrom({convLayer1}), CreateOutputsFrom({convLayer2}), {substitutionpreCompiledLayer}); view.AddSubstitution({*baseSubgraph, *substitutionSubgraph}); // Construct original subgraph to compare against SubgraphViewSelector::SubgraphViewPtr originalSubgraph = CreateSubgraphViewFrom(CreateInputsFrom({convLayer1}), CreateOutputsFrom({convLayer2}), {convLayer1, convLayer2, substitutionpreCompiledLayer}); // Validate should fail as convLayer1 is not counted BOOST_CHECK(!view.Validate(*originalSubgraph)); } BOOST_AUTO_TEST_CASE(OptimizeViewsValidateDeviceMockBackend) { // build up the structure of the network armnn::INetworkPtr net(armnn::INetwork::Create()); armnn::IConnectableLayer* input = net->AddInputLayer(0, "inLayer0"); armnn::IConnectableLayer* input1 = net->AddInputLayer(1, "inLayer1"); armnn::IConnectableLayer* addition = net->AddAdditionLayer("addLayer"); armnn::IConnectableLayer* output = net->AddOutputLayer(0, "outLayer"); input->GetOutputSlot(0).Connect(addition->GetInputSlot(0)); input1->GetOutputSlot(0).Connect(addition->GetInputSlot(1)); addition->GetOutputSlot(0).Connect(output->GetInputSlot(0)); input->GetOutputSlot(0).SetTensorInfo(armnn::TensorInfo({ 1, 1, 4, 4 }, armnn::DataType::Float32)); input1->GetOutputSlot(0).SetTensorInfo(armnn::TensorInfo({ 1, 1, 4, 4 }, armnn::DataType::Float32)); addition->GetOutputSlot(0).SetTensorInfo(armnn::TensorInfo({ 1, 1, 4, 4 }, armnn::DataType::Float32)); armnn::IRuntime::CreationOptions options; armnn::IRuntimePtr runtime(armnn::IRuntime::Create(options)); std::vector<armnn::BackendId> backends = { MockBackend().GetIdStatic() }; armnn::IOptimizedNetworkPtr optNet = armnn::Optimize(*net, backends, runtime->GetDeviceSpec()); BOOST_CHECK(optNet); // Check the optimised graph OptimizedNetwork* optNetObjPtr = boost::polymorphic_downcast<OptimizedNetwork*>(optNet.get()); CheckLayers(optNetObjPtr->GetGraph()); } BOOST_AUTO_TEST_SUITE_END()<|endoftext|>
<commit_before>#include <cstdio> #include <cstdlib> #include <cstring> #include <iostream> #include <bitset> #include <sstream> #include <unistd.h> #include <vector> #include <algorithm> #include <list> #include <map> #include "segment.h" #include "message.h" #include "loc_success_message.h" #include "loc_failure_message.h" #include "loc_request_message.h" #include "execute_success_message.h" #include "execute_failure_message.h" #include "execute_request_message.h" #include "register_success_message.h" #include "register_failure_message.h" #include "register_request_message.h" #include "terminate_message.h" #include "rpc.h" #include "constants.h" #include "network.h" #include "helper_functions.h" using namespace std; // Global variables for client static bool connectedToBinder = false; static int clientBinderSocket = -1; static int serverBinderSocket = -1; // Global variables for server static map<procedure_signature, skeleton, ps_compare> procSkeleDict; static string serverIdentifier; static unsigned int port = 0; static int welcomeSocket = 0; static bool onSwitch = true; void mapPrint(){ cout << "procSkeleDict size: "<<procSkeleDict.size() << endl; cout << "Map Print: "; for(map<procedure_signature, skeleton>::iterator it = procSkeleDict.begin(); it != procSkeleDict.end(); ++it){ cout << it->first.name << ", "; } cout << endl; } void printArgTypes(int * argTypes){ cout << " Printing argTypes: " ; unsigned num = countNumOfArgTypes(argTypes); for(int i = 0; i < num; i++){ cout << argTypes[i] << ", "; } cout << endl; } void printArgs(int * argTypes, void ** args){ cout << "Printing args: " ; // Parses the argument from the buffer unsigned numOfArgs = countNumOfArgTypes(argTypes) - 1; cout<<"Number of args: " << numOfArgs << endl; for (unsigned int i = 0; i < numOfArgs; i++) { int argType = argTypes[i]; int argTypeInformation = (argType & ARG_TYPE_INFORMATION_MASK) >> ARG_TYPE_INFORMATION_SHIFT_AMOUNT; int argTypeArrayLength = argType & ARG_TYPE_ARRAY_LENGTH_MASK; argTypeArrayLength = (argTypeArrayLength == 0) ? 1: argTypeArrayLength; void *arg = args[i]; switch (argTypeInformation) { case ARG_CHAR: { cout << "Printing ARG_CHAR: " << endl; char *argCharArray = (char *) arg; cout << argCharArray << endl; break; } case ARG_SHORT: { cout << "Printing ARG_SHORT: " << endl; short *argShortArray = (short *) arg; for (int j = 0; j < argTypeArrayLength; j++) { cout << argShortArray[i] << ", "; } cout << endl; break; } case ARG_INT: { cout << "Printing ARG_INT: " << endl; int *argIntArray = (int *) arg; for (int j = 0; j < argTypeArrayLength; j++) { cout << argIntArray[j] << ", "; } cout << endl; break; } case ARG_LONG: { cout << "Printing ARG_LONG: " << endl; long *argLongArray = (long *) arg; for (int j = 0; j < argTypeArrayLength; j++) { cout << argLongArray[j] << ","; } cout << endl; break; } case ARG_DOUBLE: { cout << "Printing ARG_DOUBLE: " << endl; double *argDoubleArray = (double *) arg; for (int j = 0; j < argTypeArrayLength; j++) { cout << argDoubleArray[j] << ", "; } cout << endl; break; } case ARG_FLOAT: { cout << "Printing ARG_FLOAT: " << endl; float *argFloatArray = (float *) arg; for (int j = 0; j < argTypeArrayLength; j++) { cout << argFloatArray[j] << ", "; } cout << endl; break; } } } cout << endl; } // See interface (header file). int rpcInit(){ cout << "Running rpcInit..." << endl; /* * Creates a connection socket to be used for accepting connections * from clients */ welcomeSocket = createSocket(); setUpToListen(welcomeSocket); serverIdentifier = getHostAddress(); port = getSocketPort(welcomeSocket); cout << "This servers welcomeSocket is: " << welcomeSocket << endl; // Opens a connection to the binderz serverBinderSocket = createSocket(); string binderAddress = getBinderAddress(); unsigned int binderPort = getBinderPort(); setUpToConnect(serverBinderSocket, binderAddress, binderPort); connectedToBinder = true; cout << "This servers serverBinderSocket is: " << serverBinderSocket << endl; return 0; } // See interface (header file). int rpcCall(char *name, int *argTypes, void **args) { cout << "Running rpcCall..." << endl; string serverAddress; unsigned int serverPort = 0; int status; if(!connectedToBinder){ cout << "Connecting to binder..." << endl; clientBinderSocket = createSocket(); string binderAddress = getBinderAddress(); unsigned int binderPort = getBinderPort(); status = setUpToConnect(clientBinderSocket, binderAddress, binderPort); connectedToBinder = true; cout << "Connected to binder..." << endl; } //do something with returnVal LocRequestMessage messageToBinder = LocRequestMessage(string(name), argTypes); Segment segmentToBinder = Segment(messageToBinder.getLength(), MSG_TYPE_LOC_REQUEST, &messageToBinder); int binder_status = segmentToBinder.send(clientBinderSocket); cout << "LOC REQUEST message sent..." << endl; //maybe error check with binder_status //TODO: SEGMENT FAULT IF NOT IN THIS FOR LOOP /**Server stuff **/ if(binder_status >= 0){ Segment *parsedSegment = 0; int tempStatus = 0; tempStatus = Segment::receive(clientBinderSocket, parsedSegment); Message *messageFromBinder = parsedSegment->getMessage(); switch (parsedSegment->getType()) { case MSG_TYPE_LOC_SUCCESS: { cout << "LOC SUCCESS message received..." << endl; LocSuccessMessage *lsm = dynamic_cast<LocSuccessMessage *>(messageFromBinder); serverAddress = lsm->getServerIdentifier(); serverPort = lsm->getPort(); cout << "serverAddress: " << serverAddress << endl; cout << "serverPort: " << serverPort << endl; break; } case MSG_TYPE_LOC_FAILURE: { cout << "LOC FAILURE message received..." << endl; return -1; break; } } } cout << "Connecting to server..." << endl; int serverSocket = createSocket(); int status1 = setUpToConnect(serverSocket, serverAddress, serverPort); cout << "status1: " << status1 << endl; cout << "Server Socket: " << serverSocket << endl; cout << "Server Address: " << serverAddress << endl; cout << "Server Port: " << serverPort << endl; cout << "Connected to server..." << endl; ExecuteRequestMessage exeReqMsg = ExecuteRequestMessage(name, argTypes, args); Segment exeReqSeg = Segment(exeReqMsg.getLength(), MSG_TYPE_EXECUTE_REQUEST, &exeReqMsg); int status2 = exeReqSeg.send(serverSocket); cout << "Status of exeRegMsg send: " << status2 << endl; int returnVal = 0; Segment * parsedSegmentEsm = 0; int status3 = 0; status3 = Segment::receive(serverSocket, parsedSegmentEsm); cout << "Flag 1" << endl; //instead we have cout << "Flag 2" << endl; switch (parsedSegmentEsm->getType()) { case MSG_TYPE_EXECUTE_SUCCESS: { cout << "EXECUTE SUCCESS message received..." << endl; Message * msg = parsedSegmentEsm->getMessage(); ExecuteSuccessMessage * esm = dynamic_cast<ExecuteSuccessMessage*>(msg); // TODO FIX: name = esm->getName(); //argTypes = esm->getArgTypes(); void** newArgs = esm->getArgs(); unsigned numOfArgs = countNumOfArgTypes(esm->getArgTypes()) - 1; for (unsigned int i = 0; i < numOfArgs; i++) { args[i] = newArgs[i]; } break; } case MSG_TYPE_EXECUTE_FAILURE: { cout << "EXECUTE FAILURE message received..." << endl; Message * cast = parsedSegmentEsm->getMessage(); ExecuteFailureMessage * efm = dynamic_cast<ExecuteFailureMessage*>(cast); returnVal = efm->getReasonCode(); break; } } close(serverSocket); return returnVal; } //TODO: // CREATE SERVER // CONNECT TO BINDER int rpcRegister(char * name, int *argTypes, skeleton f){ cout << "Running rpcRegister..." << endl; RegisterRequestMessage regReqMsg = RegisterRequestMessage(serverIdentifier, port, name, argTypes); /* cout << "rpcRegister name: " << name << endl; cout << "rpcRegister serverIdentifier: " << serverIdentifier << endl; cout << "rpcRegister port: " << port << endl; */ /* We should get seg.send to give us some feed back maybe int status = regReqMsg->send(serverBinderSocket); */ Segment regReqSeg = Segment(regReqMsg.getLength(), MSG_TYPE_REGISTER_REQUEST, &regReqMsg); int status = regReqSeg.send(serverBinderSocket); cout << "When we register we use this serverBinderSocket: " << serverBinderSocket << endl; //cout << "rpcRegister Status: " << status << endl; if(status >= 0){ //Success Segment *parsedSegment = 0; int result = 0; result = Segment::receive(serverBinderSocket, parsedSegment); if(parsedSegment->getType() == MSG_TYPE_REGISTER_SUCCESS){ cout << "MSG_TYPE_REGISTER_SUCCESS" << endl; Message * cast = parsedSegment->getMessage(); //Error Checking maybe RegisterSuccessMessage * rsm = dynamic_cast<RegisterSuccessMessage*>(cast); //struct procedure_signature k(string(name), argTypes); struct procedure_signature k = procedure_signature(string(name), argTypes); procSkeleDict[k] = f; cout << "k: " << k.name << ", "<< f << endl; }else if(parsedSegment->getType() == MSG_TYPE_REGISTER_FAILURE){ return 0; } }else if( status < 0){ //Error return -99; } return 1; } // See interface (header file). int rpcExecute(){ cout << "Running rpcExecute..." << endl; fd_set allSockets; fd_set readSockets; /* * Clears all entries from the all sockets set and the read * sockets set */ FD_ZERO(&allSockets); FD_ZERO(&readSockets); /* * Adds the welcome socket to the all sockets set and sets * it as the maximum socket so far */ FD_SET(serverBinderSocket, &allSockets); FD_SET(welcomeSocket, &allSockets); int maxSocket = welcomeSocket; while (onSwitch) { readSockets = allSockets; // Checks if some of the sockets are ready to be read from int result = select(maxSocket + 1, &readSockets, 0, 0, 0); if (result < 0) { continue; } for (int i = 0; i <= maxSocket; i++) { if (!FD_ISSET(i, &readSockets)) { continue; } if (i == welcomeSocket) { /* * Creates the connection socket when a connection is made * to the welcome socket */ int connectionSocket = acceptConnection(i); if (connectionSocket < 0) { continue; } // Adds the connection socket to the all sockets set FD_SET(connectionSocket, &allSockets); /* * Sets the connection socket as the maximum socket so far * if necessary */ if (connectionSocket > maxSocket) { maxSocket = connectionSocket; } } else { /* * Creates a segment to receive data from the client/binder and * reads into it from the connection socket */ Segment *segment = 0; result = 0; result = Segment::receive(i, segment); if (result < 0) { /* * Closes the connection socket and removes it from the * all sockets set */ cout << "Bad result, I'm closing, i is: "<< i << endl; destroySocket(i); FD_CLR(i, &allSockets); continue; } switch (segment->getType()) { case MSG_TYPE_EXECUTE_REQUEST: { Message * cast = segment->getMessage(); ExecuteRequestMessage * erm = dynamic_cast<ExecuteRequestMessage*>(cast); procedure_signature * ps = new procedure_signature(erm->getName(), erm->getArgTypes()); cout << "erm->getName(): " << erm->getName() << endl; printArgTypes(erm->getArgTypes()); printArgs(erm->getArgTypes(), erm->getArgs()); skeleton skel = procSkeleDict[*ps]; if(skel == 0){ cout << "Skel is null" << endl; } int result = skel(erm->getArgTypes(), erm->getArgs()); cout << "Result: " << result << endl; printArgs(erm->getArgTypes(), erm->getArgs()); if(result == 0 ){ ExecuteSuccessMessage exeSuccessMsg = ExecuteSuccessMessage(erm->getName(), erm->getArgTypes(), erm->getArgs()); Segment exeSuccessSeg = Segment(exeSuccessMsg.getLength(), MSG_TYPE_EXECUTE_SUCCESS, &exeSuccessMsg); int tstatus = exeSuccessSeg.send(i); cout << "ExecuteSuccessMessage status: " << tstatus << endl; }else{ ExecuteFailureMessage exeFailMsg = ExecuteFailureMessage(result); Segment exeFailSeg = Segment(exeFailMsg.getLength(), MSG_TYPE_EXECUTE_FAILURE, &exeFailMsg); int tstatus = exeFailSeg.send(i); } break; } case MSG_TYPE_TERMINATE: { cout << "Got to terminate" << endl; if (i != serverBinderSocket) { return ERROR_CODE_TERMINATE; } onSwitch = false; break; } } } } } // Destroys the welcome socket cout << "We are destorying the welcomeSocket: " << welcomeSocket << endl; destroySocket(welcomeSocket); return SUCCESS_CODE; } int rpcCacheCall() { cout << "Running rpcCacheCall..." << endl; return SUCCESS_CODE; } int rpcTerminate() { cout << "Running rpcTerminate..." << endl; // Sends a terminate message to the binder TerminateMessage messageToBinder = TerminateMessage(); Segment segmentToBinder = Segment(messageToBinder.getLength(), MSG_TYPE_TERMINATE, &messageToBinder); int binder_status = segmentToBinder.send(clientBinderSocket); cout << segmentToBinder.getType() << endl; cout << "clientBinderSocket: " << clientBinderSocket << endl; // Closes the connection to the binder destroySocket(clientBinderSocket); return SUCCESS_CODE; } <commit_msg>changes<commit_after>#include <cstdio> #include <cstdlib> #include <cstring> #include <iostream> #include <bitset> #include <sstream> #include <unistd.h> #include <vector> #include <algorithm> #include <list> #include <map> #include "segment.h" #include "message.h" #include "loc_success_message.h" #include "loc_failure_message.h" #include "loc_request_message.h" #include "execute_success_message.h" #include "execute_failure_message.h" #include "execute_request_message.h" #include "register_success_message.h" #include "register_failure_message.h" #include "register_request_message.h" #include "terminate_message.h" #include "rpc.h" #include "constants.h" #include "network.h" #include "helper_functions.h" using namespace std; // Global variables for client static bool connectedToBinder = false; static int clientBinderSocket = -1; static int serverBinderSocket = -1; // Global variables for server static map<procedure_signature, skeleton, ps_compare> procSkeleDict; static string serverIdentifier; static unsigned int port = 0; static int welcomeSocket = 0; static bool onSwitch = true; void mapPrint(){ cout << "procSkeleDict size: "<<procSkeleDict.size() << endl; cout << "Map Print: "; for(map<procedure_signature, skeleton>::iterator it = procSkeleDict.begin(); it != procSkeleDict.end(); ++it){ cout << it->first.name << ", "; } cout << endl; } void printArgTypes(int * argTypes){ cout << " Printing argTypes: " ; unsigned num = countNumOfArgTypes(argTypes); for(int i = 0; i < num; i++){ cout << argTypes[i] << ", "; } cout << endl; } void printArgs(int * argTypes, void ** args){ cout << "Printing args: " ; // Parses the argument from the buffer unsigned numOfArgs = countNumOfArgTypes(argTypes) - 1; cout<<"Number of args: " << numOfArgs << endl; for (unsigned int i = 0; i < numOfArgs; i++) { int argType = argTypes[i]; int argTypeInformation = (argType & ARG_TYPE_INFORMATION_MASK) >> ARG_TYPE_INFORMATION_SHIFT_AMOUNT; int argTypeArrayLength = argType & ARG_TYPE_ARRAY_LENGTH_MASK; argTypeArrayLength = (argTypeArrayLength == 0) ? 1: argTypeArrayLength; void *arg = args[i]; switch (argTypeInformation) { case ARG_CHAR: { cout << "Printing ARG_CHAR: " << endl; char *argCharArray = (char *) arg; cout << argCharArray << endl; break; } case ARG_SHORT: { cout << "Printing ARG_SHORT: " << endl; short *argShortArray = (short *) arg; for (int j = 0; j < argTypeArrayLength; j++) { cout << argShortArray[i] << ", "; } cout << endl; break; } case ARG_INT: { cout << "Printing ARG_INT: " << endl; int *argIntArray = (int *) arg; for (int j = 0; j < argTypeArrayLength; j++) { cout << argIntArray[j] << ", "; } cout << endl; break; } case ARG_LONG: { cout << "Printing ARG_LONG: " << endl; long *argLongArray = (long *) arg; for (int j = 0; j < argTypeArrayLength; j++) { cout << argLongArray[j] << ","; } cout << endl; break; } case ARG_DOUBLE: { cout << "Printing ARG_DOUBLE: " << endl; double *argDoubleArray = (double *) arg; for (int j = 0; j < argTypeArrayLength; j++) { cout << argDoubleArray[j] << ", "; } cout << endl; break; } case ARG_FLOAT: { cout << "Printing ARG_FLOAT: " << endl; float *argFloatArray = (float *) arg; for (int j = 0; j < argTypeArrayLength; j++) { cout << argFloatArray[j] << ", "; } cout << endl; break; } } } cout << endl; } // See interface (header file). int rpcInit(){ cout << "Running rpcInit..." << endl; /* * Creates a connection socket to be used for accepting connections * from clients */ cout << "B4 welcomeSocket is: " << welcomeSocket << endl; cout << "B4 serverBinderSocket is: " << serverBinderSocket << endl; welcomeSocket = createSocket(); setUpToListen(welcomeSocket); serverIdentifier = getHostAddress(); port = getSocketPort(welcomeSocket); cout << "This servers welcomeSocket is: " << welcomeSocket << endl; // Opens a connection to the binderz serverBinderSocket = createSocket(); string binderAddress = getBinderAddress(); unsigned int binderPort = getBinderPort(); setUpToConnect(serverBinderSocket, binderAddress, binderPort); connectedToBinder = true; cout << "This servers serverBinderSocket is: " << serverBinderSocket << endl; return 0; } // See interface (header file). int rpcCall(char *name, int *argTypes, void **args) { cout << "Running rpcCall..." << endl; string serverAddress; unsigned int serverPort = 0; int status; if(!connectedToBinder){ cout << "Connecting to binder..." << endl; clientBinderSocket = createSocket(); string binderAddress = getBinderAddress(); unsigned int binderPort = getBinderPort(); status = setUpToConnect(clientBinderSocket, binderAddress, binderPort); connectedToBinder = true; cout << "Connected to binder..." << endl; } //do something with returnVal LocRequestMessage messageToBinder = LocRequestMessage(string(name), argTypes); Segment segmentToBinder = Segment(messageToBinder.getLength(), MSG_TYPE_LOC_REQUEST, &messageToBinder); int binder_status = segmentToBinder.send(clientBinderSocket); cout << "LOC REQUEST message sent..." << endl; //maybe error check with binder_status //TODO: SEGMENT FAULT IF NOT IN THIS FOR LOOP /**Server stuff **/ if(binder_status >= 0){ Segment *parsedSegment = 0; int tempStatus = 0; tempStatus = Segment::receive(clientBinderSocket, parsedSegment); Message *messageFromBinder = parsedSegment->getMessage(); switch (parsedSegment->getType()) { case MSG_TYPE_LOC_SUCCESS: { cout << "LOC SUCCESS message received..." << endl; LocSuccessMessage *lsm = dynamic_cast<LocSuccessMessage *>(messageFromBinder); serverAddress = lsm->getServerIdentifier(); serverPort = lsm->getPort(); cout << "serverAddress: " << serverAddress << endl; cout << "serverPort: " << serverPort << endl; break; } case MSG_TYPE_LOC_FAILURE: { cout << "LOC FAILURE message received..." << endl; return -1; break; } } } cout << "Connecting to server..." << endl; int serverSocket = createSocket(); int status1 = setUpToConnect(serverSocket, serverAddress, serverPort); cout << "status1: " << status1 << endl; cout << "Server Socket: " << serverSocket << endl; cout << "Server Address: " << serverAddress << endl; cout << "Server Port: " << serverPort << endl; cout << "Connected to server..." << endl; ExecuteRequestMessage exeReqMsg = ExecuteRequestMessage(name, argTypes, args); Segment exeReqSeg = Segment(exeReqMsg.getLength(), MSG_TYPE_EXECUTE_REQUEST, &exeReqMsg); int status2 = exeReqSeg.send(serverSocket); cout << "Status of exeRegMsg send: " << status2 << endl; int returnVal = 0; Segment * parsedSegmentEsm = 0; int status3 = 0; status3 = Segment::receive(serverSocket, parsedSegmentEsm); cout << "Flag 1" << endl; //instead we have cout << "Flag 2" << endl; switch (parsedSegmentEsm->getType()) { case MSG_TYPE_EXECUTE_SUCCESS: { cout << "EXECUTE SUCCESS message received..." << endl; Message * msg = parsedSegmentEsm->getMessage(); ExecuteSuccessMessage * esm = dynamic_cast<ExecuteSuccessMessage*>(msg); // TODO FIX: name = esm->getName(); //argTypes = esm->getArgTypes(); void** newArgs = esm->getArgs(); unsigned numOfArgs = countNumOfArgTypes(esm->getArgTypes()) - 1; for (unsigned int i = 0; i < numOfArgs; i++) { args[i] = newArgs[i]; } break; } case MSG_TYPE_EXECUTE_FAILURE: { cout << "EXECUTE FAILURE message received..." << endl; Message * cast = parsedSegmentEsm->getMessage(); ExecuteFailureMessage * efm = dynamic_cast<ExecuteFailureMessage*>(cast); returnVal = efm->getReasonCode(); break; } } close(serverSocket); return returnVal; } //TODO: // CREATE SERVER // CONNECT TO BINDER int rpcRegister(char * name, int *argTypes, skeleton f){ cout << "Running rpcRegister..." << endl; RegisterRequestMessage regReqMsg = RegisterRequestMessage(serverIdentifier, port, name, argTypes); /* cout << "rpcRegister name: " << name << endl; cout << "rpcRegister serverIdentifier: " << serverIdentifier << endl; cout << "rpcRegister port: " << port << endl; */ /* We should get seg.send to give us some feed back maybe int status = regReqMsg->send(serverBinderSocket); */ Segment regReqSeg = Segment(regReqMsg.getLength(), MSG_TYPE_REGISTER_REQUEST, &regReqMsg); int status = regReqSeg.send(serverBinderSocket); cout << "When we register we use this serverBinderSocket: " << serverBinderSocket << endl; //cout << "rpcRegister Status: " << status << endl; if(status >= 0){ //Success Segment *parsedSegment = 0; int result = 0; result = Segment::receive(serverBinderSocket, parsedSegment); if(parsedSegment->getType() == MSG_TYPE_REGISTER_SUCCESS){ cout << "MSG_TYPE_REGISTER_SUCCESS" << endl; Message * cast = parsedSegment->getMessage(); //Error Checking maybe RegisterSuccessMessage * rsm = dynamic_cast<RegisterSuccessMessage*>(cast); //struct procedure_signature k(string(name), argTypes); struct procedure_signature k = procedure_signature(string(name), argTypes); procSkeleDict[k] = f; cout << "k: " << k.name << ", "<< f << endl; }else if(parsedSegment->getType() == MSG_TYPE_REGISTER_FAILURE){ return 0; } }else if( status < 0){ //Error return -99; } return 1; } // See interface (header file). int rpcExecute(){ cout << "Running rpcExecute..." << endl; fd_set allSockets; fd_set readSockets; /* * Clears all entries from the all sockets set and the read * sockets set */ FD_ZERO(&allSockets); FD_ZERO(&readSockets); /* * Adds the welcome socket to the all sockets set and sets * it as the maximum socket so far */ FD_SET(serverBinderSocket, &allSockets); FD_SET(welcomeSocket, &allSockets); int maxSocket = welcomeSocket; while (onSwitch) { readSockets = allSockets; // Checks if some of the sockets are ready to be read from int result = select(maxSocket + 1, &readSockets, 0, 0, 0); if (result < 0) { continue; } for (int i = 0; i <= maxSocket; i++) { if (!FD_ISSET(i, &readSockets)) { continue; } if (i == welcomeSocket) { /* * Creates the connection socket when a connection is made * to the welcome socket */ int connectionSocket = acceptConnection(i); if (connectionSocket < 0) { continue; } // Adds the connection socket to the all sockets set FD_SET(connectionSocket, &allSockets); /* * Sets the connection socket as the maximum socket so far * if necessary */ if (connectionSocket > maxSocket) { maxSocket = connectionSocket; } } else { /* * Creates a segment to receive data from the client/binder and * reads into it from the connection socket */ Segment *segment = 0; result = 0; result = Segment::receive(i, segment); if (result < 0) { /* * Closes the connection socket and removes it from the * all sockets set */ cout << "Bad result, I'm closing, i is: "<< i << endl; destroySocket(i); FD_CLR(i, &allSockets); continue; } switch (segment->getType()) { case MSG_TYPE_EXECUTE_REQUEST: { Message * cast = segment->getMessage(); ExecuteRequestMessage * erm = dynamic_cast<ExecuteRequestMessage*>(cast); procedure_signature * ps = new procedure_signature(erm->getName(), erm->getArgTypes()); cout << "erm->getName(): " << erm->getName() << endl; printArgTypes(erm->getArgTypes()); printArgs(erm->getArgTypes(), erm->getArgs()); skeleton skel = procSkeleDict[*ps]; if(skel == 0){ cout << "Skel is null" << endl; } int result = skel(erm->getArgTypes(), erm->getArgs()); cout << "Result: " << result << endl; printArgs(erm->getArgTypes(), erm->getArgs()); if(result == 0 ){ ExecuteSuccessMessage exeSuccessMsg = ExecuteSuccessMessage(erm->getName(), erm->getArgTypes(), erm->getArgs()); Segment exeSuccessSeg = Segment(exeSuccessMsg.getLength(), MSG_TYPE_EXECUTE_SUCCESS, &exeSuccessMsg); int tstatus = exeSuccessSeg.send(i); cout << "ExecuteSuccessMessage status: " << tstatus << endl; }else{ ExecuteFailureMessage exeFailMsg = ExecuteFailureMessage(result); Segment exeFailSeg = Segment(exeFailMsg.getLength(), MSG_TYPE_EXECUTE_FAILURE, &exeFailMsg); int tstatus = exeFailSeg.send(i); } break; } case MSG_TYPE_TERMINATE: { cout << "Got to terminate" << endl; if (i != serverBinderSocket) { return ERROR_CODE_TERMINATE; } onSwitch = false; break; } } } } } // Destroys the welcome socket cout << "We are destorying the welcomeSocket: " << welcomeSocket << endl; destroySocket(welcomeSocket); return SUCCESS_CODE; } int rpcCacheCall() { cout << "Running rpcCacheCall..." << endl; return SUCCESS_CODE; } int rpcTerminate() { cout << "Running rpcTerminate..." << endl; // Sends a terminate message to the binder TerminateMessage messageToBinder = TerminateMessage(); Segment segmentToBinder = Segment(messageToBinder.getLength(), MSG_TYPE_TERMINATE, &messageToBinder); int binder_status = segmentToBinder.send(clientBinderSocket); cout << segmentToBinder.getType() << endl; cout << "clientBinderSocket: " << clientBinderSocket << endl; // Closes the connection to the binder destroySocket(clientBinderSocket); return SUCCESS_CODE; } <|endoftext|>
<commit_before>#include <cstdio> #include <cstring> #include <iostream> #include <sstream> #include <netinet/in.h> #include <unistd.h> #include <sys/types.h> #include <sys/socket.h> #include <arpa/inet.h> #include <vector> #include <algorithm> #include <list> #include <map> #include <netdb.h> #include <cstdlib> #include "segment.h" #include "message.h" #include "loc_success_message.h" #include "loc_failure_message.h" #include "loc_request_message.h" #include "execute_success_message.h" #include "execute_failure_message.h" #include "execute_request_message.h" #include "register_success_message.h" #include "register_failure_message.h" #include "register_request_message.h" #include "terminate_message.h" #include "rpc.h" #include "constants.h" #include "network.h" #include "helper_function.h" using namespace std; // Global variables for client bool connectedToBinder = false; int binderSocket = 0; // Global variables for server struct addrinfo* servinfo; static map<procedure_signature, skeleton, ps_compare> proc_skele_dict; string serverIdentifier; unsigned int port = 0; int welcomeSocket = 0; void mapPrint(){ cout << "proc_skele_dict size: "<<proc_skele_dict.size() << endl; cout << "Map Print: "; for(map<procedure_signature, skeleton>::iterator it = proc_skele_dict.begin(); it != proc_skele_dict.end(); ++it){ cout << it->first.name << endl; } cout << endl; } // See interface (header file). int rpcInit(){ cout << "Running rpcInit..." << endl; // Creates a connection socket to be used for accepting connections // from clients welcomeSocket = createSocket(); setUpToListen(welcomeSocket); serverIdentifier = getHostAddress(); port = getSocketPort(welcomeSocket); cout << "SERVER IDENTIFIER: " << serverIdentifier << endl; cout << "PORT: " << port << endl; // Opens a connection to the binder binderSocket = createSocket(); string binderAddress = getBinderAddress(); unsigned int binderPort = getBinderPort(); setUpToConnect(binderSocket, binderAddress, binderPort); connectedToBinder = true; cout << "binderSocket: " << binderSocket << endl; return 0; } int sendExecute(int sock, string name, int* argTypes, void**args){ ExecuteRequestMessage exeReqMsg = ExecuteRequestMessage(name, argTypes, args); Segment exeReqSeg = Segment(exeReqMsg.getLength(), MSG_TYPE_EXECUTE_REQUEST, &exeReqMsg); int status = exeReqSeg.send(sock); int returnVal; string retName; int* retArgTypes; void** retArgs; if(status == 0){ Segment * segment = 0; status = Segment::receive(sock, segment); if(segment->getType() == MSG_TYPE_EXECUTE_SUCCESS) { Message * cast = segment->getMessage(); ExecuteSuccessMessage * esm = dynamic_cast<ExecuteSuccessMessage*>(cast); retName = esm->getName(); retArgTypes = esm->getArgTypes(); retArgs = esm->getArgs(); if(retName == name){ //extractArgumentsMessage(replyMessageP, argTypes, args, argTypesLength, false); returnVal = 0; }else{ returnVal = 99; } }else if(segment->getType() == MSG_TYPE_EXECUTE_FAILURE){ Message * cast = segment->getMessage(); ExecuteFailureMessage * efm = dynamic_cast<ExecuteFailureMessage*>(cast); returnVal = efm->getReasonCode(); } }else{ //Something bad happened returnVal = 99; } return returnVal; } // See interface (header file). int rpcCall(char *name, int *argTypes, void **args) { cout << "Flag0" << endl; string serverAddress; unsigned int serverPort; int status; if(!connectedToBinder){ binderSocket = createSocket(); string binderAddress = getBinderAddress(); unsigned int binderPort = getBinderPort(); status = setUpToConnect(binderSocket, binderAddress, binderPort); connectedToBinder = true; } //do something with returnVal cout << "Flag1" << endl; LocRequestMessage locReqMsg = LocRequestMessage(name, argTypes); Segment locReqSeg = Segment(locReqMsg.getLength(), MSG_TYPE_LOC_REQUEST, &locReqMsg); int binder_status = locReqSeg.send(binderSocket); cout << "Flag1.5" << endl; //maybe error check with binder_status //TODO: SEGMENT FAULT IF NOT IN THIS FOR LOOP /**Server stuff **/ if(binder_status >= 0){ cout << "Flag2" << endl; Segment * parsedSegment = 0; cout << "Flag2.1" << endl; int tempStatus = 0; cout << "Flag2.2" << endl; tempStatus = Segment::receive(binderSocket, parsedSegment); cout << "Flag2.5" << endl; if(parsedSegment->getType() == MSG_TYPE_LOC_SUCCESS) { //'LOC_REQUEST' cout << "Got success" << endl; Message * cast = parsedSegment->getMessage(); LocSuccessMessage * lcm = dynamic_cast<LocSuccessMessage*>(cast); serverAddress = lcm->getServerIdentifier(); serverPort = lcm->getPort(); }else if(parsedSegment->getType() == MSG_TYPE_LOC_FAILURE) { //something bad happens return 1; } } int serverSocket = createSocket(); int status1 = setUpToConnect(serverSocket, serverAddress, serverPort); status1 = sendExecute(serverSocket, string(name), argTypes, args); return status1; } //TODO: // CREATE SERVER // CONNECT TO BINDER int rpcRegister(char * name, int *argTypes, skeleton f){ RegisterRequestMessage regReqMsg = RegisterRequestMessage(serverIdentifier, port, name, argTypes); cout << "rpcRegister name: " << name << endl; cout << "rpcRegister serverIdentifier: " << serverIdentifier << endl; cout << "rpcRegister port: " << port << endl; /* We should get seg.send to give us some feed back maybe int status = regReqMsg->send(binderSocket); */ Segment regReqSeg = Segment(regReqMsg.getLength(), MSG_TYPE_REGISTER_REQUEST, &regReqMsg); int status = regReqSeg.send(binderSocket); cout << "rpcRegister Status: " << status << endl; if(status >= 0){ //Success Segment *parsedSegment = 0; int result = 0; result = Segment::receive(binderSocket, parsedSegment); if(parsedSegment->getType() == MSG_TYPE_REGISTER_SUCCESS){ cout << "MSG_TYPE_REGISTER_SUCCESS" << endl; Message * cast = parsedSegment->getMessage(); //Error Checking maybe RegisterSuccessMessage * rsm = dynamic_cast<RegisterSuccessMessage*>(cast); struct procedure_signature k(string(name), argTypes); proc_skele_dict[k] = f; //cout << "k: " << k.name << endl; mapPrint(); }else if(parsedSegment->getType() == MSG_TYPE_REGISTER_FAILURE){ return 0; } }else if( status < 0){ //Error return -99; } return 1; } int rpcExecute(void){ cout << "Running rpcExecute..." << endl; //Create connection socket ot be used for accepting clients vector<int> myConnections; vector<int> myToRemove; fd_set readfds; int n; int status; while(true){ //CONNECTIONS VECTOR FD_ZERO(&readfds); FD_SET(welcomeSocket, &readfds); n = welcomeSocket; for (vector<int>::iterator it = myConnections.begin();it != myConnections.end(); ++it) { int connection = *it; FD_SET(connection, &readfds); if (connection > n){ n = connection; } } n = n+1; status = select(n, &readfds, NULL, NULL, NULL); if (status == -1) { cerr << "ERROR: select failed." << endl; } else { if (FD_ISSET(welcomeSocket, &readfds)) { int connectionSocket = acceptConnection(welcomeSocket); if (connectionSocket < 0) { cerr << "ERROR: while accepting connection" << endl; continue; } myConnections.push_back(connectionSocket); } else { for (vector<int>::iterator it = myConnections.begin(); it != myConnections.end(); ++it) { int tempConnection = *it; if (FD_ISSET(tempConnection, &readfds)) { int reasonCode = 0; Segment * segment = 0; status = Segment::receive(tempConnection, segment); if(segment->getType() == MSG_TYPE_EXECUTE_REQUEST){ Message * cast = segment->getMessage(); ExecuteRequestMessage * eqm = dynamic_cast<ExecuteRequestMessage*>(cast); procedure_signature * ps = new procedure_signature(eqm->getName(), eqm->getArgTypes()); skeleton skel = proc_skele_dict[*ps]; int result = skel(eqm->getArgTypes(), eqm->getArgs()); if(result == 0 ){ ExecuteSuccessMessage exeSuccessMsg = ExecuteSuccessMessage(eqm->getName(), eqm->getArgTypes(), eqm->getArgs()); Segment exeSuccessSeg = Segment(exeSuccessMsg.getLength(), MSG_TYPE_EXECUTE_SUCCESS, &exeSuccessMsg); status = exeSuccessSeg.send(tempConnection); }else{ ExecuteFailureMessage exeFailMsg = ExecuteFailureMessage(reasonCode); Segment exeFailSeg = Segment(exeFailMsg.getLength(), MSG_TYPE_EXECUTE_FAILURE, &exeFailMsg); status = exeFailSeg.send(tempConnection); } } if (status == 0) { // client has closed the connection myToRemove.push_back(tempConnection); return status; } } } } for (vector<int>::iterator it = myToRemove.begin(); it != myToRemove.end(); ++it) { myConnections.erase(remove(myConnections.begin(), myConnections.end(), *it), myConnections.end()); close(*it); } myToRemove.clear(); } } freeaddrinfo(servinfo); return 0; } int rpcCacheCall() { return 0; } int rpcTerminate() { cout << "Running rpcTerminate..." << endl; TerminateMessage messageToBinder = TerminateMessage(); Segment segmentToBinder = Segment(messageToBinder.getLength(), MSG_TYPE_TERMINATE, &messageToBinder); segmentToBinder.send(binderSocket); return 0; } <commit_msg>changes<commit_after>#include <cstdio> #include <cstring> #include <iostream> #include <sstream> #include <netinet/in.h> #include <unistd.h> #include <sys/types.h> #include <sys/socket.h> #include <arpa/inet.h> #include <vector> #include <algorithm> #include <list> #include <map> #include <netdb.h> #include <cstdlib> #include "segment.h" #include "message.h" #include "loc_success_message.h" #include "loc_failure_message.h" #include "loc_request_message.h" #include "execute_success_message.h" #include "execute_failure_message.h" #include "execute_request_message.h" #include "register_success_message.h" #include "register_failure_message.h" #include "register_request_message.h" #include "terminate_message.h" #include "rpc.h" #include "constants.h" #include "network.h" #include "helper_function.h" using namespace std; // Global variables for client bool connectedToBinder = false; int binderSocket = 0; // Global variables for server struct addrinfo* servinfo; static map<procedure_signature, skeleton, ps_compare> proc_skele_dict; string serverIdentifier; unsigned int port = 0; int welcomeSocket = 0; void mapPrint(){ cout << "proc_skele_dict size: "<<proc_skele_dict.size() << endl; cout << "Map Print: "; for(map<procedure_signature, skeleton>::iterator it = proc_skele_dict.begin(); it != proc_skele_dict.end(); ++it){ cout << it->first.name << endl; } cout << endl; } // See interface (header file). int rpcInit(){ cout << "Running rpcInit..." << endl; // Creates a connection socket to be used for accepting connections // from clients welcomeSocket = createSocket(); setUpToListen(welcomeSocket); serverIdentifier = getHostAddress(); port = getSocketPort(welcomeSocket); cout << "SERVER IDENTIFIER: " << serverIdentifier << endl; cout << "PORT: " << port << endl; // Opens a connection to the binder binderSocket = createSocket(); string binderAddress = getBinderAddress(); unsigned int binderPort = getBinderPort(); setUpToConnect(binderSocket, binderAddress, binderPort); connectedToBinder = true; cout << "binderSocket: " << binderSocket << endl; return 0; } int sendExecute(int sock, string name, int* argTypes, void**args){ ExecuteRequestMessage exeReqMsg = ExecuteRequestMessage(name, argTypes, args); Segment exeReqSeg = Segment(exeReqMsg.getLength(), MSG_TYPE_EXECUTE_REQUEST, &exeReqMsg); int status = exeReqSeg.send(sock); int returnVal; string retName; int* retArgTypes; void** retArgs; if(status == 0){ Segment * segment = 0; status = Segment::receive(sock, segment); if(segment->getType() == MSG_TYPE_EXECUTE_SUCCESS) { Message * cast = segment->getMessage(); ExecuteSuccessMessage * esm = dynamic_cast<ExecuteSuccessMessage*>(cast); retName = esm->getName(); retArgTypes = esm->getArgTypes(); retArgs = esm->getArgs(); if(retName == name){ //extractArgumentsMessage(replyMessageP, argTypes, args, argTypesLength, false); returnVal = 0; }else{ returnVal = 99; } }else if(segment->getType() == MSG_TYPE_EXECUTE_FAILURE){ Message * cast = segment->getMessage(); ExecuteFailureMessage * efm = dynamic_cast<ExecuteFailureMessage*>(cast); returnVal = efm->getReasonCode(); } }else{ //Something bad happened returnVal = 99; } return returnVal; } // See interface (header file). int rpcCall(char *name, int *argTypes, void **args) { cout << "Flag0" << endl; string serverAddress; unsigned int serverPort; int status; if(!connectedToBinder){ cout << "Does it run" << endl; binderSocket = createSocket(); string binderAddress = getBinderAddress(); unsigned int binderPort = getBinderPort(); status = setUpToConnect(binderSocket, binderAddress, binderPort); connectedToBinder = true; } //do something with returnVal cout << "binderSocket: " <<binderSocket << endl; cout << "Flag1" << endl; LocRequestMessage locReqMsg = LocRequestMessage(name, argTypes); Segment locReqSeg = Segment(locReqMsg.getLength(), MSG_TYPE_LOC_REQUEST, &locReqMsg); int binder_status = locReqSeg.send(binderSocket); cout << "Flag1.5" << endl; //maybe error check with binder_status //TODO: SEGMENT FAULT IF NOT IN THIS FOR LOOP /**Server stuff **/ if(binder_status >= 0){ cout << "Flag2" << endl; Segment * parsedSegment = 0; cout << "Flag2.1" << endl; int tempStatus = 0; cout << "Flag2.2" << endl; tempStatus = Segment::receive(binderSocket, parsedSegment); cout << "Flag2.5" << endl; if(parsedSegment->getType() == MSG_TYPE_LOC_SUCCESS) { //'LOC_REQUEST' cout << "Got success" << endl; Message * cast = parsedSegment->getMessage(); LocSuccessMessage * lcm = dynamic_cast<LocSuccessMessage*>(cast); serverAddress = lcm->getServerIdentifier(); serverPort = lcm->getPort(); }else if(parsedSegment->getType() == MSG_TYPE_LOC_FAILURE) { //something bad happens return 1; } } int serverSocket = createSocket(); int status1 = setUpToConnect(serverSocket, serverAddress, serverPort); status1 = sendExecute(serverSocket, string(name), argTypes, args); return status1; } //TODO: // CREATE SERVER // CONNECT TO BINDER int rpcRegister(char * name, int *argTypes, skeleton f){ RegisterRequestMessage regReqMsg = RegisterRequestMessage(serverIdentifier, port, name, argTypes); cout << "rpcRegister name: " << name << endl; cout << "rpcRegister serverIdentifier: " << serverIdentifier << endl; cout << "rpcRegister port: " << port << endl; /* We should get seg.send to give us some feed back maybe int status = regReqMsg->send(binderSocket); */ Segment regReqSeg = Segment(regReqMsg.getLength(), MSG_TYPE_REGISTER_REQUEST, &regReqMsg); int status = regReqSeg.send(binderSocket); cout << "rpcRegister Status: " << status << endl; if(status >= 0){ //Success Segment *parsedSegment = 0; int result = 0; result = Segment::receive(binderSocket, parsedSegment); if(parsedSegment->getType() == MSG_TYPE_REGISTER_SUCCESS){ cout << "MSG_TYPE_REGISTER_SUCCESS" << endl; Message * cast = parsedSegment->getMessage(); //Error Checking maybe RegisterSuccessMessage * rsm = dynamic_cast<RegisterSuccessMessage*>(cast); struct procedure_signature k(string(name), argTypes); proc_skele_dict[k] = f; //cout << "k: " << k.name << endl; mapPrint(); }else if(parsedSegment->getType() == MSG_TYPE_REGISTER_FAILURE){ return 0; } }else if( status < 0){ //Error return -99; } return 1; } int rpcExecute(void){ cout << "Running rpcExecute..." << endl; //Create connection socket ot be used for accepting clients vector<int> myConnections; vector<int> myToRemove; fd_set readfds; int n; int status; while(true){ //CONNECTIONS VECTOR FD_ZERO(&readfds); FD_SET(welcomeSocket, &readfds); n = welcomeSocket; for (vector<int>::iterator it = myConnections.begin();it != myConnections.end(); ++it) { int connection = *it; FD_SET(connection, &readfds); if (connection > n){ n = connection; } } n = n+1; status = select(n, &readfds, NULL, NULL, NULL); if (status == -1) { cerr << "ERROR: select failed." << endl; } else { if (FD_ISSET(welcomeSocket, &readfds)) { int connectionSocket = acceptConnection(welcomeSocket); if (connectionSocket < 0) { cerr << "ERROR: while accepting connection" << endl; continue; } myConnections.push_back(connectionSocket); } else { for (vector<int>::iterator it = myConnections.begin(); it != myConnections.end(); ++it) { int tempConnection = *it; if (FD_ISSET(tempConnection, &readfds)) { int reasonCode = 0; Segment * segment = 0; status = Segment::receive(tempConnection, segment); if(segment->getType() == MSG_TYPE_EXECUTE_REQUEST){ Message * cast = segment->getMessage(); ExecuteRequestMessage * eqm = dynamic_cast<ExecuteRequestMessage*>(cast); procedure_signature * ps = new procedure_signature(eqm->getName(), eqm->getArgTypes()); skeleton skel = proc_skele_dict[*ps]; int result = skel(eqm->getArgTypes(), eqm->getArgs()); if(result == 0 ){ ExecuteSuccessMessage exeSuccessMsg = ExecuteSuccessMessage(eqm->getName(), eqm->getArgTypes(), eqm->getArgs()); Segment exeSuccessSeg = Segment(exeSuccessMsg.getLength(), MSG_TYPE_EXECUTE_SUCCESS, &exeSuccessMsg); status = exeSuccessSeg.send(tempConnection); }else{ ExecuteFailureMessage exeFailMsg = ExecuteFailureMessage(reasonCode); Segment exeFailSeg = Segment(exeFailMsg.getLength(), MSG_TYPE_EXECUTE_FAILURE, &exeFailMsg); status = exeFailSeg.send(tempConnection); } } if (status == 0) { // client has closed the connection myToRemove.push_back(tempConnection); return status; } } } } for (vector<int>::iterator it = myToRemove.begin(); it != myToRemove.end(); ++it) { myConnections.erase(remove(myConnections.begin(), myConnections.end(), *it), myConnections.end()); close(*it); } myToRemove.clear(); } } freeaddrinfo(servinfo); return 0; } int rpcCacheCall() { return 0; } int rpcTerminate() { cout << "Running rpcTerminate..." << endl; TerminateMessage messageToBinder = TerminateMessage(); Segment segmentToBinder = Segment(messageToBinder.getLength(), MSG_TYPE_TERMINATE, &messageToBinder); segmentToBinder.send(binderSocket); return 0; } <|endoftext|>
<commit_before>#include "server_functions.h" #include <stdio.h> #include <string.h> #include <iostream> #include <sstream> #include <netinet/in.h> #include <unistd.h> #include <sys/types.h> #include <sys/socket.h> #include <arpa/inet.h> #include <vector> #include <algorithm> #include <netdb.h> #include <stdlib.h> #include "segment.h" #include "message.h" #include "loc_success_message.h" #include "loc_failure_message.h" #include "loc_request_message.h" #include "execute_success_message.h" #include "execute_failure_message.h" #include "execute_request_message.h" #include "rpc.h" #include "constants.h" #include "helper_function.h" #include "message_types.h" #include "message_results.h" using namespace std; bool connectedToBinder = false; int binder_sock; int connectedToBinder(){ if(connectedToBinder){ return 0; } char * binderAddressString = getenv ("BINDER_ADDRESS"); char * binderPortString = getenv("BINDER_PORT"); if(binderAddressString == NULL){ return 1; } if(binderPortString == NULL){ return 2; } binder_sock = create_connection(binderAddressString, binderPortString); if (binder_sock < 0) { return 3; }else{ connectedToBinder = true; } } int sendExecute(int sock, char* name, int* argTypes, void**args){ ExecuteRequestMessage execute_request = new ExecuteRequestMessage(name, argTypes, args); int status = execute_request->send(sock); int returnVal; char* retName; int* retArgTypes; void** retArgs if(status == 0){ Segment * segment = 0; status = Segment::receive(sock, segment); if(segment->getType() == MSG_TYPE_EXECUTE_SUCCESS) { Message * cast = segment->getMessage(); ExecuteSuccessMessage * esm = dynamic_cast<ExecuteSuccessMessage*>(cast); retName = esm->getName(); retArgTypes = esm->getArgTypes(); retArgs = esm->getArgs(); if(strcmp(retName, name)){ //extractArgumentsMessage(replyMessageP, argTypes, args, argTypesLength, false); returnVal = 0; }else{ returnVal = 99; } }else if(segment->getType() == MSG_TYPE_EXECUTE_FAILURE){ Message * cast = segment->getMessage(); ExecuteFailureMessage * efm = dynamic_cast<ExecuteFailureMessage*>(cast); returnVal = efm->getReasonCode(); } }else{ //Something bad happened returnVal = 99; } return returnVal } int rpcCall(char * name, int * argTypes, void ** args) { int returnVal; char *serverAddress; char *serverPort; int server_socket if(!connectedToBinder){ returnVal = connectedToBinder(); } //do something with returnVal LocRequestMessage loc_request = new LocRequestMessage(name, argTypes); int binder_status = loc_request->send(binder_sock); //maybe error check with binder_status /**Server stuff **/ if(status == 0){ Segment * segment = 0; status = Segment::receive(sock, segment); if(segment->getType() == MSG_TYPE_LOC_SUCCESS){ //'LOC_REQUEST' Message * cast = segment->getMessage(); LocSuccessMessage * lcm = dynamic_cast<LocSuccessMessage*>(cast); serverAddress = lcm->getServerIdentifier(); serverPort = lcm->getPort(); }else if(segment->getType() == MSG_TYPE_LOC_FAILURE){ //something bad happens return 1; } } int server_sock = create_connection(serverAddress, serverPort); int server_status = sendExecute(server_sock, name, argTypes, args); return server_status; } static map<procedure_signature, skeleton> proc_skele_dict; string serverIdentifier; unsigned int port; //int binder_sock; //only one binder socket variable int sock; //TODO: // CREATE SERVER // CONNECT TO BINDER struct thread_data { int sock; vector<string> *buf; }; void connect_to_binder() { char *serverAddress = getenv("BINDER_ADDRESS"); char *port = getenv("BINDER_PORT"); binder_sock = createConnection(serverAddress, port); return binder_sock; } int rpcRegister(char * name, int *argTypes, skeleton f){ int binder_sock = connect_to_binder(); int retStatus; RegisterRequestMessage request_message = new RegisterRequestMessage(serverIdentifier, port, name, argTypes); int status = success_message->send(binder_sock); if(status == 0){ //Success Segment * segment = 0; status = Segment::receive(binder_sock, segment); if(segment->getType() == MSG_TYPE_REGISTER_SUCCESS){ Message * cast = segment->getMessage(); RegisterSuccessMessage * rsm = dynamic_cast<RegisterSuccessMessage*>(cast); struct procedure_signature k(string(name), argTypes); proc_skele_dict[k] = f; }else if(segment->getType() == MSG_TYPE_REGISTER_FAILURE){ return 0; } }else if( status > 0){ //Warning return -99; }else if( status < 0){ //Error return 99; } } int rpcExecute(void){ //Create connection socket ot be used for accepting clients vector<int> myConnections; vector<int> myToRemove; fd_set readfds; int n; int status; struct sockaddr_storage their_addr; while(true){ //CONNECTIONS VECTOR FD_ZERO(&readfds); FD_SET(sock, &readfds); n = sock; for (vector<int>::iterator it = myConnections.begin();it != myConnections.end(); ++it) { int connection = *it; FD_SET(connection, &readfds); if (connection > n){ n = connection; } } n = n+1; status = select(n, &readfds, NULL, NULL, NULL); if (status == -1) { cerr << "ERROR: select failed." << endl; } else { if (FD_ISSET(sock, &readfds)) { socklen_t addr_size = sizeof their_addr; int new_sock = accept(sock, (struct sockaddr*)&their_addr, &addr_size); if (new_sock < 0) { cerr << "ERROR: while accepting connection" << endl; close(new_sock); continue; } myConnections.push_back(new_sock); } else { for (vector<int>::iterator it = myConnections.begin(); it != myConnections.end(); ++it) { int tempConnection = *it; if (FD_ISSET(tempConnection, &readfds)) { int reasonCode = 0; Segment * segment = 0; status = Segment::receive(sock, segment); if(segment->getType() == MSG_TYPE_EXECUTE_REQUEST){ Message * cast = segment->getMessage(); ExecuteRequestMessage * eqm = dynamic_cast<ExecuteRequestMessage*>(cast); procedure_signature ps = new procedure_signature(eqm->getName(), eqm->getArgTypes()); skeleton skel = proc_skele_dict[ps]; int result = skel(eqm->getArgTypes(), eqm->getArgs()); if(result == 0 ){ ExecuteSuccessMessage execute_success = new ExecuteSuccessMessage(name, eqm->getArgTypes(), eqm->getArgs()); int status = execute_success->send(sock); }else{ ExecuteFailureMessage execute_failure = new ExecuteFailureMessage(reasoncode); int status = execute_failure->send(sock); } } if (status == 0) { // client has closed the connection myToRemove.push_back(sock); return errorMsg; } } } } for (vector<int>::iterator it = myToRemove.begin(); it != myToRemove.end(); ++it) { myConnections.erase(remove(myConnections.begin(), myConnections.end(), *it), myConnections.end()); close(*it); } myToRemove.clear(); } } freeaddrinfo(servinfo); } int rpcInit(void){ int status; struct addrinfo hints; struct addrinfo* servinfo; struct addrinfo* p; memset(&hints, 0, sizeof hints); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; hints.ai_flags = AI_PASSIVE; status = getaddrinfo(NULL, "0", &hints, &servinfo); if (status != 0) { fprintf(stderr, "getaddrinfo error: %s\n", gai_strerror(status)); return 0; } p = servinfo; sock = socket(p->ai_family, p->ai_socktype, p->ai_protocol); status = bind(sock, servinfo->ai_addr, servinfo->ai_addrlen); status = listen(sock, 5); char hostname[256]; gethostname(hostname, 256); struct sockaddr_in sin; socklen_t len = sizeof(sin); getsockname(sock, (struct sockaddr *)&sin, &len); stringstream ss; ss << ntohs(sin.sin_port); string ps = ss.str(); serverIdentifier = hostname; port = ntohs(sin.sin_port); }<commit_msg>changes<commit_after>#include "server_functions.h" #include <stdio.h> #include <string.h> #include <iostream> #include <sstream> #include <netinet/in.h> #include <unistd.h> #include <sys/types.h> #include <sys/socket.h> #include <arpa/inet.h> #include <vector> #include <algorithm> #include <netdb.h> #include <stdlib.h> #include "segment.h" #include "message.h" #include "loc_success_message.h" #include "loc_failure_message.h" #include "loc_request_message.h" #include "execute_success_message.h" #include "execute_failure_message.h" #include "execute_request_message.h" #include "register_success_message.h" #include "register_failure_message.h" #include "register_request_message.h" #include "rpc.h" #include "constants.h" #include "helper_function.h" #include "message_types.h" #include "message_results.h" using namespace std; bool connectedToBinder = false; int binder_sock; int connectToBinder(){ if(connectedToBinder){ return 0; } char * binderAddressString = getenv ("BINDER_ADDRESS"); char * binderPortString = getenv("BINDER_PORT"); if(binderAddressString == NULL){ return 1; } if(binderPortString == NULL){ return 2; } binder_sock = createConnection(binderAddressString, binderPortString); if (binder_sock < 0) { return 3; }else{ connectedToBinder = true; } } int sendExecute(int sock, char* name, int* argTypes, void**args){ ExecuteRequestMessage execute_request = new ExecuteRequestMessage(name, argTypes, args); int status = execute_request->send(sock); int returnVal; char* retName; int* retArgTypes; void** retArgs; if(status == 0){ Segment * segment = 0; status = Segment::receive(sock, segment); if(segment->getType() == MSG_TYPE_EXECUTE_SUCCESS) { Message * cast = segment->getMessage(); ExecuteSuccessMessage * esm = dynamic_cast<ExecuteSuccessMessage*>(cast); retName = esm->getName(); retArgTypes = esm->getArgTypes(); retArgs = esm->getArgs(); if(strcmp(retName, name)){ //extractArgumentsMessage(replyMessageP, argTypes, args, argTypesLength, false); returnVal = 0; }else{ returnVal = 99; } }else if(segment->getType() == MSG_TYPE_EXECUTE_FAILURE){ Message * cast = segment->getMessage(); ExecuteFailureMessage * efm = dynamic_cast<ExecuteFailureMessage*>(cast); returnVal = efm->getReasonCode(); } }else{ //Something bad happened returnVal = 99; } return returnVal } int rpcCall(char * name, int * argTypes, void ** args) { int returnVal; char *serverAddress; char *serverPort; int server_socket if(!connectedToBinder){ returnVal = connectToBinder(); } //do something with returnVal LocRequestMessage loc_request = new LocRequestMessage(name, argTypes); int binder_status = loc_request->send(binder_sock); //maybe error check with binder_status /**Server stuff **/ if(status == 0){ Segment * segment = 0; status = Segment::receive(sock, segment); if(segment->getType() == MSG_TYPE_LOC_SUCCESS){ //'LOC_REQUEST' Message * cast = segment->getMessage(); LocSuccessMessage * lcm = dynamic_cast<LocSuccessMessage*>(cast); serverAddress = lcm->getServerIdentifier(); serverPort = lcm->getPort(); }else if(segment->getType() == MSG_TYPE_LOC_FAILURE){ //something bad happens return 1; } } int server_sock = createConnection(serverAddress, serverPort); int server_status = sendExecute(server_sock, name, argTypes, args); return server_status; } static map<procedure_signature, skeleton> proc_skele_dict; string serverIdentifier; unsigned int port; //int binder_sock; //only one binder socket variable int sock; //TODO: // CREATE SERVER // CONNECT TO BINDER struct thread_data { int sock; vector<string> *buf; }; void connect_to_binder() { char *serverAddress = getenv("BINDER_ADDRESS"); char *port = getenv("BINDER_PORT"); binder_sock = createConnection(serverAddress, port); return binder_sock; } int rpcRegister(char * name, int *argTypes, skeleton f){ int binder_sock = connect_to_binder(); int retStatus; RegisterRequestMessage request_message = new RegisterRequestMessage(serverIdentifier, port, name, argTypes); int status = success_message->send(binder_sock); if(status == 0){ //Success Segment * segment = 0; status = Segment::receive(binder_sock, segment); if(segment->getType() == MSG_TYPE_REGISTER_SUCCESS){ Message * cast = segment->getMessage(); RegisterSuccessMessage * rsm = dynamic_cast<RegisterSuccessMessage*>(cast); struct procedure_signature k(string(name), argTypes); proc_skele_dict[k] = f; }else if(segment->getType() == MSG_TYPE_REGISTER_FAILURE){ return 0; } }else if( status > 0){ //Warning return -99; }else if( status < 0){ //Error return 99; } } int rpcExecute(void){ //Create connection socket ot be used for accepting clients vector<int> myConnections; vector<int> myToRemove; fd_set readfds; int n; int status; struct sockaddr_storage their_addr; while(true){ //CONNECTIONS VECTOR FD_ZERO(&readfds); FD_SET(sock, &readfds); n = sock; for (vector<int>::iterator it = myConnections.begin();it != myConnections.end(); ++it) { int connection = *it; FD_SET(connection, &readfds); if (connection > n){ n = connection; } } n = n+1; status = select(n, &readfds, NULL, NULL, NULL); if (status == -1) { cerr << "ERROR: select failed." << endl; } else { if (FD_ISSET(sock, &readfds)) { socklen_t addr_size = sizeof their_addr; int new_sock = accept(sock, (struct sockaddr*)&their_addr, &addr_size); if (new_sock < 0) { cerr << "ERROR: while accepting connection" << endl; close(new_sock); continue; } myConnections.push_back(new_sock); } else { for (vector<int>::iterator it = myConnections.begin(); it != myConnections.end(); ++it) { int tempConnection = *it; if (FD_ISSET(tempConnection, &readfds)) { int reasonCode = 0; Segment * segment = 0; status = Segment::receive(sock, segment); if(segment->getType() == MSG_TYPE_EXECUTE_REQUEST){ Message * cast = segment->getMessage(); ExecuteRequestMessage * eqm = dynamic_cast<ExecuteRequestMessage*>(cast); procedure_signature ps = new procedure_signature(eqm->getName(), eqm->getArgTypes()); skeleton skel = proc_skele_dict[ps]; int result = skel(eqm->getArgTypes(), eqm->getArgs()); if(result == 0 ){ ExecuteSuccessMessage execute_success = new ExecuteSuccessMessage(name, eqm->getArgTypes(), eqm->getArgs()); int status = execute_success->send(sock); }else{ ExecuteFailureMessage execute_failure = new ExecuteFailureMessage(reasoncode); int status = execute_failure->send(sock); } } if (status == 0) { // client has closed the connection myToRemove.push_back(sock); return errorMsg; } } } } for (vector<int>::iterator it = myToRemove.begin(); it != myToRemove.end(); ++it) { myConnections.erase(remove(myConnections.begin(), myConnections.end(), *it), myConnections.end()); close(*it); } myToRemove.clear(); } } freeaddrinfo(servinfo); } int rpcInit(void){ int status; struct addrinfo hints; struct addrinfo* servinfo; struct addrinfo* p; memset(&hints, 0, sizeof hints); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; hints.ai_flags = AI_PASSIVE; status = getaddrinfo(NULL, "0", &hints, &servinfo); if (status != 0) { fprintf(stderr, "getaddrinfo error: %s\n", gai_strerror(status)); return 0; } p = servinfo; sock = socket(p->ai_family, p->ai_socktype, p->ai_protocol); status = bind(sock, servinfo->ai_addr, servinfo->ai_addrlen); status = listen(sock, 5); char hostname[256]; gethostname(hostname, 256); struct sockaddr_in sin; socklen_t len = sizeof(sin); getsockname(sock, (struct sockaddr *)&sin, &len); stringstream ss; ss << ntohs(sin.sin_port); string ps = ss.str(); serverIdentifier = hostname; port = ntohs(sin.sin_port); }<|endoftext|>
<commit_before>#include "esmtools.hpp" //---------------------------------------------------------- EsmTools::EsmTools(const std::string &path) { esm.readFile(path); } //---------------------------------------------------------- std::string EsmTools::dumpFile() { std::string dump; if(esm.getStatus() == true) { for(size_t i = 0; i < esm.getRecordColl().size(); ++i) { size_t cur_pos = 16; size_t cur_size = 0; std::string cur_id; std::string cur_text; std::string rec; esm.setRecordTo(i); rec = esm.getRecordContent(); dump += esm.getRecordId() + "\r\n"; while(cur_pos != rec.size()) { cur_id = rec.substr(cur_pos, 4); cur_size = tools.convertStringByteArrayToUInt(rec.substr(cur_pos + 4, 4)); cur_text = rec.substr(cur_pos + 8, cur_size); cur_text = tools.replaceNonReadableCharsWithDot(cur_text); dump += " " + cur_id + " " + std::to_string(cur_size) + " " + cur_text + "\r\n"; cur_pos += 8 + cur_size; } } } return dump; } //---------------------------------------------------------- std::string EsmTools::makeScriptList() { std::string scripts; if(esm.getStatus() == true) { for(size_t i = 0; i < esm.getRecordColl().size(); ++i) { esm.setRecordTo(i); if(esm.getRecordId() == "SCPT") { esm.setUniqueTo("SCHD"); scripts += esm.getUniqueText() + "\r\n"; scripts += "---\r\n"; esm.setFirstFriendlyTo("SCTX"); scripts += esm.getFriendlyText() + "\r\n"; scripts += "---\r\n"; esm.setFirstFriendlyTo("SCDT", false); scripts += tools.replaceNonReadableCharsWithDot(esm.getFriendlyText()) + "\r\n"; scripts += "---\r\n"; } } } return scripts; } <commit_msg>add banm script list creator<commit_after>#include "esmtools.hpp" //---------------------------------------------------------- EsmTools::EsmTools(const std::string &path) { esm.readFile(path); } //---------------------------------------------------------- std::string EsmTools::dumpFile() { std::string dump; if(esm.getStatus() == true) { for(size_t i = 0; i < esm.getRecordColl().size(); ++i) { size_t cur_pos = 16; size_t cur_size = 0; std::string cur_id; std::string cur_text; std::string rec; esm.setRecordTo(i); rec = esm.getRecordContent(); dump += esm.getRecordId() + "\r\n"; while(cur_pos != rec.size()) { cur_id = rec.substr(cur_pos, 4); cur_size = tools.convertStringByteArrayToUInt(rec.substr(cur_pos + 4, 4)); cur_text = rec.substr(cur_pos + 8, cur_size); cur_text = tools.replaceNonReadableCharsWithDot(cur_text); dump += " " + cur_id + " " + std::to_string(cur_size) + " " + cur_text + "\r\n"; cur_pos += 8 + cur_size; } } } return dump; } //---------------------------------------------------------- std::string EsmTools::makeScriptList() { std::string scripts; if(esm.getStatus() == true) { for(size_t i = 0; i < esm.getRecordColl().size(); ++i) { esm.setRecordTo(i); if(esm.getRecordId() == "INFO") { esm.setUniqueTo("INAM"); scripts += esm.getUniqueText() + "\r\n"; scripts += "---\r\n"; esm.setFirstFriendlyTo("BNAM"); scripts += esm.getFriendlyText() + "\r\n"; scripts += "---\r\n"; } if(esm.getRecordId() == "SCPT") { esm.setUniqueTo("SCHD"); scripts += esm.getUniqueText() + "\r\n"; scripts += "---\r\n"; esm.setFirstFriendlyTo("SCTX"); scripts += esm.getFriendlyText() + "\r\n"; scripts += "---\r\n"; esm.setFirstFriendlyTo("SCDT", false); scripts += tools.replaceNonReadableCharsWithDot(esm.getFriendlyText()) + "\r\n"; scripts += "---\r\n"; } } } return scripts; } <|endoftext|>
<commit_before>/* * Copyright (C) 2015-2018 dubalu.com LLC. All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to * deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. */ #include "exception.h" #include <cstdarg> // for va_end, va_list, va_start #include <cstdio> // for vsnprintf #include <cstdlib> // for free #include <cstring> // for strtok_r #include <cxxabi.h> // for abi::__cxa_demangle #include <execinfo.h> // for backtrace, backtrace_symbols #define BUFFER_SIZE 1024 std::string traceback(const std::string& filename, int line, void *const * callstack, int frames) { std::string tb = "\n== Traceback at (" + filename + ":" + std::to_string(line) + ")"; if (frames == 0) { return tb; } tb.push_back(':'); // resolve addresses into strings containing "filename(function+address)" char** strs = backtrace_symbols(callstack, frames); // iterate over the returned symbol lines. skip the first, it is the // address of this function. for (int i = 1; i < frames; ++i) { int status = 0; const char *sep = "\t ()+"; char *mangled, *lasts; std::string result; for (mangled = strtok_r(strs[i], sep, &lasts); mangled; mangled = strtok_r(nullptr, sep, &lasts)) { char* unmangled = abi::__cxa_demangle(mangled, nullptr, 0, &status); if (!result.empty()) { result += " "; } if (status == 0) { result += unmangled; } else { result += mangled; } free(unmangled); } tb += "\n " + result; } free(strs); return tb; } std::string traceback(const std::string& filename, int line) { void* callstack[128]; // retrieve current stack addresses int frames = backtrace(callstack, sizeof(callstack) / sizeof(void*)); auto tb = traceback(filename, line, callstack, frames); if (frames == 0) { tb.append(":\n <empty, possibly corrupt>"); } return tb; } BaseException::BaseException() : line{0}, frames{0}, callstack{{}} { } BaseException::BaseException(const BaseException& exc) : type{exc.type}, message{exc.message}, context{exc.context}, traceback{exc.traceback}, filename{exc.filename}, line{exc.line}, frames{exc.frames} { memcpy(callstack, exc.callstack, frames * sizeof(void*)); } BaseException::BaseException(BaseException&& exc) : type{std::move(exc.type)}, message{std::move(exc.message)}, context{std::move(exc.context)}, traceback{std::move(exc.traceback)}, filename{std::move(exc.filename)}, line{std::move(exc.line)}, callstack{std::move(exc.callstack)}, frames{std::move(exc.frames)} { } BaseException::BaseException(const BaseException* exc) : BaseException(exc ? *exc : BaseException()) { } BaseException::BaseException(const char *filename, int line, const char* type, const char *format, ...) : type(type), filename(filename), line(line), frames(0) { va_list argptr; va_start(argptr, format); // Figure out the length of the formatted message. va_list argptr_copy; va_copy(argptr_copy, argptr); auto len = vsnprintf(nullptr, 0, format, argptr_copy); va_end(argptr_copy); // Make a string to hold the formatted message. message.resize(len + 1); message.resize(vsnprintf(&message[0], len + 1, format, argptr)); va_end(argptr); #ifdef XAPIAND_TRACEBACKS frames = backtrace(callstack, sizeof(callstack) / sizeof(void*)); #endif } const char* BaseException::get_message() const { if (message.empty()) { message.assign(type); } return message.c_str(); } const char* BaseException::get_context() const { if (context.empty()) { context.assign(filename + ":" + std::to_string(line) + ": " + get_message()); } return context.c_str(); } const char* BaseException::get_traceback() const { if (traceback.empty()) { traceback = ::traceback(filename, line, callstack, frames); } return traceback.c_str(); } <commit_msg>Exception: Reordered initialization<commit_after>/* * Copyright (C) 2015-2018 dubalu.com LLC. All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to * deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. */ #include "exception.h" #include <cstdarg> // for va_end, va_list, va_start #include <cstdio> // for vsnprintf #include <cstdlib> // for free #include <cstring> // for strtok_r #include <cxxabi.h> // for abi::__cxa_demangle #include <execinfo.h> // for backtrace, backtrace_symbols #define BUFFER_SIZE 1024 std::string traceback(const std::string& filename, int line, void *const * callstack, int frames) { std::string tb = "\n== Traceback at (" + filename + ":" + std::to_string(line) + ")"; if (frames == 0) { return tb; } tb.push_back(':'); // resolve addresses into strings containing "filename(function+address)" char** strs = backtrace_symbols(callstack, frames); // iterate over the returned symbol lines. skip the first, it is the // address of this function. for (int i = 1; i < frames; ++i) { int status = 0; const char *sep = "\t ()+"; char *mangled, *lasts; std::string result; for (mangled = strtok_r(strs[i], sep, &lasts); mangled; mangled = strtok_r(nullptr, sep, &lasts)) { char* unmangled = abi::__cxa_demangle(mangled, nullptr, 0, &status); if (!result.empty()) { result += " "; } if (status == 0) { result += unmangled; } else { result += mangled; } free(unmangled); } tb += "\n " + result; } free(strs); return tb; } std::string traceback(const std::string& filename, int line) { void* callstack[128]; // retrieve current stack addresses int frames = backtrace(callstack, sizeof(callstack) / sizeof(void*)); auto tb = traceback(filename, line, callstack, frames); if (frames == 0) { tb.append(":\n <empty, possibly corrupt>"); } return tb; } BaseException::BaseException() : line{0}, callstack{{}}, frames{0} { } BaseException::BaseException(const BaseException& exc) : type{exc.type}, filename{exc.filename}, line{exc.line}, frames{exc.frames}, message{exc.message}, context{exc.context}, traceback{exc.traceback} { memcpy(callstack, exc.callstack, frames * sizeof(void*)); } BaseException::BaseException(BaseException&& exc) : type{std::move(exc.type)}, filename{std::move(exc.filename)}, line{std::move(exc.line)}, callstack{std::move(exc.callstack)}, frames{std::move(exc.frames)}, message{std::move(exc.message)}, context{std::move(exc.context)}, traceback{std::move(exc.traceback)} { } BaseException::BaseException(const BaseException* exc) : BaseException(exc ? *exc : BaseException()) { } BaseException::BaseException(const char *filename, int line, const char* type, const char *format, ...) : type(type), filename(filename), line(line), frames(0) { va_list argptr; va_start(argptr, format); // Figure out the length of the formatted message. va_list argptr_copy; va_copy(argptr_copy, argptr); auto len = vsnprintf(nullptr, 0, format, argptr_copy); va_end(argptr_copy); // Make a string to hold the formatted message. message.resize(len + 1); message.resize(vsnprintf(&message[0], len + 1, format, argptr)); va_end(argptr); #ifdef XAPIAND_TRACEBACKS frames = backtrace(callstack, sizeof(callstack) / sizeof(void*)); #endif } const char* BaseException::get_message() const { if (message.empty()) { message.assign(type); } return message.c_str(); } const char* BaseException::get_context() const { if (context.empty()) { context.assign(filename + ":" + std::to_string(line) + ": " + get_message()); } return context.c_str(); } const char* BaseException::get_traceback() const { if (traceback.empty()) { traceback = ::traceback(filename, line, callstack, frames); } return traceback.c_str(); } <|endoftext|>
<commit_before>//======================================================================= // Copyright (c) 2013-2020 Baptiste Wicht. // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #include <iostream> #include <fstream> #include <sstream> #include "expenses.hpp" #include "args.hpp" #include "accounts.hpp" #include "data.hpp" #include "guid.hpp" #include "config.hpp" #include "utils.hpp" #include "console.hpp" #include "writer.hpp" #include "budget_exception.hpp" using namespace budget; namespace { static data_handler<expense> expenses { "expenses", "expenses.data" }; void show_templates(){ std::vector<std::string> columns = {"ID", "Account", "Name", "Amount"}; std::vector<std::vector<std::string>> contents; size_t count = 0; for(auto& expense : expenses.data()){ if(expense.date == TEMPLATE_DATE){ contents.push_back({to_string(expense.id), get_account(expense.account).name, expense.name, to_string(expense.amount)}); ++count; } } if(count == 0){ std::cout << "No templates" << std::endl; } else { console_writer w(std::cout); w.display_table(columns, contents); } } } //end of anonymous namespace std::map<std::string, std::string> budget::expense::get_params() const { std::map<std::string, std::string> params; params["input_id"] = budget::to_string(id); params["input_guid"] = guid; params["input_date"] = budget::to_string(date); params["input_name"] = name; params["input_account"] = budget::to_string(account); params["input_amount"] = budget::to_string(amount); return params; } void budget::expenses_module::load(){ load_expenses(); load_accounts(); } void budget::expenses_module::unload(){ save_expenses(); } void budget::expenses_module::handle(const std::vector<std::string>& args){ console_writer w(std::cout); if(args.size() == 1){ show_expenses(w); } else { auto& subcommand = args[1]; if(subcommand == "show"){ if(args.size() == 2){ show_expenses(w); } else if(args.size() == 3){ show_expenses(budget::month(to_number<unsigned short>(args[2])), w); } else if(args.size() == 4){ show_expenses( budget::month(to_number<unsigned short>(args[2])), budget::year(to_number<unsigned short>(args[3])), w); } else { throw budget_exception("Too many arguments to expense show"); } } else if(subcommand == "all"){ show_all_expenses(w); } else if(subcommand == "template"){ show_templates(); } else if(subcommand == "add"){ if(args.size() > 2){ std::string template_name; std::string space; for(size_t i = 2; i < args.size(); ++i){ template_name += space; template_name += args[i]; space = " "; } bool template_found = false; for(auto& template_expense : all_expenses()){ if(template_expense.date == TEMPLATE_DATE && template_expense.name == template_name){ expense expense; expense.guid = generate_guid(); expense.date = budget::local_day(); expense.name = template_expense.name; expense.amount = template_expense.amount; expense.account = template_expense.account; auto id = expenses.add(std::move(expense)); std::cout << "Expense " << id << " has been created" << std::endl; template_found = true; break; } } if(!template_found){ std::cout << "Template \"" << template_name << "\" not found, creating a new template" << std::endl; expense expense; expense.guid = generate_guid(); expense.date = TEMPLATE_DATE; expense.name = template_name; std::string account_name; edit_string_complete(account_name, "Account", all_account_names(), not_empty_checker(), account_checker()); expense.account = get_account(account_name, expense.date.year(), expense.date.month()).id; edit_money(expense.amount, "Amount", not_negative_checker(), not_zero_checker()); auto id = expenses.add(std::move(expense)); std::cout << "Template " << id << " has been created" << std::endl; } } else { expense expense; expense.guid = generate_guid(); expense.date = budget::local_day(); std::string account_name; if (config_contains("default_account")) { auto default_account = config_value("default_account"); if (account_exists(default_account)) { account_name = default_account; } else { std::cerr << "error: The default account set in the configuration does not exist, ignoring it" << std::endl; } } edit_date(expense.date, "Date"); edit_string_complete(account_name, "Account", all_account_names(), not_empty_checker(), account_checker(expense.date)); expense.account = get_account(account_name, expense.date.year(), expense.date.month()).id; edit_string(expense.name, "Name", not_empty_checker()); edit_money(expense.amount, "Amount", not_negative_checker(), not_zero_checker()); auto id = expenses.add(std::move(expense)); std::cout << "Expense " << id << " has been created" << std::endl; } } else if(subcommand == "delete"){ enough_args(args, 3); size_t id = to_number<size_t>(args[2]); if (expenses.remove(id)) { std::cout << "Expense " << id << " has been deleted" << std::endl; } else { throw budget_exception("There are no expense with id "); } } else if(subcommand == "edit"){ enough_args(args, 3); size_t id = to_number<size_t>(args[2]); auto expense = expenses[id]; edit_date(expense.date, "Date"); auto account_name = get_account(expense.account).name; edit_string_complete(account_name, "Account", all_account_names(), not_empty_checker(), account_checker(expense.date)); expense.account = get_account(account_name, expense.date.year(), expense.date.month()).id; edit_string(expense.name, "Name", not_empty_checker()); edit_money(expense.amount, "Amount", not_negative_checker(), not_zero_checker()); if (expenses.indirect_edit(expense)) { std::cout << "Expense " << id << " has been modified" << std::endl; } } else if (subcommand == "search") { std::string search; edit_string(search, "Search", not_empty_checker()); search_expenses(search, w); } else { throw budget_exception("Invalid subcommand \"" + subcommand + "\""); } } } void budget::load_expenses(){ expenses.load(); } void budget::save_expenses(){ expenses.save(); } void budget::add_expense(budget::expense&& expense){ expenses.add(std::forward<budget::expense>(expense)); } bool budget::edit_expense(const expense& expense){ return expenses.indirect_edit(expense); } std::ostream& budget::operator<<(std::ostream& stream, const expense& expense){ return stream << expense.id << ':' << expense.guid << ':' << expense.account << ':' << expense.name << ':' << expense.amount << ':' << to_string(expense.date); } void budget::operator>>(const std::vector<std::string>& parts, expense& expense){ bool random = config_contains("random"); expense.id = to_number<size_t>(parts.at(0)); expense.guid = parts.at(1); expense.account = to_number<size_t>(parts.at(2)); expense.name = parts.at(3); expense.date = from_string(parts.at(5)); if(random){ expense.amount = budget::random_money(10, 1500); } else { expense.amount = parse_money(parts.at(4)); } } std::vector<expense> budget::all_expenses(){ return expenses.data(); } bool budget::indirect_edit_expense(const expense & expense, bool propagate) { return expenses.indirect_edit(expense, propagate); } void budget::set_expenses_changed(){ expenses.set_changed(); } void budget::show_all_expenses(budget::writer& w){ w << title_begin << "All Expenses " << add_button("expenses") << title_end; std::vector<std::string> columns = {"ID", "Date", "Account", "Name", "Amount", "Edit"}; std::vector<std::vector<std::string>> contents; for(auto& expense : expenses.data()){ contents.push_back({to_string(expense.id), to_string(expense.date), get_account(expense.account).name, expense.name, to_string(expense.amount), "::edit::expenses::" + to_string(expense.id)}); } w.display_table(columns, contents); } void budget::search_expenses(const std::string& search, budget::writer& w){ w << title_begin << "Results" << title_end; std::vector<std::string> columns = {"ID", "Date", "Account", "Name", "Amount", "Edit"}; std::vector<std::vector<std::string>> contents; money total; size_t count = 0; auto l_search = search; std::transform(l_search.begin(), l_search.end(), l_search.begin(), ::tolower); for(auto& expense : expenses.data()){ auto l_name = expense.name; std::transform(l_name.begin(), l_name.end(), l_name.begin(), ::tolower); if(l_name.find(l_search) != std::string::npos){ contents.push_back({to_string(expense.id), to_string(expense.date), get_account(expense.account).name, expense.name, to_string(expense.amount), "::edit::expenses::" + to_string(expense.id)}); total += expense.amount; ++count; } } if(count == 0){ w << "No expenses found" << end_of_line; } else { contents.push_back({"", "", "", "Total", to_string(total), ""}); w.display_table(columns, contents, 1, {}, 0, 1); } } void budget::show_expenses(budget::month month, budget::year year, budget::writer& w){ w << title_begin << "Expenses of " << month << " " << year << " " << add_button("expenses") << budget::year_month_selector{"expenses", year, month} << title_end; std::vector<std::string> columns = {"ID", "Date", "Account", "Name", "Amount", "Edit"}; std::vector<std::vector<std::string>> contents; money total; size_t count = 0; for(auto& expense : expenses.data()){ if(expense.date.year() == year && expense.date.month() == month){ contents.push_back({to_string(expense.id), to_string(expense.date), get_account(expense.account).name, expense.name, to_string(expense.amount), "::edit::expenses::" + to_string(expense.id)}); total += expense.amount; ++count; } } if(count == 0){ w << "No expenses for " << month << "-" << year << end_of_line; } else { contents.push_back({"", "", "", "Total", to_string(total), ""}); w.display_table(columns, contents, 1, {}, 0, 1); } } void budget::show_expenses(budget::month month, budget::writer& w){ auto today = budget::local_day(); show_expenses(month, today.year(), w); } void budget::show_expenses(budget::writer& w){ auto today = budget::local_day(); show_expenses(today.month(), today.year(), w); } bool budget::expense_exists(size_t id){ return expenses.exists(id); } void budget::expense_delete(size_t id) { if (!expenses.exists(id)) { throw budget_exception("There are no expense with id "); } expenses.remove(id); } expense budget::expense_get(size_t id) { return expenses[id]; } filter_view<expense> budget::all_expenses_year(data_cache & cache, budget::year year) { return make_filter_view(cache.expenses(), [=](const expense& e) { return e.date.year() == year; }); } filter_view<expense> budget::all_expenses_month(data_cache & cache, budget::year year, budget::month month) { return make_filter_view(cache.expenses(), [=](const expense& e) { return e.date.year() == year && e.date.month() == month; }); } filter_view<expense> budget::all_expenses_month(data_cache & cache, size_t account_id, budget::year year, budget::month month) { return make_filter_view(cache.expenses(), [=](const expense& e) { return e.account == account_id && e.date.year() == year && e.date.month() == month; }); } filter_view<expense> budget::all_expenses_between(data_cache & cache, budget::year year, budget::month sm, budget::month month) { return make_filter_view(cache.expenses(), [=](const expense& e) { return e.date.year() == year && e.date.month() >= sm && e.date.month() <= month; }); } filter_view<expense> budget::all_expenses_between(data_cache & cache, size_t account_id, budget::year year, budget::month sm, budget::month month) { return make_filter_view(cache.expenses(), [=](const expense& e) { return e.account == account_id && e.date.year() == year && e.date.month() >= sm && e.date.month() <= month; }); } <commit_msg>Some reformating<commit_after>//======================================================================= // Copyright (c) 2013-2020 Baptiste Wicht. // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #include <iostream> #include <fstream> #include <sstream> #include "expenses.hpp" #include "args.hpp" #include "accounts.hpp" #include "data.hpp" #include "guid.hpp" #include "config.hpp" #include "utils.hpp" #include "console.hpp" #include "writer.hpp" #include "budget_exception.hpp" using namespace budget; namespace { static data_handler<expense> expenses { "expenses", "expenses.data" }; void show_templates() { std::vector<std::string> columns = {"ID", "Account", "Name", "Amount"}; std::vector<std::vector<std::string>> contents; size_t count = 0; for (auto& expense : expenses.data()) { if (expense.date == TEMPLATE_DATE) { contents.push_back({to_string(expense.id), get_account(expense.account).name, expense.name, to_string(expense.amount)}); ++count; } } if (count == 0) { std::cout << "No templates" << std::endl; } else { console_writer w(std::cout); w.display_table(columns, contents); } } } //end of anonymous namespace std::map<std::string, std::string> budget::expense::get_params() const { std::map<std::string, std::string> params; params["input_id"] = budget::to_string(id); params["input_guid"] = guid; params["input_date"] = budget::to_string(date); params["input_name"] = name; params["input_account"] = budget::to_string(account); params["input_amount"] = budget::to_string(amount); return params; } void budget::expenses_module::load(){ load_expenses(); load_accounts(); } void budget::expenses_module::unload(){ save_expenses(); } void budget::expenses_module::handle(const std::vector<std::string>& args){ console_writer w(std::cout); if(args.size() == 1){ show_expenses(w); } else { auto& subcommand = args[1]; if(subcommand == "show"){ if(args.size() == 2){ show_expenses(w); } else if(args.size() == 3){ show_expenses(budget::month(to_number<unsigned short>(args[2])), w); } else if(args.size() == 4){ show_expenses( budget::month(to_number<unsigned short>(args[2])), budget::year(to_number<unsigned short>(args[3])), w); } else { throw budget_exception("Too many arguments to expense show"); } } else if(subcommand == "all"){ show_all_expenses(w); } else if(subcommand == "template"){ show_templates(); } else if(subcommand == "add"){ if(args.size() > 2){ std::string template_name; std::string space; for(size_t i = 2; i < args.size(); ++i){ template_name += space; template_name += args[i]; space = " "; } bool template_found = false; for (auto& template_expense : all_expenses()) { if (template_expense.date == TEMPLATE_DATE && template_expense.name == template_name) { expense expense; expense.guid = generate_guid(); expense.date = budget::local_day(); expense.name = template_expense.name; expense.amount = template_expense.amount; expense.account = template_expense.account; auto id = expenses.add(std::move(expense)); std::cout << "Expense " << id << " has been created" << std::endl; template_found = true; break; } } if (!template_found) { std::cout << "Template \"" << template_name << "\" not found, creating a new template" << std::endl; expense expense; expense.guid = generate_guid(); expense.date = TEMPLATE_DATE; expense.name = template_name; std::string account_name; edit_string_complete(account_name, "Account", all_account_names(), not_empty_checker(), account_checker()); expense.account = get_account(account_name, expense.date.year(), expense.date.month()).id; edit_money(expense.amount, "Amount", not_negative_checker(), not_zero_checker()); auto id = expenses.add(std::move(expense)); std::cout << "Template " << id << " has been created" << std::endl; } } else { expense expense; expense.guid = generate_guid(); expense.date = budget::local_day(); std::string account_name; if (config_contains("default_account")) { auto default_account = config_value("default_account"); if (account_exists(default_account)) { account_name = default_account; } else { std::cerr << "error: The default account set in the configuration does not exist, ignoring it" << std::endl; } } edit_date(expense.date, "Date"); edit_string_complete(account_name, "Account", all_account_names(), not_empty_checker(), account_checker(expense.date)); expense.account = get_account(account_name, expense.date.year(), expense.date.month()).id; edit_string(expense.name, "Name", not_empty_checker()); edit_money(expense.amount, "Amount", not_negative_checker(), not_zero_checker()); auto id = expenses.add(std::move(expense)); std::cout << "Expense " << id << " has been created" << std::endl; } } else if(subcommand == "delete"){ enough_args(args, 3); size_t id = to_number<size_t>(args[2]); if (expenses.remove(id)) { std::cout << "Expense " << id << " has been deleted" << std::endl; } else { throw budget_exception("There are no expense with id "); } } else if(subcommand == "edit"){ enough_args(args, 3); size_t id = to_number<size_t>(args[2]); auto expense = expenses[id]; edit_date(expense.date, "Date"); auto account_name = get_account(expense.account).name; edit_string_complete(account_name, "Account", all_account_names(), not_empty_checker(), account_checker(expense.date)); expense.account = get_account(account_name, expense.date.year(), expense.date.month()).id; edit_string(expense.name, "Name", not_empty_checker()); edit_money(expense.amount, "Amount", not_negative_checker(), not_zero_checker()); if (expenses.indirect_edit(expense)) { std::cout << "Expense " << id << " has been modified" << std::endl; } } else if (subcommand == "search") { std::string search; edit_string(search, "Search", not_empty_checker()); search_expenses(search, w); } else { throw budget_exception("Invalid subcommand \"" + subcommand + "\""); } } } void budget::load_expenses(){ expenses.load(); } void budget::save_expenses(){ expenses.save(); } void budget::add_expense(budget::expense&& expense){ expenses.add(std::forward<budget::expense>(expense)); } bool budget::edit_expense(const expense& expense){ return expenses.indirect_edit(expense); } std::ostream& budget::operator<<(std::ostream& stream, const expense& expense){ return stream << expense.id << ':' << expense.guid << ':' << expense.account << ':' << expense.name << ':' << expense.amount << ':' << to_string(expense.date); } void budget::operator>>(const std::vector<std::string>& parts, expense& expense){ bool random = config_contains("random"); expense.id = to_number<size_t>(parts.at(0)); expense.guid = parts.at(1); expense.account = to_number<size_t>(parts.at(2)); expense.name = parts.at(3); expense.date = from_string(parts.at(5)); if (random) { expense.amount = budget::random_money(10, 1500); } else { expense.amount = parse_money(parts.at(4)); } } std::vector<expense> budget::all_expenses(){ return expenses.data(); } bool budget::indirect_edit_expense(const expense & expense, bool propagate) { return expenses.indirect_edit(expense, propagate); } void budget::set_expenses_changed(){ expenses.set_changed(); } void budget::show_all_expenses(budget::writer& w){ w << title_begin << "All Expenses " << add_button("expenses") << title_end; std::vector<std::string> columns = {"ID", "Date", "Account", "Name", "Amount", "Edit"}; std::vector<std::vector<std::string>> contents; for (auto& expense : expenses.data()) { contents.push_back({to_string(expense.id), to_string(expense.date), get_account(expense.account).name, expense.name, to_string(expense.amount), "::edit::expenses::" + to_string(expense.id)}); } w.display_table(columns, contents); } void budget::search_expenses(const std::string& search, budget::writer& w){ w << title_begin << "Results" << title_end; std::vector<std::string> columns = {"ID", "Date", "Account", "Name", "Amount", "Edit"}; std::vector<std::vector<std::string>> contents; money total; size_t count = 0; auto l_search = search; std::transform(l_search.begin(), l_search.end(), l_search.begin(), ::tolower); for (auto& expense : expenses.data()) { auto l_name = expense.name; std::transform(l_name.begin(), l_name.end(), l_name.begin(), ::tolower); if (l_name.find(l_search) != std::string::npos) { contents.push_back({to_string(expense.id), to_string(expense.date), get_account(expense.account).name, expense.name, to_string(expense.amount), "::edit::expenses::" + to_string(expense.id)}); total += expense.amount; ++count; } } if(count == 0){ w << "No expenses found" << end_of_line; } else { contents.push_back({"", "", "", "Total", to_string(total), ""}); w.display_table(columns, contents, 1, {}, 0, 1); } } void budget::show_expenses(budget::month month, budget::year year, budget::writer& w){ w << title_begin << "Expenses of " << month << " " << year << " " << add_button("expenses") << budget::year_month_selector{"expenses", year, month} << title_end; std::vector<std::string> columns = {"ID", "Date", "Account", "Name", "Amount", "Edit"}; std::vector<std::vector<std::string>> contents; money total; size_t count = 0; for (auto& expense : expenses.data()) { if (expense.date.year() == year && expense.date.month() == month) { contents.push_back({to_string(expense.id), to_string(expense.date), get_account(expense.account).name, expense.name, to_string(expense.amount), "::edit::expenses::" + to_string(expense.id)}); total += expense.amount; ++count; } } if(count == 0){ w << "No expenses for " << month << "-" << year << end_of_line; } else { contents.push_back({"", "", "", "Total", to_string(total), ""}); w.display_table(columns, contents, 1, {}, 0, 1); } } void budget::show_expenses(budget::month month, budget::writer& w){ auto today = budget::local_day(); show_expenses(month, today.year(), w); } void budget::show_expenses(budget::writer& w){ auto today = budget::local_day(); show_expenses(today.month(), today.year(), w); } bool budget::expense_exists(size_t id){ return expenses.exists(id); } void budget::expense_delete(size_t id) { if (!expenses.exists(id)) { throw budget_exception("There are no expense with id "); } expenses.remove(id); } expense budget::expense_get(size_t id) { return expenses[id]; } filter_view<expense> budget::all_expenses_year(data_cache & cache, budget::year year) { return make_filter_view(cache.expenses(), [=](const expense& e) { return e.date.year() == year; }); } filter_view<expense> budget::all_expenses_month(data_cache & cache, budget::year year, budget::month month) { return make_filter_view(cache.expenses(), [=](const expense& e) { return e.date.year() == year && e.date.month() == month; }); } filter_view<expense> budget::all_expenses_month(data_cache & cache, size_t account_id, budget::year year, budget::month month) { return make_filter_view(cache.expenses(), [=](const expense& e) { return e.account == account_id && e.date.year() == year && e.date.month() == month; }); } filter_view<expense> budget::all_expenses_between(data_cache & cache, budget::year year, budget::month sm, budget::month month) { return make_filter_view(cache.expenses(), [=](const expense& e) { return e.date.year() == year && e.date.month() >= sm && e.date.month() <= month; }); } filter_view<expense> budget::all_expenses_between(data_cache & cache, size_t account_id, budget::year year, budget::month sm, budget::month month) { return make_filter_view(cache.expenses(), [=](const expense& e) { return e.account == account_id && e.date.year() == year && e.date.month() >= sm && e.date.month() <= month; }); } <|endoftext|>
<commit_before>/** * Fass.cc * * Author: Sara Vallero * Author: Valentina Zaccolo */ #include "Fass.h" #include "FassLog.h" #include "Configurator.h" #include "InitShares.h" #include "FassDb.h" //#include "Log.h" //#include "RPCManager.h" //#include "PriorityManager.h" #include <fstream> #include <signal.h> #include <sstream> #include <stdexcept> #include <unistd.h> //#include <stdlib.h> //#include <libxml/parser.h> //#include <fcntl.h> //#include <sys/types.h> //#include <sys/stat.h> //#include <pthread.h> #include <iostream> using namespace std; void Fass::start(bool bootstrap_only) { bool rc; //int fd; sigset_t mask; int signal; char hn[80]; /// returns the null-terminated hostname in the character /// array hn, which has a length of 79 bytes. /// is hostname used somewhere? if ( gethostname(hn,79) != 0 ) { throw runtime_error("Error getting hostname"); } hostname = hn; /** Configuration system */ fass_configuration = new FassConfigurator(etc_location, var_location); rc = fass_configuration->load_configuration(); if ( !rc ) { throw runtime_error("Could not load Fass configuration file."); } /** Initial shares system */ //initial_shares = new FassInitShares(etc_location, var_location); //rc = initial_shares->load_shares(); //if ( !rc ) //{ // throw runtime_error("Could not load initial shares file."); //} /** Log system */ ostringstream os; try{ Log::MessageType clevel; clevel = get_debug_level(); /// Initializing FASS daemon log system string log_fname; log_fname = log_location + "fass.log"; FassLog::init_log_system(clevel, log_fname.c_str(), ios_base::trunc, "fassd"); os << "Starting " << version() << endl; os << "----------------------------------------\n"; os << " Fass Configuration File \n"; os << "----------------------------------------\n"; os << fass_configuration->get_conf_fname() << " \n"; os << "----------------------------------------"; FassLog::log("FASS",Log::INFO,os); fass_configuration->print_loaded_options(); } catch(runtime_error&){ throw; } /** Initialize the XML library */ // Try to avoid it // xmlInitParser(); /** Database */ // instance of specific DB (can be changed) string dbtype; string dbendpoint; string dbname; int dbport; fass_configuration->get_single_option("database", "type", dbtype); fass_configuration->get_single_option("database", "endpoint", dbendpoint); fass_configuration->get_single_option("database", "port", dbport); fass_configuration->get_single_option("database", "name", dbname); if ( dbtype == "influxdb" ){ // TODO: should be done with a switch and enum, not critical database = new InfluxDb(dbendpoint, dbport, dbname); } else { FassLog::log("FASS", Log::ERROR, "Unknown database type!"); throw; } // FOR VALE: database should be passed as argument to the Priority Manager /** Block all signals before creating any thread */ sigfillset(&mask); pthread_sigmask(SIG_BLOCK, &mask, NULL); /** Managers */ // some config variables are used both by the RPCManager and the XMLRPCClient (called by the PM) // we use the same valuse for both server/client, these should be consistent with the OpenNebula ones int message_size; int timeout; // OpenNebula xml-rpc endpoint string one_endpoint; string one_port; fass_configuration->get_single_option("fass", "one_endpoint", one_endpoint); fass_configuration->get_single_option("fass", "one_port", one_port); one_endpoint.append(":"); one_endpoint.append(one_port); one_endpoint.append("/RPC2"); //FassLog::log("FASS", Log::DEBUG, one_endpoint); // OpenNebula authentication string one_secret; fass_configuration->get_single_option("fass", "one_secret", one_secret); // xml-rpc config fass_configuration->get_single_option("rpcm", "message_size", message_size); fass_configuration->get_single_option("rpcm", "timeout", timeout); /// ---- Priority Manager ---- try { int manager_timer; int machines_limit; fass_configuration->get_single_option("pm", "max_vm", machines_limit); fass_configuration->get_single_option("pm", "manager_timer", manager_timer); // Read initial shares from separate file //initial_shares = new FassConfigurator(etc_location, var_location); //rc = initial_shares->load_configuration(); //if ( !rc ) //{ // throw runtime_error("Could not load Initial Shares file."); //} //std::vector<user> users; //std::list<users> list_of_users; // TODO add the shares vector //initial_shares->get_single_option("users", "user", user); //list_of_users::iterator list_it; //for (list_it = users.begin(); list_it != users.end(); ++list_it) //{ // list_of_users.insert(list_it,users); //} //pm = new PriorityManager(one_endpoint, one_secret, message_size, timeout, machines_limit, manager_timer, list_of_users); pm = new PriorityManager(one_endpoint, one_secret, message_size, timeout, machines_limit, manager_timer); } catch (bad_alloc&) { FassLog::log("FASS", Log::ERROR, "Error creating Priority Manager"); throw; } /// ---- Start the Priority Manager ---- rc = pm->start(); if ( !rc ) { throw runtime_error("Could not start the Priority Manager"); } /// ---- Request Manager ---- try { //int rm_port = 0; string rm_port = ""; int max_conn; int max_conn_backlog; int keepalive_timeout; int keepalive_max_conn; bool rpc_log; string log_call_format; string rpc_filename = ""; string rm_listen_address; //= "0.0.0.0"; fass_configuration->get_single_option("rpcm", "listen_port", rm_port); fass_configuration->get_single_option("rpcm", "listen_address", rm_listen_address); fass_configuration->get_single_option("rpcm", "max_conn", max_conn); fass_configuration->get_single_option("rpcm", "max_conn_backlog", max_conn_backlog); fass_configuration->get_single_option("rpcm", "keepalive_timeout", keepalive_timeout); fass_configuration->get_single_option("rpcm", "keepalive_max_conn", keepalive_max_conn); fass_configuration->get_single_option("rpcm", "rpc_log", rpc_log); fass_configuration->get_single_option("rpcm", "log_call_format", log_call_format); if (rpc_log) { rpc_filename = log_location + "fass_xmlrpc.log"; } rpcm = new RPCManager(one_endpoint,rm_port, max_conn, max_conn_backlog, keepalive_timeout, keepalive_max_conn, timeout, rpc_filename, log_call_format, rm_listen_address, message_size); } catch (bad_alloc&) { FassLog::log("FASS", Log::ERROR, "Error creating RPC Manager"); throw; } /// ---- Start the Request Manager ---- rc = rpcm->start(); if ( !rc ) { throw runtime_error("Could not start the RPC Manager"); } /** Wait for a SIGTERM or SIGINT signal */ sigemptyset(&mask); sigaddset(&mask, SIGINT); sigaddset(&mask, SIGTERM); sigwait(&mask, &signal); /** Stop the managers and free resources */ pm->finalize(); //sleep to wait drivers??? pthread_join(rpcm->get_thread_id(),0); pthread_join(pm->get_thread_id(),0); //XML Library // xmlCleanupParser(); FassLog::log("FASS", Log::INFO, "All modules finalized, exiting.\n"); return; //error_mad: // Log::log("FASS", Log::ERROR, "Could not load driver"); // throw runtime_error("Could not load a Fass driver"); } Log::MessageType Fass::get_debug_level() const { Log::MessageType clevel = Log::ERROR; int log_level_int ; fass_configuration->get_single_option("fass", "log_level", log_level_int); if ( log_level_int != 0 ) { if ( Log::ERROR <= log_level_int && log_level_int <= Log::DDDEBUG ) { clevel = static_cast<Log::MessageType>(log_level_int); } } return clevel; } <commit_msg>Update Fass.cc<commit_after>/** * Copyright © 2017 INFN Torino - INDIGO-DataCloud * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "Fass.h" #include "FassLog.h" #include "Configurator.h" #include "InitShares.h" #include "FassDb.h" //#include "Log.h" //#include "RPCManager.h" //#include "PriorityManager.h" #include <fstream> #include <signal.h> #include <sstream> #include <stdexcept> #include <unistd.h> //#include <stdlib.h> //#include <libxml/parser.h> //#include <fcntl.h> //#include <sys/types.h> //#include <sys/stat.h> //#include <pthread.h> #include <iostream> using namespace std; void Fass::start(bool bootstrap_only) { bool rc; //int fd; sigset_t mask; int signal; char hn[80]; /// returns the null-terminated hostname in the character /// array hn, which has a length of 79 bytes. /// is hostname used somewhere? if ( gethostname(hn,79) != 0 ) { throw runtime_error("Error getting hostname"); } hostname = hn; /** Configuration system */ fass_configuration = new FassConfigurator(etc_location, var_location); rc = fass_configuration->load_configuration(); if ( !rc ) { throw runtime_error("Could not load Fass configuration file."); } /** Initial shares system */ //initial_shares = new FassInitShares(etc_location, var_location); //rc = initial_shares->load_shares(); //if ( !rc ) //{ // throw runtime_error("Could not load initial shares file."); //} /** Log system */ ostringstream os; try{ Log::MessageType clevel; clevel = get_debug_level(); /// Initializing FASS daemon log system string log_fname; log_fname = log_location + "fass.log"; FassLog::init_log_system(clevel, log_fname.c_str(), ios_base::trunc, "fassd"); os << "Starting " << version() << endl; os << "----------------------------------------\n"; os << " Fass Configuration File \n"; os << "----------------------------------------\n"; os << fass_configuration->get_conf_fname() << " \n"; os << "----------------------------------------"; FassLog::log("FASS",Log::INFO,os); fass_configuration->print_loaded_options(); } catch(runtime_error&){ throw; } /** Initialize the XML library */ // Try to avoid it // xmlInitParser(); /** Database */ // instance of specific DB (can be changed) string dbtype; string dbendpoint; string dbname; int dbport; fass_configuration->get_single_option("database", "type", dbtype); fass_configuration->get_single_option("database", "endpoint", dbendpoint); fass_configuration->get_single_option("database", "port", dbport); fass_configuration->get_single_option("database", "name", dbname); if ( dbtype == "influxdb" ){ // TODO: should be done with a switch and enum, not critical database = new InfluxDb(dbendpoint, dbport, dbname); } else { FassLog::log("FASS", Log::ERROR, "Unknown database type!"); throw; } // FOR VALE: database should be passed as argument to the Priority Manager /** Block all signals before creating any thread */ sigfillset(&mask); pthread_sigmask(SIG_BLOCK, &mask, NULL); /** Managers */ // some config variables are used both by the RPCManager and the XMLRPCClient (called by the PM) // we use the same valuse for both server/client, these should be consistent with the OpenNebula ones int message_size; int timeout; // OpenNebula xml-rpc endpoint string one_endpoint; string one_port; fass_configuration->get_single_option("fass", "one_endpoint", one_endpoint); fass_configuration->get_single_option("fass", "one_port", one_port); one_endpoint.append(":"); one_endpoint.append(one_port); one_endpoint.append("/RPC2"); //FassLog::log("FASS", Log::DEBUG, one_endpoint); // OpenNebula authentication string one_secret; fass_configuration->get_single_option("fass", "one_secret", one_secret); // xml-rpc config fass_configuration->get_single_option("rpcm", "message_size", message_size); fass_configuration->get_single_option("rpcm", "timeout", timeout); /// ---- Priority Manager ---- try { int manager_timer; int machines_limit; fass_configuration->get_single_option("pm", "max_vm", machines_limit); fass_configuration->get_single_option("pm", "manager_timer", manager_timer); // Read initial shares from separate file //initial_shares = new FassConfigurator(etc_location, var_location); //rc = initial_shares->load_configuration(); //if ( !rc ) //{ // throw runtime_error("Could not load Initial Shares file."); //} //std::vector<user> users; //std::list<users> list_of_users; // TODO add the shares vector //initial_shares->get_single_option("users", "user", user); //list_of_users::iterator list_it; //for (list_it = users.begin(); list_it != users.end(); ++list_it) //{ // list_of_users.insert(list_it,users); //} //pm = new PriorityManager(one_endpoint, one_secret, message_size, timeout, machines_limit, manager_timer, list_of_users); pm = new PriorityManager(one_endpoint, one_secret, message_size, timeout, machines_limit, manager_timer); } catch (bad_alloc&) { FassLog::log("FASS", Log::ERROR, "Error creating Priority Manager"); throw; } /// ---- Start the Priority Manager ---- rc = pm->start(); if ( !rc ) { throw runtime_error("Could not start the Priority Manager"); } /// ---- Request Manager ---- try { //int rm_port = 0; string rm_port = ""; int max_conn; int max_conn_backlog; int keepalive_timeout; int keepalive_max_conn; bool rpc_log; string log_call_format; string rpc_filename = ""; string rm_listen_address; //= "0.0.0.0"; fass_configuration->get_single_option("rpcm", "listen_port", rm_port); fass_configuration->get_single_option("rpcm", "listen_address", rm_listen_address); fass_configuration->get_single_option("rpcm", "max_conn", max_conn); fass_configuration->get_single_option("rpcm", "max_conn_backlog", max_conn_backlog); fass_configuration->get_single_option("rpcm", "keepalive_timeout", keepalive_timeout); fass_configuration->get_single_option("rpcm", "keepalive_max_conn", keepalive_max_conn); fass_configuration->get_single_option("rpcm", "rpc_log", rpc_log); fass_configuration->get_single_option("rpcm", "log_call_format", log_call_format); if (rpc_log) { rpc_filename = log_location + "fass_xmlrpc.log"; } rpcm = new RPCManager(one_endpoint,rm_port, max_conn, max_conn_backlog, keepalive_timeout, keepalive_max_conn, timeout, rpc_filename, log_call_format, rm_listen_address, message_size); } catch (bad_alloc&) { FassLog::log("FASS", Log::ERROR, "Error creating RPC Manager"); throw; } /// ---- Start the Request Manager ---- rc = rpcm->start(); if ( !rc ) { throw runtime_error("Could not start the RPC Manager"); } /** Wait for a SIGTERM or SIGINT signal */ sigemptyset(&mask); sigaddset(&mask, SIGINT); sigaddset(&mask, SIGTERM); sigwait(&mask, &signal); /** Stop the managers and free resources */ pm->finalize(); //sleep to wait drivers??? pthread_join(rpcm->get_thread_id(),0); pthread_join(pm->get_thread_id(),0); //XML Library // xmlCleanupParser(); FassLog::log("FASS", Log::INFO, "All modules finalized, exiting.\n"); return; //error_mad: // Log::log("FASS", Log::ERROR, "Could not load driver"); // throw runtime_error("Could not load a Fass driver"); } Log::MessageType Fass::get_debug_level() const { Log::MessageType clevel = Log::ERROR; int log_level_int ; fass_configuration->get_single_option("fass", "log_level", log_level_int); if ( log_level_int != 0 ) { if ( Log::ERROR <= log_level_int && log_level_int <= Log::DDDEBUG ) { clevel = static_cast<Log::MessageType>(log_level_int); } } return clevel; } <|endoftext|>
<commit_before>/* * Copyright 2007-2018 Content Management AG * All rights reserved. * * author: Max Kellermann <mk@cm4all.com> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "Stock.hxx" #include "Factory.hxx" #include "FilteredSocket.hxx" #include "stock/Stock.hxx" #include "stock/Class.hxx" #include "stock/LoggerDomain.hxx" #include "address_list.hxx" #include "pool/pool.hxx" #include "net/PConnectSocket.hxx" #include "net/SocketAddress.hxx" #include "net/AllocatedSocketAddress.hxx" #include "net/ToString.hxx" #include "io/Logger.hxx" #include "util/Cancellable.hxx" #include "util/RuntimeError.hxx" #include "util/Exception.hxx" #include <assert.h> #include <errno.h> #include <string.h> #include <unistd.h> #include <sys/un.h> #include <sys/socket.h> struct FilteredSocketStockRequest { const bool ip_transparent; const SocketAddress bind_address, address; const unsigned timeout; SocketFilterFactory *const filter_factory; FilteredSocketStockRequest(bool _ip_transparent, SocketAddress _bind_address, SocketAddress _address, unsigned _timeout, SocketFilterFactory *_filter_factory) :ip_transparent(_ip_transparent), bind_address(_bind_address), address(_address), timeout(_timeout), filter_factory(_filter_factory) {} }; struct FilteredSocketStockConnection final : StockItem, ConnectSocketHandler, BufferedSocketHandler, Cancellable { BasicLogger<StockLoggerDomain> logger; const FdType type; const AllocatedSocketAddress address; SocketFilterFactory *const filter_factory; /** * To cancel the ClientSocket. */ CancellablePointer cancel_ptr; FilteredSocket socket; FilteredSocketStockConnection(CreateStockItem c, FdType _type, SocketAddress _address, SocketFilterFactory *_filter_factory, CancellablePointer &_cancel_ptr) noexcept :StockItem(c), logger(c.stock), type(_type), address(_address), filter_factory(_filter_factory), socket(c.stock.GetEventLoop()) { _cancel_ptr = *this; cancel_ptr = nullptr; } ~FilteredSocketStockConnection() override { if (cancel_ptr) cancel_ptr.Cancel(); else if (socket.IsValid() && socket.IsConnected()) { socket.Close(); socket.Destroy(); } } /* virtual methods from class Cancellable */ void Cancel() noexcept override { assert(cancel_ptr); cancel_ptr.CancelAndClear(); InvokeCreateAborted(); } /* virtual methods from class ConnectSocketHandler */ void OnSocketConnectSuccess(UniqueSocketDescriptor &&fd) override; void OnSocketConnectError(std::exception_ptr ep) override; /* virtual methods from class BufferedSocketHandler */ BufferedResult OnBufferedData() override; bool OnBufferedClosed() noexcept override; gcc_noreturn bool OnBufferedWrite() override { /* should never be reached because we never schedule writing */ gcc_unreachable(); } void OnBufferedError(std::exception_ptr e) noexcept override; /* virtual methods from class StockItem */ bool Borrow() noexcept override { return true; } bool Release() noexcept override; }; /* * BufferedSocketHandler * */ BufferedResult FilteredSocketStockConnection::OnBufferedData() { logger(2, "unexpected data in idle TCP connection"); InvokeIdleDisconnect(); return BufferedResult::CLOSED; } bool FilteredSocketStockConnection::OnBufferedClosed() noexcept { InvokeIdleDisconnect(); return false; } void FilteredSocketStockConnection::OnBufferedError(std::exception_ptr e) noexcept { logger(2, "error on idle connection: ", e); InvokeIdleDisconnect(); } /* * client_socket callback * */ void FilteredSocketStockConnection::OnSocketConnectSuccess(UniqueSocketDescriptor &&fd) { cancel_ptr = nullptr; try { socket.Init(fd.Release(), type, nullptr, nullptr, filter_factory != nullptr ? filter_factory->CreateFilter() : nullptr, *this); } catch (...) { InvokeCreateError(std::current_exception()); return; } InvokeCreateSuccess(); } void FilteredSocketStockConnection::OnSocketConnectError(std::exception_ptr ep) { cancel_ptr = nullptr; ep = NestException(ep, FormatRuntimeError("Failed to connect to '%s'", GetStockName())); InvokeCreateError(ep); } /* * stock class * */ void FilteredSocketStock::Create(CreateStockItem c, void *info, struct pool &caller_pool, CancellablePointer &cancel_ptr) { const auto &request = *(const FilteredSocketStockRequest *)info; const int address_family = request.address.GetFamily(); const FdType type = address_family == AF_LOCAL ? FD_SOCKET : FD_TCP; auto *connection = new FilteredSocketStockConnection(c, type, request.address, request.filter_factory, cancel_ptr); client_socket_new(c.stock.GetEventLoop(), caller_pool, address_family, SOCK_STREAM, 0, request.ip_transparent, request.bind_address, request.address, request.timeout, *connection, connection->cancel_ptr); } bool FilteredSocketStockConnection::Release() noexcept { if (!socket.IsEmpty()) { logger(2, "unexpected data in idle connection"); return false; } socket.Reinit(nullptr, nullptr, *this); socket.UnscheduleWrite(); static const struct timeval tv = { .tv_sec = 60, .tv_usec = 0, }; socket.ScheduleReadTimeout(false, &tv); return true; } /* * interface * */ void FilteredSocketStock::Get(struct pool &pool, const char *name, bool ip_transparent, SocketAddress bind_address, SocketAddress address, unsigned timeout, SocketFilterFactory *filter_factory, StockGetHandler &handler, CancellablePointer &cancel_ptr) noexcept { assert(!address.IsNull()); auto request = NewFromPool<FilteredSocketStockRequest>(pool, ip_transparent, bind_address, address, timeout, filter_factory); if (name == nullptr) { char buffer[1024]; if (!ToString(buffer, sizeof(buffer), address)) buffer[0] = 0; if (!bind_address.IsNull()) { char bind_buffer[1024]; if (!ToString(bind_buffer, sizeof(bind_buffer), bind_address)) bind_buffer[0] = 0; name = p_strcat(&pool, bind_buffer, ">", buffer, nullptr); } else name = p_strdup(&pool, buffer); } if (filter_factory != nullptr) name = p_strcat(&pool, name, "|", filter_factory->GetFilterId(), nullptr); stock.Get(pool, name, request, handler, cancel_ptr); } FilteredSocket & fs_stock_item_get(StockItem &item) { auto &connection = (FilteredSocketStockConnection &)item; return connection.socket; } SocketAddress fs_stock_item_get_address(const StockItem &item) { const auto &connection = (const FilteredSocketStockConnection &)item; return connection.address; } <commit_msg>fs/Stock: check IsConnected() in Release()<commit_after>/* * Copyright 2007-2018 Content Management AG * All rights reserved. * * author: Max Kellermann <mk@cm4all.com> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "Stock.hxx" #include "Factory.hxx" #include "FilteredSocket.hxx" #include "stock/Stock.hxx" #include "stock/Class.hxx" #include "stock/LoggerDomain.hxx" #include "address_list.hxx" #include "pool/pool.hxx" #include "net/PConnectSocket.hxx" #include "net/SocketAddress.hxx" #include "net/AllocatedSocketAddress.hxx" #include "net/ToString.hxx" #include "io/Logger.hxx" #include "util/Cancellable.hxx" #include "util/RuntimeError.hxx" #include "util/Exception.hxx" #include <assert.h> #include <errno.h> #include <string.h> #include <unistd.h> #include <sys/un.h> #include <sys/socket.h> struct FilteredSocketStockRequest { const bool ip_transparent; const SocketAddress bind_address, address; const unsigned timeout; SocketFilterFactory *const filter_factory; FilteredSocketStockRequest(bool _ip_transparent, SocketAddress _bind_address, SocketAddress _address, unsigned _timeout, SocketFilterFactory *_filter_factory) :ip_transparent(_ip_transparent), bind_address(_bind_address), address(_address), timeout(_timeout), filter_factory(_filter_factory) {} }; struct FilteredSocketStockConnection final : StockItem, ConnectSocketHandler, BufferedSocketHandler, Cancellable { BasicLogger<StockLoggerDomain> logger; const FdType type; const AllocatedSocketAddress address; SocketFilterFactory *const filter_factory; /** * To cancel the ClientSocket. */ CancellablePointer cancel_ptr; FilteredSocket socket; FilteredSocketStockConnection(CreateStockItem c, FdType _type, SocketAddress _address, SocketFilterFactory *_filter_factory, CancellablePointer &_cancel_ptr) noexcept :StockItem(c), logger(c.stock), type(_type), address(_address), filter_factory(_filter_factory), socket(c.stock.GetEventLoop()) { _cancel_ptr = *this; cancel_ptr = nullptr; } ~FilteredSocketStockConnection() override { if (cancel_ptr) cancel_ptr.Cancel(); else if (socket.IsValid() && socket.IsConnected()) { socket.Close(); socket.Destroy(); } } /* virtual methods from class Cancellable */ void Cancel() noexcept override { assert(cancel_ptr); cancel_ptr.CancelAndClear(); InvokeCreateAborted(); } /* virtual methods from class ConnectSocketHandler */ void OnSocketConnectSuccess(UniqueSocketDescriptor &&fd) override; void OnSocketConnectError(std::exception_ptr ep) override; /* virtual methods from class BufferedSocketHandler */ BufferedResult OnBufferedData() override; bool OnBufferedClosed() noexcept override; gcc_noreturn bool OnBufferedWrite() override { /* should never be reached because we never schedule writing */ gcc_unreachable(); } void OnBufferedError(std::exception_ptr e) noexcept override; /* virtual methods from class StockItem */ bool Borrow() noexcept override { return true; } bool Release() noexcept override; }; /* * BufferedSocketHandler * */ BufferedResult FilteredSocketStockConnection::OnBufferedData() { logger(2, "unexpected data in idle TCP connection"); InvokeIdleDisconnect(); return BufferedResult::CLOSED; } bool FilteredSocketStockConnection::OnBufferedClosed() noexcept { InvokeIdleDisconnect(); return false; } void FilteredSocketStockConnection::OnBufferedError(std::exception_ptr e) noexcept { logger(2, "error on idle connection: ", e); InvokeIdleDisconnect(); } /* * client_socket callback * */ void FilteredSocketStockConnection::OnSocketConnectSuccess(UniqueSocketDescriptor &&fd) { cancel_ptr = nullptr; try { socket.Init(fd.Release(), type, nullptr, nullptr, filter_factory != nullptr ? filter_factory->CreateFilter() : nullptr, *this); } catch (...) { InvokeCreateError(std::current_exception()); return; } InvokeCreateSuccess(); } void FilteredSocketStockConnection::OnSocketConnectError(std::exception_ptr ep) { cancel_ptr = nullptr; ep = NestException(ep, FormatRuntimeError("Failed to connect to '%s'", GetStockName())); InvokeCreateError(ep); } /* * stock class * */ void FilteredSocketStock::Create(CreateStockItem c, void *info, struct pool &caller_pool, CancellablePointer &cancel_ptr) { const auto &request = *(const FilteredSocketStockRequest *)info; const int address_family = request.address.GetFamily(); const FdType type = address_family == AF_LOCAL ? FD_SOCKET : FD_TCP; auto *connection = new FilteredSocketStockConnection(c, type, request.address, request.filter_factory, cancel_ptr); client_socket_new(c.stock.GetEventLoop(), caller_pool, address_family, SOCK_STREAM, 0, request.ip_transparent, request.bind_address, request.address, request.timeout, *connection, connection->cancel_ptr); } bool FilteredSocketStockConnection::Release() noexcept { if (!socket.IsConnected()) return false; if (!socket.IsEmpty()) { logger(2, "unexpected data in idle connection"); return false; } socket.Reinit(nullptr, nullptr, *this); socket.UnscheduleWrite(); static const struct timeval tv = { .tv_sec = 60, .tv_usec = 0, }; socket.ScheduleReadTimeout(false, &tv); return true; } /* * interface * */ void FilteredSocketStock::Get(struct pool &pool, const char *name, bool ip_transparent, SocketAddress bind_address, SocketAddress address, unsigned timeout, SocketFilterFactory *filter_factory, StockGetHandler &handler, CancellablePointer &cancel_ptr) noexcept { assert(!address.IsNull()); auto request = NewFromPool<FilteredSocketStockRequest>(pool, ip_transparent, bind_address, address, timeout, filter_factory); if (name == nullptr) { char buffer[1024]; if (!ToString(buffer, sizeof(buffer), address)) buffer[0] = 0; if (!bind_address.IsNull()) { char bind_buffer[1024]; if (!ToString(bind_buffer, sizeof(bind_buffer), bind_address)) bind_buffer[0] = 0; name = p_strcat(&pool, bind_buffer, ">", buffer, nullptr); } else name = p_strdup(&pool, buffer); } if (filter_factory != nullptr) name = p_strcat(&pool, name, "|", filter_factory->GetFilterId(), nullptr); stock.Get(pool, name, request, handler, cancel_ptr); } FilteredSocket & fs_stock_item_get(StockItem &item) { auto &connection = (FilteredSocketStockConnection &)item; return connection.socket; } SocketAddress fs_stock_item_get_address(const StockItem &item) { const auto &connection = (const FilteredSocketStockConnection &)item; return connection.address; } <|endoftext|>
<commit_before>/* $Id$ * * Copyright 2010 Anders Wallin (anders.e.e.wallin "at" gmail.com) * * This file is part of OpenCAMlib. * * OpenCAMlib is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OpenCAMlib is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenCAMlib. If not, see <http://www.gnu.org/licenses/>. */ #ifndef PATH_H #define PATH_H #include <list> #include "point.hpp" #include "line.hpp" #include "arc.hpp" namespace ocl { /// Span type enum SpanType{ LineSpanType, ArcSpanType }; /// \brief A finite curve which returns Point objects along its length. /// /// location along span is based on a parameter t for which 0 <= t <= 1.0 class Span{ public: /// return type of span virtual SpanType type()const = 0; /// return the length of the span in the xy-plane virtual double length2d()const = 0; /// return a point at parameter value 0 <= t <= 1.0 virtual Point getPoint(double t) const = 0; // 0.0 to 1.0 }; /// Line Span class LineSpan : public Span { public: /// create a line span from Line l LineSpan(const Line& l) : line(l){} /// the line Line line; // Span's virtual functions /// return span type SpanType type()const{return LineSpanType;} /// return span length double length2d() const { return line.length2d(); } /// return point on span Point getPoint(double t) const { return line.getPoint(t); } }; /// circular Arc Span class ArcSpan : public Span { public: /// create span ArcSpan(const Arc& a) : arc(a){} /// arc Arc arc; // Span's virtual functions /// return type SpanType type()const{return ArcSpanType;} /// return length in xy-plane double length2d()const{return arc.length2d();} /// return a point on the span Point getPoint(double t)const{return arc.getPoint(t);} }; /// /// \brief A collection of Span objects /// class Path { public: /// create empty path Path(); /// copy constructor Path(const Path &p); /// destructor virtual ~Path(); /// list of spans in this path std::list<Span*> span_list; // FIXME: this looks wrong // should be only one append() that takes a Span /// append a Line to this path void append(const Line &l); /// append an Arc to this path void append(const Arc &a); }; } // end namespace #endif // end file path.h <commit_msg>Fix gcc 4.7.1 compile error<commit_after>/* $Id$ * * Copyright 2010 Anders Wallin (anders.e.e.wallin "at" gmail.com) * * This file is part of OpenCAMlib. * * OpenCAMlib is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OpenCAMlib is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenCAMlib. If not, see <http://www.gnu.org/licenses/>. */ #ifndef PATH_H #define PATH_H #include <list> #include "point.hpp" #include "line.hpp" #include "arc.hpp" namespace ocl { /// Span type enum SpanType{ LineSpanType, ArcSpanType }; /// \brief A finite curve which returns Point objects along its length. /// /// location along span is based on a parameter t for which 0 <= t <= 1.0 class Span{ public: /// return type of span virtual SpanType type()const = 0; /// return the length of the span in the xy-plane virtual double length2d()const = 0; /// return a point at parameter value 0 <= t <= 1.0 virtual Point getPoint(double t) const = 0; // 0.0 to 1.0 /// avoid gcc 4.7.1 delete-non-virtual-dtor error virtual ~Span(); }; /// Line Span class LineSpan : public Span { public: /// create a line span from Line l LineSpan(const Line& l) : line(l){} /// the line Line line; // Span's virtual functions /// return span type SpanType type()const{return LineSpanType;} /// return span length double length2d() const { return line.length2d(); } /// return point on span Point getPoint(double t) const { return line.getPoint(t); } }; /// circular Arc Span class ArcSpan : public Span { public: /// create span ArcSpan(const Arc& a) : arc(a){} /// arc Arc arc; // Span's virtual functions /// return type SpanType type()const{return ArcSpanType;} /// return length in xy-plane double length2d()const{return arc.length2d();} /// return a point on the span Point getPoint(double t)const{return arc.getPoint(t);} }; /// /// \brief A collection of Span objects /// class Path { public: /// create empty path Path(); /// copy constructor Path(const Path &p); /// destructor virtual ~Path(); /// list of spans in this path std::list<Span*> span_list; // FIXME: this looks wrong // should be only one append() that takes a Span /// append a Line to this path void append(const Line &l); /// append an Arc to this path void append(const Arc &a); }; } // end namespace #endif // end file path.h <|endoftext|>
<commit_before>/* This file is part of Akregator. Copyright (C) 2005 Frank Osterfeld <osterfeld@kde.org> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. As a special exception, permission is given to link this program with any edition of Qt, and distribute the resulting executable, without including the source code for Qt in the source distribution. */ #include "actionmanager.h" #include "actions.h" #include "browserframe.h" #include "browserframe_p.h" #include "openurlrequest.h" #include <QAction> #include <QGridLayout> #include <QList> #include <QPoint> #include <QPointer> #include <QString> #include <QWidget> #include <kaction.h> #include <kdebug.h> #include <klibloader.h> #include <KMenu> #include <kmimetypetrader.h> #include <ktoolbarpopupaction.h> #include <kurl.h> #include <kxmlguiclient.h> #include <kparts/browserextension.h> #include <kparts/part.h> #include <cassert> using namespace KParts; using namespace Akregator; BrowserFrame::BrowserFrame(QWidget* parent) : Frame(parent), d( new Private( this ) ) { } BrowserFrame::~BrowserFrame() { delete d; } KUrl BrowserFrame::url() const { return d->part ? d->part->url() : KUrl(); } bool BrowserFrame::canGoForward() const { return !d->history.isEmpty() && d->current != d->history.end()-1 && d->current != d->history.end(); } bool BrowserFrame::canGoBack() const { return !d->history.isEmpty() && d->current != d->history.begin(); } void BrowserFrame::slotOpenUrlNotify() { // TODO: inform the world that a new url was opened } void BrowserFrame::slotSetLocationBarUrl(const QString& /*url*/) { // TODO: use this to update URLs for dragging (like tab drag etc.) } void BrowserFrame::slotSetIconUrl(const KUrl& url ) { FeedIconManager::self()->removeListener( this ); FeedIconManager::self()->addListener( url, this ); } void BrowserFrame::setFavicon( const QIcon& icon ) { emit signalIconChanged( this, icon ); } void BrowserFrame::slotSpeedProgress(int /*bytesPerSecond*/) { } namespace { static OpenUrlRequest requestFromSender( QObject* sender, int id ) { QAction* const action = qobject_cast<QAction*>( sender ); assert( action ); const KUrl url = action->data().value<KUrl>(); OpenUrlRequest req; req.setFrameId( id ); req.setUrl( url ); return req; } } void BrowserFrame::slotOpenLinkInBrowser() { OpenUrlRequest req = requestFromSender( sender(), id() ); req.setOptions( OpenUrlRequest::ExternalBrowser ); emit signalOpenUrlRequest( req ); } void BrowserFrame::slotOpenLinkInNewTab() { OpenUrlRequest req = requestFromSender( sender(), id() ); req.setOptions( OpenUrlRequest::NewTab ); emit signalOpenUrlRequest( req ); } namespace { enum SeparatorOption { ShowSeparatorIfNotEmpty, NoSeparator }; void addActionsToMenu( QMenu* menu, const QList<QAction*> actions, SeparatorOption option ) { if ( !actions.isEmpty() && option != NoSeparator ) menu->addSeparator(); Q_FOREACH( QAction* const i, actions ) menu->addAction( i ); } } void BrowserFrame::slotPopupMenu( const QPoint& global, const KUrl& url, mode_t mode, const OpenUrlArguments& args, const BrowserArguments& browserArgs, BrowserExtension::PopupFlags flags, const KParts::BrowserExtension::ActionGroupMap& actionGroups ) { const bool showReload = (flags & BrowserExtension::ShowReload) != 0; const bool showNavigationItems = (flags & BrowserExtension::ShowNavigationItems) != 0; const bool isLink = (flags & BrowserExtension:: IsLink) != 0; const bool isSelection = (flags & BrowserExtension::ShowTextSelectionItems) != 0; bool isFirst = true; QPointer<KMenu> popup( new KMenu( d->part->widget() ) ); if (showNavigationItems) { popup->addAction( ActionManager::getInstance()->action( "browser_back" ) ); popup->addAction( ActionManager::getInstance()->action( "browser_forward" ) ); isFirst = false; } if (showReload) { popup->addAction( ActionManager::getInstance()->action( "browser_reload" ) ); isFirst = false; } #define addSeparatorIfNotFirst() if ( !isFirst ) popup->addSeparator(); isFirst = false; if (isLink) { addSeparatorIfNotFirst(); popup->addAction( createOpenLinkInNewTabAction( url, this, SLOT( slotOpenLinkInNewTab() ), popup ) ); popup->addAction( createOpenLinkInExternalBrowserAction( url, this, SLOT( slotOpenLinkInBrowser() ), popup ) ); addActionsToMenu( popup, actionGroups.value( "linkactions" ), ShowSeparatorIfNotEmpty ); } if (isSelection) { addSeparatorIfNotFirst(); addActionsToMenu( popup, actionGroups.value( "editactions" ), NoSeparator ); } addSeparatorIfNotFirst(); addActionsToMenu( popup, actionGroups.value( "part" ), NoSeparator ); popup->exec( global ); delete popup; } void BrowserFrame::slotOpenUrlRequestDelayed(const KUrl& url, const OpenUrlArguments& args, const BrowserArguments& browserArgs) { OpenUrlRequest req; req.setFrameId(id()); req.setUrl(url); req.setArgs(args); req.setBrowserArgs(browserArgs); emit signalOpenUrlRequest(req); } void BrowserFrame::slotCreateNewWindow(const KUrl& url, const OpenUrlArguments& args, const BrowserArguments& browserArgs, const WindowArgs& /*windowArgs*/, ReadOnlyPart** part) { OpenUrlRequest req; req.setFrameId(id()); req.setUrl(url); req.setArgs(args); req.setBrowserArgs(browserArgs); req.setOptions(OpenUrlRequest::NewTab); emit signalOpenUrlRequest(req); if ( part ) *part = req.part(); } bool BrowserFrame::openUrl(const OpenUrlRequest& request) { const QString serviceType = request.args().mimeType(); if (serviceType.isEmpty()) return false; d->updateHistoryEntry(); kDebug() << "serviceType: " << serviceType; if (d->loadPartForMimetype(serviceType)) { assert( d->part ); d->part->setArguments(request.args()); if ( !request.url().isValid() ) return false; const bool res = d->part->openUrl( request.url() ); if ( res ) { d->appendHistoryEntry(request.url()); d->updateHistoryEntry(); } return res; } else { // TODO: show open|save|cancel dialog } return false; // TODO: is this correct? } ReadOnlyPart* BrowserFrame::part() const { return d->part; } void BrowserFrame::slotHistoryBackAboutToShow() { QAction* ba = ActionManager::getInstance()->action("browser_back"); QMenu* popup = static_cast<KToolBarPopupAction*>(ba)->menu(); popup->clear(); if (!canGoBack()) return; QList<Private::HistoryEntry>::Iterator it = d->current-1; int i = 0; while( i < 10) { if ( it == d->history.begin() ) { popup->addAction(new Private::HistoryAction(it, popup, d)); return; } popup->addAction(new Private::HistoryAction(it, popup, d)); ++i; --it; } } void BrowserFrame::slotHistoryForwardAboutToShow() { QAction* fw = ActionManager::getInstance()->action("browser_forward"); QMenu* popup = qobject_cast<KToolBarPopupAction*>(fw)->menu(); popup->clear(); if (!canGoForward()) return; QList<Private::HistoryEntry>::Iterator it = d->current+1; int i = 0; while( i < 10) { if ( it == d->history.end()-1 ) { popup->addAction( new Private::HistoryAction(it, popup, d)); return; } popup->addAction(new Private::HistoryAction(it, popup, d)); ++i; ++it; } } void BrowserFrame::slotHistoryForward() { if (canGoForward()) d->restoreHistoryEntry(d->current+1); } void BrowserFrame::slotHistoryBack() { if (canGoBack()) d->restoreHistoryEntry(d->current-1); } void BrowserFrame::slotReload() { // TODO //TemporaryValue lock( d->lockHistory, true ); //openUrl(d->url, d->mimetype); // this s } void BrowserFrame::slotStop() { if (d->part) d->part->closeUrl(); Frame::slotStop(); } void BrowserFrame::slotPaletteOrFontChanged() { } bool BrowserFrame::isReloadable() const { return false; // TODO } bool BrowserFrame::isLoading() const { return d->isLoading; } void BrowserFrame::loadConfig( const KConfigGroup& config, const QString& prefix) { QString url = config.readEntry( QString::fromLatin1( "url" ).prepend( prefix ), QString() ); QString mimetype = config.readEntry( QString::fromLatin1( "mimetype" ).prepend( prefix ), QString() ); OpenUrlRequest req(url); KParts::OpenUrlArguments args; args.setMimeType(mimetype); req.setArgs(args); openUrl(req); } void BrowserFrame::saveConfig( KConfigGroup& config, const QString& prefix) { config.writeEntry( QString::fromLatin1( "url" ).prepend( prefix ), url().url() ); config.writeEntry( QString::fromLatin1( "mimetype" ).prepend( prefix ), d->mimetype ); } #include "browserframe.moc" <commit_msg>Making reload work again in akregator<commit_after>/* This file is part of Akregator. Copyright (C) 2005 Frank Osterfeld <osterfeld@kde.org> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. As a special exception, permission is given to link this program with any edition of Qt, and distribute the resulting executable, without including the source code for Qt in the source distribution. */ #include "actionmanager.h" #include "actions.h" #include "browserframe.h" #include "browserframe_p.h" #include "openurlrequest.h" #include "utils/temporaryvalue.h" #include <QAction> #include <QGridLayout> #include <QList> #include <QPoint> #include <QPointer> #include <QString> #include <QWidget> #include <kaction.h> #include <kdebug.h> #include <klibloader.h> #include <KMenu> #include <kmimetypetrader.h> #include <ktoolbarpopupaction.h> #include <kurl.h> #include <kxmlguiclient.h> #include <kparts/browserextension.h> #include <kparts/part.h> #include <cassert> using namespace KParts; using namespace Akregator; BrowserFrame::BrowserFrame(QWidget* parent) : Frame(parent), d( new Private( this ) ) { } BrowserFrame::~BrowserFrame() { delete d; } KUrl BrowserFrame::url() const { return d->part ? d->part->url() : KUrl(); } bool BrowserFrame::canGoForward() const { return !d->history.isEmpty() && d->current != d->history.end()-1 && d->current != d->history.end(); } bool BrowserFrame::canGoBack() const { return !d->history.isEmpty() && d->current != d->history.begin(); } void BrowserFrame::slotOpenUrlNotify() { // TODO: inform the world that a new url was opened } void BrowserFrame::slotSetLocationBarUrl(const QString& /*url*/) { // TODO: use this to update URLs for dragging (like tab drag etc.) } void BrowserFrame::slotSetIconUrl(const KUrl& url ) { FeedIconManager::self()->removeListener( this ); FeedIconManager::self()->addListener( url, this ); } void BrowserFrame::setFavicon( const QIcon& icon ) { emit signalIconChanged( this, icon ); } void BrowserFrame::slotSpeedProgress(int /*bytesPerSecond*/) { } namespace { static OpenUrlRequest requestFromSender( QObject* sender, int id ) { QAction* const action = qobject_cast<QAction*>( sender ); assert( action ); const KUrl url = action->data().value<KUrl>(); OpenUrlRequest req; req.setFrameId( id ); req.setUrl( url ); return req; } } void BrowserFrame::slotOpenLinkInBrowser() { OpenUrlRequest req = requestFromSender( sender(), id() ); req.setOptions( OpenUrlRequest::ExternalBrowser ); emit signalOpenUrlRequest( req ); } void BrowserFrame::slotOpenLinkInNewTab() { OpenUrlRequest req = requestFromSender( sender(), id() ); req.setOptions( OpenUrlRequest::NewTab ); emit signalOpenUrlRequest( req ); } namespace { enum SeparatorOption { ShowSeparatorIfNotEmpty, NoSeparator }; void addActionsToMenu( QMenu* menu, const QList<QAction*> actions, SeparatorOption option ) { if ( !actions.isEmpty() && option != NoSeparator ) menu->addSeparator(); Q_FOREACH( QAction* const i, actions ) menu->addAction( i ); } } void BrowserFrame::slotPopupMenu( const QPoint& global, const KUrl& url, mode_t mode, const OpenUrlArguments& args, const BrowserArguments& browserArgs, BrowserExtension::PopupFlags flags, const KParts::BrowserExtension::ActionGroupMap& actionGroups ) { const bool showReload = (flags & BrowserExtension::ShowReload) != 0; const bool showNavigationItems = (flags & BrowserExtension::ShowNavigationItems) != 0; const bool isLink = (flags & BrowserExtension:: IsLink) != 0; const bool isSelection = (flags & BrowserExtension::ShowTextSelectionItems) != 0; bool isFirst = true; QPointer<KMenu> popup( new KMenu( d->part->widget() ) ); if (showNavigationItems) { popup->addAction( ActionManager::getInstance()->action( "browser_back" ) ); popup->addAction( ActionManager::getInstance()->action( "browser_forward" ) ); isFirst = false; } if (showReload) { popup->addAction( ActionManager::getInstance()->action( "browser_reload" ) ); isFirst = false; } #define addSeparatorIfNotFirst() if ( !isFirst ) popup->addSeparator(); isFirst = false; if (isLink) { addSeparatorIfNotFirst(); popup->addAction( createOpenLinkInNewTabAction( url, this, SLOT( slotOpenLinkInNewTab() ), popup ) ); popup->addAction( createOpenLinkInExternalBrowserAction( url, this, SLOT( slotOpenLinkInBrowser() ), popup ) ); addActionsToMenu( popup, actionGroups.value( "linkactions" ), ShowSeparatorIfNotEmpty ); } if (isSelection) { addSeparatorIfNotFirst(); addActionsToMenu( popup, actionGroups.value( "editactions" ), NoSeparator ); } addSeparatorIfNotFirst(); addActionsToMenu( popup, actionGroups.value( "part" ), NoSeparator ); popup->exec( global ); delete popup; } void BrowserFrame::slotOpenUrlRequestDelayed(const KUrl& url, const OpenUrlArguments& args, const BrowserArguments& browserArgs) { OpenUrlRequest req; req.setFrameId(id()); req.setUrl(url); req.setArgs(args); req.setBrowserArgs(browserArgs); emit signalOpenUrlRequest(req); } void BrowserFrame::slotCreateNewWindow(const KUrl& url, const OpenUrlArguments& args, const BrowserArguments& browserArgs, const WindowArgs& /*windowArgs*/, ReadOnlyPart** part) { OpenUrlRequest req; req.setFrameId(id()); req.setUrl(url); req.setArgs(args); req.setBrowserArgs(browserArgs); req.setOptions(OpenUrlRequest::NewTab); emit signalOpenUrlRequest(req); if ( part ) *part = req.part(); } bool BrowserFrame::openUrl(const OpenUrlRequest& request) { const QString serviceType = request.args().mimeType(); if (serviceType.isEmpty()) return false; d->updateHistoryEntry(); kDebug() << "serviceType: " << serviceType; if (d->loadPartForMimetype(serviceType)) { assert( d->part ); d->part->setArguments(request.args()); if ( !request.url().isValid() ) return false; const bool res = d->part->openUrl( request.url() ); if ( res ) { d->appendHistoryEntry(request.url()); d->updateHistoryEntry(); } return res; } else { // TODO: show open|save|cancel dialog } return false; // TODO: is this correct? } ReadOnlyPart* BrowserFrame::part() const { return d->part; } void BrowserFrame::slotHistoryBackAboutToShow() { QAction* ba = ActionManager::getInstance()->action("browser_back"); QMenu* popup = static_cast<KToolBarPopupAction*>(ba)->menu(); popup->clear(); if (!canGoBack()) return; QList<Private::HistoryEntry>::Iterator it = d->current-1; int i = 0; while( i < 10) { if ( it == d->history.begin() ) { popup->addAction(new Private::HistoryAction(it, popup, d)); return; } popup->addAction(new Private::HistoryAction(it, popup, d)); ++i; --it; } } void BrowserFrame::slotHistoryForwardAboutToShow() { QAction* fw = ActionManager::getInstance()->action("browser_forward"); QMenu* popup = qobject_cast<KToolBarPopupAction*>(fw)->menu(); popup->clear(); if (!canGoForward()) return; QList<Private::HistoryEntry>::Iterator it = d->current+1; int i = 0; while( i < 10) { if ( it == d->history.end()-1 ) { popup->addAction( new Private::HistoryAction(it, popup, d)); return; } popup->addAction(new Private::HistoryAction(it, popup, d)); ++i; ++it; } } void BrowserFrame::slotHistoryForward() { if (canGoForward()) d->restoreHistoryEntry(d->current+1); } void BrowserFrame::slotHistoryBack() { if (canGoBack()) d->restoreHistoryEntry(d->current-1); } void BrowserFrame::slotReload() { TemporaryValue<bool> lock( d->lockHistory, true ); OpenUrlRequest req(url()); KParts::OpenUrlArguments args; args.setMimeType(d->mimetype); req.setArgs(args); openUrl(req); } void BrowserFrame::slotStop() { if (d->part) d->part->closeUrl(); Frame::slotStop(); } void BrowserFrame::slotPaletteOrFontChanged() { } bool BrowserFrame::isReloadable() const { return true; } bool BrowserFrame::isLoading() const { return d->isLoading; } void BrowserFrame::loadConfig( const KConfigGroup& config, const QString& prefix) { QString url = config.readEntry( QString::fromLatin1( "url" ).prepend( prefix ), QString() ); QString mimetype = config.readEntry( QString::fromLatin1( "mimetype" ).prepend( prefix ), QString() ); OpenUrlRequest req(url); KParts::OpenUrlArguments args; args.setMimeType(mimetype); req.setArgs(args); openUrl(req); } void BrowserFrame::saveConfig( KConfigGroup& config, const QString& prefix) { config.writeEntry( QString::fromLatin1( "url" ).prepend( prefix ), url().url() ); config.writeEntry( QString::fromLatin1( "mimetype" ).prepend( prefix ), d->mimetype ); } #include "browserframe.moc" <|endoftext|>
<commit_before>#include <config.h> #include "coarse_scale_operator.hh" #include <dune/stuff/common/exceptions.hh> #include <dune/stuff/common/configuration.hh> #include <dune/stuff/fem/functions/integrals.hh> #include <dune/stuff/common/profiler.hh> #include <dune/stuff/grid/walker.hh> #include <dune/gdt/operators/projections.hh> #include <dune/gdt/operators/prolongations.hh> #include <dune/gdt/spaces/constraints.hh> #include <dune/gdt/functionals/l2.hh> #include <dune/multiscale/msfem/localproblems/localproblemsolver.hh> #include <dune/multiscale/msfem/localproblems/localsolutionmanager.hh> #include <dune/multiscale/msfem/localproblems/localgridlist.hh> #include <dune/multiscale/msfem/msfem_traits.hh> #include <dune/multiscale/problems/base.hh> #include <dune/multiscale/problems/selector.hh> #include <dune/multiscale/tools/discretefunctionwriter.hh> #include <dune/multiscale/tools/misc.hh> #include <dune/multiscale/msfem/coarse_rhs_functional.hh> #include <dune/stuff/common/parallel/partitioner.hh> #include <dune/grid/utility/partitioning/seedlist.hh> #include <sstream> namespace Dune { namespace Multiscale { Stuff::LA::SparsityPatternDefault CoarseScaleOperator::pattern(const CoarseScaleOperator::RangeSpaceType& range_space, const CoarseScaleOperator::SourceSpaceType& source_space, const CoarseScaleOperator::GridViewType& grid_view) { return range_space.compute_volume_pattern(grid_view, source_space); } CoarseScaleOperator::CoarseScaleOperator(const CoarseScaleOperator::SourceSpaceType& source_space_in, LocalGridList& localGridList) : OperatorBaseType(global_matrix_, source_space_in) , AssemblerBaseType(source_space_in, source_space_in.grid_view().grid().template leafGridView<InteriorBorder_Partition>()) , global_matrix_(coarse_space().mapper().size(), coarse_space().mapper().size(), EllipticOperatorType::pattern(coarse_space())) , local_assembler_(local_operator_, localGridList) , msfem_rhs_(coarse_space(), "MsFEM right hand side") , dirichlet_projection_(coarse_space()) { DSC::Profiler::ScopedTiming st("msfem.coarse.assemble"); msfem_rhs_.vector() *= 0; const auto interior = coarse_space().grid_view().grid().template leafGridView<InteriorBorder_Partition>(); typedef std::remove_const<decltype(interior)>::type InteriorType; Stuff::IndexSetPartitioner<InteriorType> ip(interior.indexSet()); SeedListPartitioning<typename InteriorType::Grid, 0> partitioning(interior, ip); CoarseRhsFunctional force_functional(msfem_rhs_.vector(), coarse_space(), localGridList, interior); const auto& dirichlet = DMP::getDirichletData(); const auto& boundary_info = Problem::getModelData()->boundaryInfo(); const auto& neumann = Problem::getNeumannData(); typedef CommonTraits::InteriorGridViewType InteriorView; GDT::Operators::DirichletProjectionLocalizable<InteriorView, Problem::DirichletDataBase, CommonTraits::DiscreteFunctionType> dirichlet_projection_operator(interior, boundary_info, *dirichlet, dirichlet_projection_); GDT::Functionals::L2Face<Problem::NeumannDataBase, CommonTraits::GdtVectorType, CommonTraits::SpaceType, InteriorView> neumann_functional(*neumann, msfem_rhs_.vector(), coarse_space(), interior); this->add_codim0_assembler(local_assembler_, this->matrix()); this->add(force_functional); this->add(dirichlet_projection_operator, new DSG::ApplyOn::BoundaryEntities<CommonTraits::InteriorGridViewType>()); this->add(neumann_functional, new DSG::ApplyOn::NeumannIntersections<CommonTraits::InteriorGridViewType>(boundary_info)); AssemblerBaseType::assemble(partitioning); // substract the operators action on the dirichlet values, since we assemble in H^1 but solve in H^1_0 CommonTraits::GdtVectorType tmp(coarse_space().mapper().size()); global_matrix_.mv(dirichlet_projection_.vector(), tmp); force_functional.vector() -= tmp; // apply the dirichlet zero constraints to restrict the system to H^1_0 GDT::Spaces::Constraints::Dirichlet<typename CommonTraits::GridViewType::Intersection, CommonTraits::RangeFieldType> dirichlet_constraints(boundary_info, coarse_space().mapper().maxNumDofs(), coarse_space().mapper().maxNumDofs()); this->add(dirichlet_constraints, global_matrix_ /*, new GDT::ApplyOn::BoundaryEntities< GridViewType >()*/); this->add(dirichlet_constraints, force_functional.vector() /*, new GDT::ApplyOn::BoundaryEntities< GridViewType >()*/); if(!DSC_CONFIG_GET("global.smp_constraints", false)) AssemblerBaseType::assemble(false); else AssemblerBaseType::assemble(partitioning); } void CoarseScaleOperator::assemble() { DUNE_THROW(Dune::InvalidStateException, "nobody should be calling this"); } void CoarseScaleOperator::apply_inverse(CoarseScaleOperator::CoarseDiscreteFunction& solution) { DSC::Profiler::ScopedTiming st("msfem.coarse.solve"); BOOST_ASSERT_MSG(msfem_rhs_.dofs_valid(), "Coarse scale RHS DOFs need to be valid!"); DSC_PROFILER.startTiming("msfem.coarse.linearSolver"); typedef typename BackendChooser<CoarseDiscreteFunctionSpace>::InverseOperatorType Inverse; const Inverse inverse( global_matrix_, msfem_rhs_.space().communicator()); auto options = Inverse::options("bicgstab.amg.ilu0"); constexpr bool overwrite = true; options.set("preconditioner.anisotropy_dim", CommonTraits::world_dim, overwrite); options.set("preconditioner.isotropy_dim", CommonTraits::world_dim, overwrite); options.set("verbose", "2", overwrite); options.set("preconditioner.verbose", "2", overwrite); options.set("smoother.verbose", "2", overwrite); options.set("post_check_solves_system", "0", overwrite); inverse.apply(msfem_rhs_.vector(), solution.vector(), options); if (!solution.dofs_valid()) DUNE_THROW(InvalidStateException, "Degrees of freedom of coarse solution are not valid!"); solution.vector() += dirichlet_projection_.vector(); DSC_PROFILER.stopTiming("msfem.coarse.linearSolver"); DSC_LOG_INFO << "Time to solve coarse MsFEM problem: " << DSC_PROFILER.getTiming("msfem.coarse.linearSolver") << "ms." << std::endl; } const CoarseScaleOperator::SourceSpaceType& CoarseScaleOperator::coarse_space() const { return test_space(); } } // namespace Multiscale { } // namespace Dune { <commit_msg>adds a hard limit on coarse bicg iterations<commit_after>#include <config.h> #include "coarse_scale_operator.hh" #include <dune/stuff/common/exceptions.hh> #include <dune/stuff/common/configuration.hh> #include <dune/stuff/fem/functions/integrals.hh> #include <dune/stuff/common/profiler.hh> #include <dune/stuff/grid/walker.hh> #include <dune/gdt/operators/projections.hh> #include <dune/gdt/operators/prolongations.hh> #include <dune/gdt/spaces/constraints.hh> #include <dune/gdt/functionals/l2.hh> #include <dune/multiscale/msfem/localproblems/localproblemsolver.hh> #include <dune/multiscale/msfem/localproblems/localsolutionmanager.hh> #include <dune/multiscale/msfem/localproblems/localgridlist.hh> #include <dune/multiscale/msfem/msfem_traits.hh> #include <dune/multiscale/problems/base.hh> #include <dune/multiscale/problems/selector.hh> #include <dune/multiscale/tools/discretefunctionwriter.hh> #include <dune/multiscale/tools/misc.hh> #include <dune/multiscale/msfem/coarse_rhs_functional.hh> #include <dune/stuff/common/parallel/partitioner.hh> #include <dune/grid/utility/partitioning/seedlist.hh> #include <sstream> namespace Dune { namespace Multiscale { Stuff::LA::SparsityPatternDefault CoarseScaleOperator::pattern(const CoarseScaleOperator::RangeSpaceType& range_space, const CoarseScaleOperator::SourceSpaceType& source_space, const CoarseScaleOperator::GridViewType& grid_view) { return range_space.compute_volume_pattern(grid_view, source_space); } CoarseScaleOperator::CoarseScaleOperator(const CoarseScaleOperator::SourceSpaceType& source_space_in, LocalGridList& localGridList) : OperatorBaseType(global_matrix_, source_space_in) , AssemblerBaseType(source_space_in, source_space_in.grid_view().grid().template leafGridView<InteriorBorder_Partition>()) , global_matrix_(coarse_space().mapper().size(), coarse_space().mapper().size(), EllipticOperatorType::pattern(coarse_space())) , local_assembler_(local_operator_, localGridList) , msfem_rhs_(coarse_space(), "MsFEM right hand side") , dirichlet_projection_(coarse_space()) { DSC::Profiler::ScopedTiming st("msfem.coarse.assemble"); msfem_rhs_.vector() *= 0; const auto interior = coarse_space().grid_view().grid().template leafGridView<InteriorBorder_Partition>(); typedef std::remove_const<decltype(interior)>::type InteriorType; Stuff::IndexSetPartitioner<InteriorType> ip(interior.indexSet()); SeedListPartitioning<typename InteriorType::Grid, 0> partitioning(interior, ip); CoarseRhsFunctional force_functional(msfem_rhs_.vector(), coarse_space(), localGridList, interior); const auto& dirichlet = DMP::getDirichletData(); const auto& boundary_info = Problem::getModelData()->boundaryInfo(); const auto& neumann = Problem::getNeumannData(); typedef CommonTraits::InteriorGridViewType InteriorView; GDT::Operators::DirichletProjectionLocalizable<InteriorView, Problem::DirichletDataBase, CommonTraits::DiscreteFunctionType> dirichlet_projection_operator(interior, boundary_info, *dirichlet, dirichlet_projection_); GDT::Functionals::L2Face<Problem::NeumannDataBase, CommonTraits::GdtVectorType, CommonTraits::SpaceType, InteriorView> neumann_functional(*neumann, msfem_rhs_.vector(), coarse_space(), interior); this->add_codim0_assembler(local_assembler_, this->matrix()); this->add(force_functional); this->add(dirichlet_projection_operator, new DSG::ApplyOn::BoundaryEntities<CommonTraits::InteriorGridViewType>()); this->add(neumann_functional, new DSG::ApplyOn::NeumannIntersections<CommonTraits::InteriorGridViewType>(boundary_info)); AssemblerBaseType::assemble(partitioning); // substract the operators action on the dirichlet values, since we assemble in H^1 but solve in H^1_0 CommonTraits::GdtVectorType tmp(coarse_space().mapper().size()); global_matrix_.mv(dirichlet_projection_.vector(), tmp); force_functional.vector() -= tmp; // apply the dirichlet zero constraints to restrict the system to H^1_0 GDT::Spaces::Constraints::Dirichlet<typename CommonTraits::GridViewType::Intersection, CommonTraits::RangeFieldType> dirichlet_constraints(boundary_info, coarse_space().mapper().maxNumDofs(), coarse_space().mapper().maxNumDofs()); this->add(dirichlet_constraints, global_matrix_ /*, new GDT::ApplyOn::BoundaryEntities< GridViewType >()*/); this->add(dirichlet_constraints, force_functional.vector() /*, new GDT::ApplyOn::BoundaryEntities< GridViewType >()*/); if(!DSC_CONFIG_GET("global.smp_constraints", false)) AssemblerBaseType::assemble(false); else AssemblerBaseType::assemble(partitioning); } void CoarseScaleOperator::assemble() { DUNE_THROW(Dune::InvalidStateException, "nobody should be calling this"); } void CoarseScaleOperator::apply_inverse(CoarseScaleOperator::CoarseDiscreteFunction& solution) { DSC::Profiler::ScopedTiming st("msfem.coarse.solve"); BOOST_ASSERT_MSG(msfem_rhs_.dofs_valid(), "Coarse scale RHS DOFs need to be valid!"); DSC_PROFILER.startTiming("msfem.coarse.linearSolver"); typedef typename BackendChooser<CoarseDiscreteFunctionSpace>::InverseOperatorType Inverse; const Inverse inverse( global_matrix_, msfem_rhs_.space().communicator()); auto options = Inverse::options("bicgstab.amg.ilu0"); constexpr bool overwrite = true; options.set("preconditioner.anisotropy_dim", CommonTraits::world_dim, overwrite); options.set("preconditioner.isotropy_dim", CommonTraits::world_dim, overwrite); options.set("verbose", "2", overwrite); options.set("max_iter", "300", overwrite); options.set("preconditioner.verbose", "2", overwrite); options.set("smoother.verbose", "2", overwrite); options.set("post_check_solves_system", "0", overwrite); inverse.apply(msfem_rhs_.vector(), solution.vector(), options); if (!solution.dofs_valid()) DUNE_THROW(InvalidStateException, "Degrees of freedom of coarse solution are not valid!"); solution.vector() += dirichlet_projection_.vector(); DSC_PROFILER.stopTiming("msfem.coarse.linearSolver"); DSC_LOG_INFO << "Time to solve coarse MsFEM problem: " << DSC_PROFILER.getTiming("msfem.coarse.linearSolver") << "ms." << std::endl; } const CoarseScaleOperator::SourceSpaceType& CoarseScaleOperator::coarse_space() const { return test_space(); } } // namespace Multiscale { } // namespace Dune { <|endoftext|>
<commit_before>/* * easyeye_segment.cc * * Created on: Jul 11, 2013 * Author: mchaberski */ #include "../common/easyeye_imaging.h" #include "easyeye_segment.h" #include "FindPupilCircleNew.h" #include "FindIrisCircle.h" #include "FindEyelidMix.h" #include "easyeye_extrema_noise.h" #include <Masek.h> #include "../common/mylog.h" #include "../common/base64.h" #include <iostream> #include <string> using mylog::Logs; using mylog::TRACE; using namespace std; using namespace easyeye; using namespace cv; Segmentation::Segmentation() : status(Result::NOT_YET_SET), boundary_pair(), eyelids_location(), extrema_noise() { } Segmentation::~Segmentation() { } void Segmentation::Describe(std::ostream& out) const { out << Result::DescribeStatus(status) << ' '; boundary_pair.Describe(out); } /* * TODO define Segmentation copy constructor and copy assignment operator * No client code uses these yet, so we can hold off. */ Segmenter::Segmenter() : config_() { } void fill_array(int array[], const int value, const int start, const int len) { for (int i = start; i < (start+len); i++) { array[i] = value; } } void Segmenter::SegmentEyeImage(cv::Mat& eyeImg, Segmentation& seg) { if (!Imaging::IsGray(eyeImg)) { Logs::GetLogger().Log(mylog::ERROR, "Segmenter::SegmentEyeImage input image must be grayscale, not type %d", eyeImg.type()); seg.status = Result::FAILURE; return; } int bothnScale = 1; // Scale if the image size is larger than w x h // [MC:] shouldn't this be OR instead of AND? int imageWidth = eyeImg.cols, imageHeight = eyeImg.rows; if(imageWidth > EYE_IMAGE_WIDTH_SCALE_THRESHOLD && imageHeight > EYE_IMAGE_HEIGHT_SCALE_THRESHOLD) { bothnScale = 2; } if (config_.pupil_finder_config.nScale != CircleFinderConfig::NSCALE_AUTO || config_.iris_finder_config.nScale != CircleFinderConfig::NSCALE_AUTO) { Logs::GetLogger().Log(mylog::ERROR, "Segmenter::SegmentEyeImage configuration " "with non-auto nscale for circle finders is not yet supported"); seg.status = Result::FAILURE; return; } config_.pupil_finder_config.nScale = bothnScale; config_.iris_finder_config.nScale = bothnScale; FindPupilCircleNew pupil_finder(config_.pupil_finder_config); pupil_finder.set_diagnostician(diagnostician_); IntCircle pupilCircle = pupil_finder.doDetect(eyeImg); BoundaryPair& bpair = seg.boundary_pair; bpair.set_pupil(pupilCircle); // Set-up ROI for detecting the iris circle const int rIrisMax = config_.iris_finder_config.max_radius(); Imaging::EyeImageROI eye_image_roi = Imaging::GetEyeImageROI(eyeImg, pupilCircle.center, bpair.pupil.radius, rIrisMax, rIrisMax); //82 is the best for video images, previous 80 Mat setImg = Imaging::GetROI(eyeImg, eye_image_roi.rect.x, eye_image_roi.rect.width, eye_image_roi.rect.y, eye_image_roi.rect.height); /// \todo Possible to optimize? // Define maximum distance between pupil and iris center position // int centerAdjust= config_.iris_finder_config.max_pupil_center_offset();//int)(rIrisMax/4); // Find iris circle using Hough Transform FindIrisCircle iris_finder(config_.iris_finder_config); IntCircle irisCircle = iris_finder.doDetect(setImg, bpair.pupil.radius); bpair.set_iris(irisCircle); CvPoint xyIrisIn; xyIrisIn.x = bpair.iris.center.x; xyIrisIn.y = bpair.iris.center.y; cv::Point2i xyIris = iris_finder.getOriginPoints(pupilCircle.center, xyIrisIn, eye_image_roi.p); bpair.iris.center.x = xyIris.x; bpair.iris.center.y = xyIris.y; // Find the upper and lower eyelid(s) FindEyelidMix eyelid_finder(config_.eyelid_finder_config); eyelid_finder.doFindPoints(eyeImg, bpair, seg.eyelids_location); Mat eyelidImg = eyelid_finder.CreateNoiseImage(eyeImg, seg.eyelids_location); ExtremaNoiseFinder extrema_noise_finder(config_.extrema_noise_finder_config); extrema_noise_finder.FindExtremaNoise(eyeImg).copyTo(seg.extrema_noise); diagnostician()->DumpSegOutput(seg.boundary_pair, seg.eyelids_location, seg.extrema_noise); seg.status = Result::SUCCESS; } SegmenterConfig::SegmenterConfig() : Config(), iris_finder_config(), pupil_finder_config(), eyelid_finder_config(), extrema_noise_finder_config() { } Contours::Contours() { } cv::RotatedRect Contours::fitEllipse(std::vector<cv::Point2i>& points) { return fitEllipse(points.begin(), points.end()); } cv::RotatedRect Contours::fitEllipse(std::vector<cv::Point2i>::iterator points_begin, std::vector<cv::Point2i>::iterator points_end) { vector<cv::Point2f> fpoints; for (vector<cv::Point2i>::iterator it = points_begin; it != points_end; ++it) { Point2f d((*it).x, (*it).y); fpoints.push_back(d); } return cv::fitEllipse(fpoints); } bool serial::SegmentationAdapter::FromJson(const Json::Value& src, void* dst) { Segmentation& seg = *((Segmentation*)dst); seg.status = (Segmentation::Status) src.get("status", Result::FAILURE).asInt(); if (!Deserialize(src["boundary_pair"], seg.boundary_pair)) { return false; } SparseMatAdapter sma; if (!Deserialize(src["extrema_noise"], &sma, seg.extrema_noise)) { return false; } if (!Deserialize(src["eyelids_location"], seg.eyelids_location)) { return false; } return src.isMember("status") && src.isMember("boundary_pair") && src.isMember("extrema_noise") && src.isMember("eyelids_location"); } void serial::SegmentationAdapter::ToJson(void* src, Json::Value& dst) { Segmentation& seg = *((Segmentation*)src); dst["status"] = seg.status; Json::Value boundary_pair; Serialize(seg.boundary_pair, boundary_pair); dst["boundary_pair"] = boundary_pair; SparseMatAdapter sma; Json::Value extrema_noise; Serialize(seg.extrema_noise, &sma, extrema_noise); dst["extrema_noise"] = extrema_noise; Json::Value eyelids_location; Serialize(seg.eyelids_location, eyelids_location); dst["eyelids_location"] = eyelids_location; } string serial::Serialize(const Segmentation& data) { SegmentationAdapter adapter; return Serialize(data, &adapter); } bool serial::Deserialize(const std::string& json, Segmentation& data) { SegmentationAdapter adapter; return Deserialize(json, &adapter, data); }<commit_msg>passing diagnostician to eyelid finder; removed unnecessary image allocation<commit_after>/* * easyeye_segment.cc * * Created on: Jul 11, 2013 * Author: mchaberski */ #include "../common/easyeye_imaging.h" #include "easyeye_segment.h" #include "FindPupilCircleNew.h" #include "FindIrisCircle.h" #include "FindEyelidMix.h" #include "easyeye_extrema_noise.h" #include <Masek.h> #include "../common/mylog.h" #include "../common/base64.h" #include <iostream> #include <string> using mylog::Logs; using mylog::TRACE; using namespace std; using namespace easyeye; using namespace cv; Segmentation::Segmentation() : status(Result::NOT_YET_SET), boundary_pair(), eyelids_location(), extrema_noise() { } Segmentation::~Segmentation() { } void Segmentation::Describe(std::ostream& out) const { out << Result::DescribeStatus(status) << ' '; boundary_pair.Describe(out); } /* * TODO define Segmentation copy constructor and copy assignment operator * No client code uses these yet, so we can hold off. */ Segmenter::Segmenter() : config_() { } void fill_array(int array[], const int value, const int start, const int len) { for (int i = start; i < (start+len); i++) { array[i] = value; } } void Segmenter::SegmentEyeImage(cv::Mat& eyeImg, Segmentation& seg) { if (!Imaging::IsGray(eyeImg)) { Logs::GetLogger().Log(mylog::ERROR, "Segmenter::SegmentEyeImage input image must be grayscale, not type %d", eyeImg.type()); seg.status = Result::FAILURE; return; } int bothnScale = 1; // Scale if the image size is larger than w x h // [MC:] shouldn't this be OR instead of AND? int imageWidth = eyeImg.cols, imageHeight = eyeImg.rows; if(imageWidth > EYE_IMAGE_WIDTH_SCALE_THRESHOLD && imageHeight > EYE_IMAGE_HEIGHT_SCALE_THRESHOLD) { bothnScale = 2; } if (config_.pupil_finder_config.nScale != CircleFinderConfig::NSCALE_AUTO || config_.iris_finder_config.nScale != CircleFinderConfig::NSCALE_AUTO) { Logs::GetLogger().Log(mylog::ERROR, "Segmenter::SegmentEyeImage configuration " "with non-auto nscale for circle finders is not yet supported"); seg.status = Result::FAILURE; return; } config_.pupil_finder_config.nScale = bothnScale; config_.iris_finder_config.nScale = bothnScale; FindPupilCircleNew pupil_finder(config_.pupil_finder_config); pupil_finder.set_diagnostician(diagnostician_); IntCircle pupilCircle = pupil_finder.doDetect(eyeImg); BoundaryPair& bpair = seg.boundary_pair; bpair.set_pupil(pupilCircle); // Set-up ROI for detecting the iris circle const int rIrisMax = config_.iris_finder_config.max_radius(); Imaging::EyeImageROI eye_image_roi = Imaging::GetEyeImageROI(eyeImg, pupilCircle.center, bpair.pupil.radius, rIrisMax, rIrisMax); //82 is the best for video images, previous 80 Mat setImg = Imaging::GetROI(eyeImg, eye_image_roi.rect.x, eye_image_roi.rect.width, eye_image_roi.rect.y, eye_image_roi.rect.height); /// \todo Possible to optimize? // Define maximum distance between pupil and iris center position // int centerAdjust= config_.iris_finder_config.max_pupil_center_offset();//int)(rIrisMax/4); // Find iris circle using Hough Transform FindIrisCircle iris_finder(config_.iris_finder_config); IntCircle irisCircle = iris_finder.doDetect(setImg, bpair.pupil.radius); bpair.set_iris(irisCircle); CvPoint xyIrisIn; xyIrisIn.x = bpair.iris.center.x; xyIrisIn.y = bpair.iris.center.y; cv::Point2i xyIris = iris_finder.getOriginPoints(pupilCircle.center, xyIrisIn, eye_image_roi.p); bpair.iris.center.x = xyIris.x; bpair.iris.center.y = xyIris.y; // Find the upper and lower eyelid(s) FindEyelidMix eyelid_finder(config_.eyelid_finder_config); eyelid_finder.set_diagnostician(diagnostician_); eyelid_finder.doFindPoints(eyeImg, bpair, seg.eyelids_location); ExtremaNoiseFinder extrema_noise_finder(config_.extrema_noise_finder_config); extrema_noise_finder.FindExtremaNoise(eyeImg).copyTo(seg.extrema_noise); diagnostician()->DumpSegOutput(seg.boundary_pair, seg.eyelids_location, seg.extrema_noise); seg.status = Result::SUCCESS; } SegmenterConfig::SegmenterConfig() : Config(), iris_finder_config(), pupil_finder_config(), eyelid_finder_config(), extrema_noise_finder_config() { } Contours::Contours() { } cv::RotatedRect Contours::fitEllipse(std::vector<cv::Point2i>& points) { return fitEllipse(points.begin(), points.end()); } cv::RotatedRect Contours::fitEllipse(std::vector<cv::Point2i>::iterator points_begin, std::vector<cv::Point2i>::iterator points_end) { vector<cv::Point2f> fpoints; for (vector<cv::Point2i>::iterator it = points_begin; it != points_end; ++it) { Point2f d((*it).x, (*it).y); fpoints.push_back(d); } return cv::fitEllipse(fpoints); } bool serial::SegmentationAdapter::FromJson(const Json::Value& src, void* dst) { Segmentation& seg = *((Segmentation*)dst); seg.status = (Segmentation::Status) src.get("status", Result::FAILURE).asInt(); if (!Deserialize(src["boundary_pair"], seg.boundary_pair)) { return false; } SparseMatAdapter sma; if (!Deserialize(src["extrema_noise"], &sma, seg.extrema_noise)) { return false; } if (!Deserialize(src["eyelids_location"], seg.eyelids_location)) { return false; } return src.isMember("status") && src.isMember("boundary_pair") && src.isMember("extrema_noise") && src.isMember("eyelids_location"); } void serial::SegmentationAdapter::ToJson(void* src, Json::Value& dst) { Segmentation& seg = *((Segmentation*)src); dst["status"] = seg.status; Json::Value boundary_pair; Serialize(seg.boundary_pair, boundary_pair); dst["boundary_pair"] = boundary_pair; SparseMatAdapter sma; Json::Value extrema_noise; Serialize(seg.extrema_noise, &sma, extrema_noise); dst["extrema_noise"] = extrema_noise; Json::Value eyelids_location; Serialize(seg.eyelids_location, eyelids_location); dst["eyelids_location"] = eyelids_location; } string serial::Serialize(const Segmentation& data) { SegmentationAdapter adapter; return Serialize(data, &adapter); } bool serial::Deserialize(const std::string& json, Segmentation& data) { SegmentationAdapter adapter; return Deserialize(json, &adapter, data); }<|endoftext|>
<commit_before>#include "allocore/sound/al_Vbap.hpp" namespace al{ void SpeakerTriple::loadVectors(const std::vector<Speaker>& spkrs){ s1Vec = spkrs[s1].vec(); s2Vec = spkrs[s2].vec(); if(s3!=-1){ s3Vec = spkrs[s3].vec(); } vec[0]=s1Vec; vec[1]=s2Vec; vec[2]=s3Vec; mat.set(s1Vec[0],s1Vec[1],s1Vec[2], s2Vec[0],s2Vec[1],s2Vec[2], s3Vec[0],s3Vec[1],s3Vec[2] ); } Vbap::Vbap(const SpeakerLayout &sl) : Spatializer(sl), mCachedTripletIndex(0), mIs3D(true) {} void Vbap::addTriple(const SpeakerTriple& st) { mTriplets.push_back(st); ++mNumTriplets; } Vec3d Vbap::computeGains(const Vec3d& vecA, const SpeakerTriple& speak) { const Mat3d& mat = speak.mat; unsigned dimensions = mIs3D ? 3 : 2; Vec3d vec(0., 0., 0.); // For each node, insert speaker coordinates in matrix for (unsigned i = 0; i < dimensions; i++){ for (unsigned j = 0; j < dimensions; j++){ vec[i] += vecA[j] * mat(j,i); } } //printf("Gains: (%f,%f,%f)",vec[0],vec[1],vec[2]); //printf("Triplet: (%d,%d,%d)",speak.s1,speak.s2,speak.s3); return vec; } // 2D VBAP, find pairs of speakers. void Vbap::findSpeakerPairs(const std::vector<Speaker>& spkrs){ unsigned numSpeakers = spkrs.size(); unsigned j, index; unsigned speakerMapping[numSpeakers]; // To map unordered speakers into an ordered set. float speakerAngles[numSpeakers]; float indexAngle; // Build a map to the speakers, that points to speaker indexes. for (unsigned i = 0; i < numSpeakers; i++) { speakerAngles[i] = spkrs[i].azimuth; speakerMapping[i] = i; } // Sort speakers into the map for (unsigned i = 1; i < numSpeakers; i++) { // Only sort speakers that have elevation == 0. Ignore all other. if (spkrs[i].elevation == 0) { indexAngle = speakerAngles[i]; index = speakerMapping[i]; j = i; while ((j > 0) && (speakerAngles[j-1] > indexAngle)) { speakerAngles[j] = speakerAngles[j-1]; speakerMapping[j] = speakerMapping[j-1]; j = j - 1; } speakerAngles[j] = indexAngle; speakerMapping[j] = index; } } // Add speaker-pairs for (unsigned i = 1; i < numSpeakers; i++){ SpeakerTriple triple; triple.s1 = speakerMapping[i-1]; triple.s2 = speakerMapping[i]; triple.s3 = -1; triple.loadVectors(spkrs); addTriple(triple); } // Add the last speaker-pair SpeakerTriple triple; triple.s1 = speakerMapping[numSpeakers-1]; triple.s2 = speakerMapping[0]; triple.s3 = -1; triple.loadVectors(spkrs); addTriple(triple); } bool Vbap::isCrossing(Vec3d c, Vec3d v, const SpeakerTriple& trip){ double a1 = angle(c,trip.s1Vec)+angle(c,trip.s2Vec); double a2 = angle(trip.s1Vec,trip.s2Vec); double a3 = angle(c,trip.s3Vec)+angle(c,v); double a4 = angle(trip.s3Vec,v); return (a1==a2 && a3==a4); } void Vbap::findSpeakerTriplets(const std::vector<Speaker>& spkrs){ std::list<SpeakerTriple> triplets; unsigned numSpeakers = spkrs.size(); int numSpeakersSigned = (int)numSpeakers; // form all possible triples for (unsigned i = 0; i < numSpeakers; i++){ for (unsigned j = i+1; j < numSpeakers; j++){ for (unsigned k = j+1; k < numSpeakers; k++){ SpeakerTriple triplet; triplet.s1=i; triplet.s2=j; triplet.s3=k; triplet.loadVectors(spkrs); triplets.push_back(triplet); } } } printf("Speaker-count=%d, Initial triplet-count=%d\n",numSpeakers,(unsigned)triplets.size()); // remove too narrow triples for(std::list<SpeakerTriple>::iterator it = triplets.begin(); it != triplets.end();++it){ SpeakerTriple trip = (*it); Vec3d xprod = cross(trip.s1Vec,trip.s2Vec); float volume = fabs(xprod.dot(trip.s3Vec)); float length = fabs(angle(trip.s1Vec , trip.s2Vec) ) + fabs(angle(trip.s1Vec , trip.s3Vec) ) + fabs(angle(trip.s2Vec , trip.s3Vec) ); float ratio; if (length > MIN_LENGTH){ ratio = volume / length; }else{ ratio = 0.0; } if (ratio < MIN_VOLUME_TO_LENGTH_RATIO) { //printf("v=%f, l=%f, r=%f x=(%f,%f,%f)\n",volume,length,ratio,xprod[0],xprod[1],xprod[2]); triplets.erase(it); --it; } } for(std::list<SpeakerTriple>::iterator it = triplets.begin(); it != triplets.end();++it){ SpeakerTriple trip = (*it); bool remove = false; for(std::list<SpeakerTriple>::iterator it2 = triplets.begin(); it2 != triplets.end();++it2){ SpeakerTriple trip2 = (*it2); for (unsigned j = 0; j < 3; ++j) { Vec3d v = trip2.vec[j]; Vec3d c = cross(cross(trip.s1Vec, trip.s2Vec),cross(trip.s3Vec,v)); if (isCrossing(c,v,trip) || isCrossing(-c,v, trip)) { remove = true; printf("Removing v=(%f,%f,%f) c=(%f,%f,%f)\n",v[0],v[1],v[2],c[0],c[1],c[2]); break; } } } if (remove) { triplets.erase(it); --it; } } // remove triangles that contain other Speakers for(std::list<SpeakerTriple>::iterator it = triplets.begin(); it != triplets.end();++it){ SpeakerTriple trip = (*it); Mat3d invMat = Mat3d(trip.mat).transpose(); for (int jj = 0; jj < numSpeakersSigned; ++jj) { // check to see if the current speaker is one of the nodes of the triple if ((jj == trip.s1) || (jj == trip.s2) || (jj == trip.s3) ) continue; Vec3d sVec = spkrs[jj].vec(); Vec3d v = sVec * invMat; // inside if positive or negative near zero, -1e-4 is a magic number bool x_inside = v[0] >= -1e-4; bool y_inside = v[1] >= -1e-4; bool z_inside = v[2] >= -1e-4; if (x_inside && y_inside && (mIs3D || z_inside)){ //printf("Removing v=(%f,%f,%f)\n",v[0],v[1],v[2]); triplets.erase(it); --it; break; } } } for(std::list<SpeakerTriple>::iterator it = triplets.begin(); it != triplets.end(); ++it) { addTriple(*it); } } void Vbap::compile(Listener& listener){ this->mListener = &listener; //Check if 3D... if(mIs3D){ printf("Finding triplets\n"); findSpeakerTriplets(mSpeakers); } else{ printf("Finding pairs\n"); findSpeakerPairs(mSpeakers); } print(); if (mNumTriplets == 0 ){ printf("No SpeakerSets found. Check mode setting or speaker layout.\n"); throw -1; } } void Vbap::perform(AudioIOData& io, SoundSource& src, Vec3d& relpos, const int& numFrames, int& frameIndex, float& sample){ unsigned currentTripletIndex = mCachedTripletIndex; // Cached source placement, so it starts searching from there. Vec3d vec = Vec3d(relpos); //printf("(%f,%f,%f)\n",vec[0],vec[1],vec[2]); //Rotate vector according to listener-rotation Quatd srcRot = this->mListener->pose().quat(); vec = srcRot.rotate(vec); //Silent by default Vec3d gains; Vec3d gainsTemp; // Search thru the triplets array in search of a match for the source position. for (unsigned count = 0; count < mNumTriplets; ++count) { gainsTemp = computeGains(vec, mTriplets[currentTripletIndex]); if ((gainsTemp[0] >= 0) && (gainsTemp[1] >= 0) && (!mIs3D || (gainsTemp[2] >= 0)) ){ //printf("Gainstemp: (%f,%f,%f)\n",gainsTemp[0],gainsTemp[1],gainsTemp[2]); gainsTemp.normalize(); gains = gainsTemp*sample/relpos.mag(); //printf("Found: (%d,%d,%d) \n", mTriplets[currentTripletIndex].s1, mTriplets[currentTripletIndex].s2, mTriplets[currentTripletIndex].s3); break; } ++currentTripletIndex; if (currentTripletIndex >= mNumTriplets){ currentTripletIndex = 0; } //printf("Index: %d\n",count); } //printf("Gains: (%f,%f,%f)\n",gains[0],gains[1],gains[2]); SpeakerTriple triple = mTriplets[currentTripletIndex]; if(mCachedTripletIndex!=currentTripletIndex){ printf("Triple: (%d,%d,%d)\n",triple.s1,triple.s2,triple.s3); printf("Gains: (%f,%f,%f)\n",gains[0],gains[1],gains[2]); printf("Gains-temp: (%f,%f,%f)\n",gainsTemp[0],gainsTemp[1],gainsTemp[2]); } mCachedTripletIndex = currentTripletIndex; // Store the new index io.out(triple.s1,frameIndex) += gains[0]; io.out(triple.s2,frameIndex) += gains[1]; if(mIs3D){ io.out(triple.s3, frameIndex) += gains[2]; } } void Vbap::print() { printf("Number of Triplets: %d\n",mNumTriplets); for (unsigned i = 0; i < mNumTriplets; i++) { printf("Triple #%d: %d,%d,%d \n",i,mTriplets[i].s1,mTriplets[i].s2,mTriplets[i].s3); } } } // al:: <commit_msg>Large update to file<commit_after>#include "allocore/sound/al_Vbap.hpp" namespace al{ // TODO: invert in al_Mat seems wrong this is a temp. fix. template <class T> bool invert2(Mat<2,T>& m){ T det = determinant(m); if(det != 0){ m.set( m(1,1)/det,-m(0,1)/det, -m(1,0)/det, m(0,0)/det ); return true; } return false; } bool SpeakerTriple::loadVectors(const std::vector<Speaker>& spkrs){ bool hasInverse; //Store speaker for getting the channel iteratively // speakers[0] = spkrs[s1]; // speakers[1] = spkrs[s2]; s1Vec = spkrs[s1].vec(); s2Vec = spkrs[s2].vec(); s1Chan = spkrs[s1].deviceChannel; s2Chan = spkrs[s2].deviceChannel; if(s3!=-1){ // 3d Speaker layout s3Vec = spkrs[s3].vec(); s3Chan = spkrs[s3].deviceChannel; // speakers[2] = spkrs[s3]; mat.set(s1Vec[0],s1Vec[1],s1Vec[2], s2Vec[0],s2Vec[1],s2Vec[2], s3Vec[0],s3Vec[1],s3Vec[2] ); hasInverse = invert(mat); }else{ // 2d Speaker layout Mat<2,double> tempMat; tempMat.set(s1Vec[0],s1Vec[1], s2Vec[0],s2Vec[1] ); hasInverse = invert2(tempMat); //insert inverted matrix into 3x3 matrix mat.set(tempMat(0,0),tempMat(0,1),s1Vec[2], tempMat(1,0),tempMat(1,1),s2Vec[2], s3Vec[0],s3Vec[1],s3Vec[2] ); } vec[0]=s1Vec; vec[1]=s2Vec; vec[2]=s3Vec; //For finding crossings speakerIdx[0] = s1; speakerIdx[1] = s2; speakerIdx[2] = s3; speakerChan[0] = s1Chan; speakerChan[1] = s2Chan; speakerChan[2] = s2Chan; return hasInverse; } Vbap::Vbap(const SpeakerLayout &sl) : Spatializer(sl), /*mCachedTripletIndex(0),*/ mIs3D(true) {} void Vbap::addTriple(const SpeakerTriple& st) { mTriplets.push_back(st); ++mNumTriplets; } Vec3d Vbap::computeGains(const Vec3d& vecA, const SpeakerTriple& speak) { const Mat3d& mat = speak.mat; unsigned dimensions = mIs3D ? 3 : 2; Vec3d vec(0., 0., 0.); // For each node, insert speaker coordinates in matrix for (unsigned i = 0; i < dimensions; i++){ for (unsigned j = 0; j < dimensions; j++){ vec[i] += vecA[j] * mat(j,i); } } return vec; } // 2D VBAP, find pairs of speakers. void Vbap::findSpeakerPairs(const std::vector<Speaker>& spkrs){ unsigned numSpeakers = spkrs.size(); unsigned j, index; unsigned speakerMapping[numSpeakers]; // To map unordered speakers into an ordered set. float speakerAngles[numSpeakers]; float indexAngle; // Build a map to the speaker, that points to speaker indexes. for (unsigned i = 0; i < numSpeakers; i++) { speakerAngles[i] = spkrs[i].azimuth; // speakerMapping[i] = spkrs[i].deviceChannel; speakerMapping[i] = i; } // Sort speakers into the map for (unsigned i = 1; i < numSpeakers; i++) { // Only sort speakers that have elevation == 0. Ignore all other. if (spkrs[i].elevation == 0) { indexAngle = speakerAngles[i]; index = speakerMapping[i]; j = i; while ((j > 0) && (speakerAngles[j-1] > indexAngle)) { speakerAngles[j] = speakerAngles[j-1]; speakerMapping[j] = speakerMapping[j-1]; j = j - 1; } speakerAngles[j] = indexAngle; speakerMapping[j] = index; } } // Add speaker-pairs for (unsigned i = 1; i < numSpeakers; i++){ SpeakerTriple triple; triple.s1 = speakerMapping[i-1]; triple.s2 = speakerMapping[i]; triple.s3 = -1; triple.loadVectors(spkrs); addTriple(triple); } // Add the last speaker-pair SpeakerTriple triple; triple.s1 = speakerMapping[numSpeakers-1]; triple.s2 = speakerMapping[0]; triple.s3 = -1; triple.loadVectors(spkrs); addTriple(triple); } bool Vbap::isCrossing(Vec3d c, Vec3d li, Vec3d lj, Vec3d ln, Vec3d lm){ double thresh = 0.0001; double a1 = angle(c,li)+angle(c,lj); double a2 = angle(li,lj); double a3 = angle(c,ln)+angle(c,lm); double a4 = angle(ln,lm); return (fabs(a1-a2)< thresh) && (fabs(a3-a4)< thresh); } void Vbap::findSpeakerTriplets(const std::vector<Speaker>& spkrs){ std::list<SpeakerTriple> triplets; unsigned numSpeakers = spkrs.size(); int numSpeakersSigned = (int)numSpeakers; // form all possible triples for (unsigned i = 0; i < numSpeakers; i++){ for (unsigned j = i+1; j < numSpeakers; j++){ for (unsigned k = j+1; k < numSpeakers; k++){ SpeakerTriple triplet; triplet.s1=i; triplet.s2=j; triplet.s3=k; //Only add triplet if its matrix is invertable if(triplet.loadVectors(spkrs)){ triplets.push_back(triplet); } } } } printf("Speaker-count=%d, Initial triplet-count=%d\n",numSpeakers,(unsigned)triplets.size()); //RemoveTriangles that have equal elevation int equalElevCounter = 0; for(std::list<SpeakerTriple>::iterator it = triplets.begin(); it != triplets.end();){ SpeakerTriple trip = (*it); double a = trip.s1Vec[2]; double b = trip.s2Vec[2]; double c = trip.s3Vec[2]; if((a==b) && (a == c)){ it = triplets.erase(it); equalElevCounter++; }else{ ++it; } } printf("Tris removed because equal elev %i\n",equalElevCounter); //Remove Sides with equal elevation that have a speaker inbetween them std::list<SpeakerTriple>::iterator itA = triplets.begin(); int equalElevBtwCounter = 0; while(itA != triplets.end()){ bool breakOuter = false; SpeakerTriple trip = (*itA); int numSpeaks = 3; for(int i = 0 ;i < 3;i++){ int spkIdx1 = i%3; int spkIdx2 = (i+1)%3; if(trip.vec[spkIdx1].z != trip.vec[spkIdx2].z){ continue; } //Set z to 0 Vec3d vec1(trip.vec[spkIdx1].x,trip.vec[spkIdx1].y,0.f); Vec3d vec2(trip.vec[spkIdx2].x,trip.vec[spkIdx2].y,0.f); for(Speaker s: spkrs){ if(s.vec().z != trip.vec[spkIdx1].z){ continue; } if( trip.speakerChan[spkIdx1] == s.deviceChannel || trip.speakerChan[spkIdx2] == s.deviceChannel){ continue; } Vec3d spkVec(s.vec().x,s.vec().y,0.f); if( angle(vec1,vec2) > angle(vec1,spkVec) && angle(vec1,vec2) > angle(vec2,spkVec)){ itA = triplets.erase(itA); breakOuter = true; equalElevBtwCounter++; break; } } } if(breakOuter){ continue; } ++itA; } printf("Tris removed because equal elev with spk btw %i\n",equalElevBtwCounter); // remove too narrow triples std::list<SpeakerTriple>::iterator nit = triplets.begin(); int narrowCounter=0; while(nit != triplets.end()){ SpeakerTriple trip = (*nit); //Scalar triple product (a x b) dot c Vec3d a = trip.s1Vec.normalized(); Vec3d b = trip.s2Vec.normalized(); Vec3d c = trip.s3Vec.normalized(); Vec3d xprod = cross(a,b); float volume = fabs(xprod.dot(c)); float length = fabs(angle(a , b) ) + fabs(angle(a , c) ) + fabs(angle(b , c) ); float ratio; if (length > MIN_LENGTH){ ratio = volume / length; }else{ ratio = 0.0; } if (ratio < MIN_VOLUME_TO_LENGTH_RATIO) { nit =triplets.erase(nit); narrowCounter++; }else{ ++nit; } } printf("Triangles removed because too narrow %i\n",narrowCounter); //Remove triplet with longest side if crossing int crossCounter = -1; while(crossCounter != 0){ crossCounter=0; std::list<SpeakerTriple>::iterator it = triplets.begin(); while(it != triplets.end()){ bool breakOuter = false; SpeakerTriple trip = (*it); std::list<SpeakerTriple>::iterator it2 = triplets.begin(); while(it2 != triplets.end()){ bool breakInner = false; SpeakerTriple trip2 = (*it2); if((trip.s1 == trip2.s1) && (trip.s2 == trip2.s2) && (trip.s3== trip2.s3) ){ ++it2; continue; } for(int i = 0 ;i < 3;i++){ for(int j = 0; j < 3; j++){ int a = trip.speakerIdx[i%3]; int b = trip.speakerIdx[(i+1)%3]; int c = trip2.speakerIdx[j%3]; int d = trip2.speakerIdx[(j+1)%3]; //Check to see if the pairs have a speaker in common if((a==c)||(a==d) || (b==c)||(b==d)){ continue; } Vec3d li = trip.vec[i%3].normalized(); Vec3d lj = trip.vec[(i+1)%3].normalized(); Vec3d ln = trip2.vec[j%3].normalized(); Vec3d lm = trip2.vec[(j+1)%3].normalized(); Vec3d cr = cross(cross(li, lj),cross(ln,lm)); double lt = dist(trip.vec[i%3], trip.vec[(i+1)%3]); double lt2 =dist(trip2.vec[j%3],trip2.vec[(j+1)%3]); if (isCrossing(cr,li,lj,ln,lm) || isCrossing(-cr,li,lj,ln,lm)) { //TODO: how to handle the case where lt == lt2 if(lt > lt2){ it = triplets.erase(it); breakOuter = true; crossCounter++; }else if (lt < lt2){ it2 =triplets.erase(it2); breakInner = true; crossCounter++; }else{ // printf("EQUA1L Trip it %i %i %i, is equal %i %i %i lt=%f lt2=%f \n",trip.s1Chan,trip.s2Chan,trip.s3Chan,trip2.s1Chan,trip2.s2Chan,trip2.s3Chan, lt,lt2); } } if(breakInner || breakOuter){break;} } if(breakInner || breakOuter){break;} } if(breakInner || breakOuter){break;} ++it2; } if(breakOuter){continue;} ++it; } printf("Triangles removed because of crossing %i\n",crossCounter); } //Remove triplet if contains another speaker double thresh = 0.f; int spkInTri = 0; for(int i = 0; i < numSpeakersSigned; ++i){ Speaker s = spkrs[i]; Vec3d vec =s.vec().normalized(); int devChan = s.deviceChannel; std::list<SpeakerTriple>::iterator itg = triplets.begin(); while(itg != triplets.end()){ SpeakerTriple trip2 = (*itg); if ((devChan == trip2.s1Chan) || (devChan == trip2.s2Chan) || (devChan == trip2.s3Chan) ){ ++itg; continue; } Vec3d gains = computeGains(vec, trip2); //if ((gains[0] > 0) && (gains[1] > 0) && (gains[2] > 0) ){ if ((gains[0] > thresh) && (gains[1] > thresh) && (gains[2] > thresh) ){ itg = triplets.erase(itg); spkInTri++; }else{ ++itg; } } } printf("Tris removed because spk inside triangle %i\n",spkInTri); std::list<SpeakerTriple>::iterator it3 = triplets.begin(); while(it3 != triplets.end()) { addTriple(*it3); ++it3; } } void Vbap::compile(Listener& listener){ this->mListener = &listener; //Check if 3D... if(mIs3D){ printf("Finding triplets\n"); findSpeakerTriplets(mSpeakers); } else{ printf("Finding pairs\n"); findSpeakerPairs(mSpeakers); } if (mNumTriplets == 0 ){ printf("No SpeakerSets found. Check mode setting or speaker layout.\n"); throw -1; } } //Per buffer void Vbap::perform(AudioIOData& io,SoundSource& src,Vec3d& relpos,const int& numFrames,float *samples){ unsigned currentTripletIndex = src.cachedIndex(); // unsigned currentTripletIndex = mCachedTripletIndex; // Cached source placement, so it starts searching from there. Vec3d vec = Vec3d(relpos); //Rotate vector according to listener-rotation Quatd srcRot = this->mListener->pose().quat(); vec = srcRot.rotate(vec); //Silent by default Vec3d gains; Vec3d gainsTemp; // Search thru the triplets array in search of a match for the source position. for (unsigned count = 0; count < mNumTriplets; ++count) { gainsTemp = computeGains(vec, mTriplets[currentTripletIndex]); if ((gainsTemp[0] >= 0) && (gainsTemp[1] >= 0) && (!mIs3D || (gainsTemp[2] >= 0)) ){ gainsTemp.normalize(); gains = gainsTemp/relpos.mag(); SpeakerTriple triple = mTriplets[currentTripletIndex]; float * outBuff1 = io.outBuffer(triple.s1Chan); float * outBuff2 = io.outBuffer(triple.s2Chan); float * outBuff3 = io.outBuffer(triple.s3Chan); for(int i = 0; i < numFrames; ++i){ outBuff1[i] += samples[i]*gains[0]; outBuff2[i] += samples[i]*gains[1]; if(mIs3D){ outBuff3[i] += samples[i]*gains[2]; } } break; } ++currentTripletIndex; if (currentTripletIndex >= mNumTriplets){ currentTripletIndex = 0; } } src.cachedIndex(currentTripletIndex); //mCachedTripletIndex = currentTripletIndex; // Store the new index } //per sample void Vbap::perform(AudioIOData& io, SoundSource& src, Vec3d& relpos, const int& numFrames, int& frameIndex, float& sample){ unsigned currentTripletIndex = src.cachedIndex(); //unsigned currentTripletIndex = mCachedTripletIndex; // Cached source placement, so it starts searching from there. Vec3d vec = Vec3d(relpos); //Rotate vector according to listener-rotation Quatd srcRot = this->mListener->pose().quat(); vec = srcRot.rotate(vec); //Silent by default Vec3d gains; Vec3d gainsTemp; // Search thru the triplets array in search of a match for the source position. for (unsigned count = 0; count < mNumTriplets; ++count) { gainsTemp = computeGains(vec, mTriplets[currentTripletIndex]); if ((gainsTemp[0] >= 0) && (gainsTemp[1] >= 0) && (!mIs3D || (gainsTemp[2] >= 0)) ){ gainsTemp.normalize(); gains = gainsTemp*sample/relpos.mag(); break; } ++currentTripletIndex; if (currentTripletIndex >= mNumTriplets){ currentTripletIndex = 0; } } SpeakerTriple triple = mTriplets[currentTripletIndex]; //mCachedTripletIndex = currentTripletIndex; // Store the new index src.cachedIndex(currentTripletIndex); io.out(triple.s1Chan,frameIndex) += gains[0]; io.out(triple.s2Chan,frameIndex) += gains[1]; if(mIs3D){ io.out(triple.s3Chan, frameIndex) += gains[2]; } } void Vbap::print() { printf("Number of Triplets: %d\n",mTriplets.size()); // for (unsigned i = 0; i < mNumTriplets; i++) { for (unsigned i = 0; i < mTriplets.size(); i++) { printf("Triple #%d: %d,%d,%d \n",i,mTriplets[i].s1Chan,mTriplets[i].s2Chan,mTriplets[i].s3Chan); } } std::vector<SpeakerTriple> Vbap::triplets() const { return mTriplets; } } // al:: <|endoftext|>
<commit_before>#ifndef __STOUT_OS_READ_HPP__ #define __STOUT_OS_READ_HPP__ #include <stdio.h> #include <unistd.h> #include <stout/error.hpp> #include <stout/try.hpp> namespace os { // Reads 'size' bytes from a file from its current offset. // If EOF is encountered before reading size bytes, then the offset // is restored and none is returned. inline Result<std::string> read(int fd, size_t size) { // Save the current offset. off_t current = lseek(fd, 0, SEEK_CUR); if (current == -1) { return ErrnoError("Failed to lseek to SEEK_CUR"); } char* buffer = new char[size]; size_t offset = 0; while (offset < size) { ssize_t length = ::read(fd, buffer + offset, size - offset); if (length < 0) { // TODO(bmahler): Handle a non-blocking fd? (EAGAIN, EWOULDBLOCK) if (errno == EINTR) { continue; } // Attempt to restore the original offset. lseek(fd, current, SEEK_SET); return ErrnoError(); } else if (length == 0) { // Reached EOF before expected! Restore the offset. lseek(fd, current, SEEK_SET); return None(); } offset += length; } return std::string(buffer, size); } // Returns the contents of the file. inline Try<std::string> read(const std::string& path) { FILE* file = fopen(path.c_str(), "r"); if (file == NULL) { return ErrnoError("Failed to open file '" + path + "'"); } // Initially the 'line' is NULL and length 0, getline() allocates // ('malloc') a buffer for reading the line. // In subsequent iterations, if the buffer is not large enough to // hold the line, getline() resizes it with 'realloc' and updates // 'line' and 'length' as necessary. See: // - http://pubs.opengroup.org/onlinepubs/9699919799/functions/getline.html // - http://man7.org/linux/man-pages/man3/getline.3.html std::string result; char* line = NULL; size_t length = 0; ssize_t read; while ((read = getline(&line, &length, file)) != -1) { result.append(line, read); } // getline() requires the line buffer to be freed by the caller. free(line); if (ferror(file)) { ErrnoError error; // NOTE: We ignore the error from fclose(). This is because // users calling this function are interested in the return value // of read(). Also an unsuccessful fclose() does not affect the // read. fclose(file); return error; } fclose(file); return result; } } // namespace os { #endif // __STOUT_OS_READ_HPP__ <commit_msg>Fixed a memory leak in os::read().<commit_after>#ifndef __STOUT_OS_READ_HPP__ #define __STOUT_OS_READ_HPP__ #include <stdio.h> #include <unistd.h> #include <stout/error.hpp> #include <stout/try.hpp> namespace os { // Reads 'size' bytes from a file from its current offset. // If EOF is encountered before reading size bytes, then the offset // is restored and none is returned. inline Result<std::string> read(int fd, size_t size) { // Save the current offset. off_t current = lseek(fd, 0, SEEK_CUR); if (current == -1) { return ErrnoError("Failed to lseek to SEEK_CUR"); } char* buffer = new char[size]; size_t offset = 0; while (offset < size) { ssize_t length = ::read(fd, buffer + offset, size - offset); if (length < 0) { // TODO(bmahler): Handle a non-blocking fd? (EAGAIN, EWOULDBLOCK) if (errno == EINTR) { continue; } // Attempt to restore the original offset. lseek(fd, current, SEEK_SET); delete[] buffer; return ErrnoError(); } else if (length == 0) { // Reached EOF before expected! Restore the offset. lseek(fd, current, SEEK_SET); delete[] buffer; return None(); } offset += length; } std::string result = std::string(buffer, size); delete[] buffer; return result; } // Returns the contents of the file. inline Try<std::string> read(const std::string& path) { FILE* file = fopen(path.c_str(), "r"); if (file == NULL) { return ErrnoError("Failed to open file '" + path + "'"); } // Initially the 'line' is NULL and length 0, getline() allocates // ('malloc') a buffer for reading the line. // In subsequent iterations, if the buffer is not large enough to // hold the line, getline() resizes it with 'realloc' and updates // 'line' and 'length' as necessary. See: // - http://pubs.opengroup.org/onlinepubs/9699919799/functions/getline.html // - http://man7.org/linux/man-pages/man3/getline.3.html std::string result; char* line = NULL; size_t length = 0; ssize_t read; while ((read = getline(&line, &length, file)) != -1) { result.append(line, read); } // getline() requires the line buffer to be freed by the caller. free(line); if (ferror(file)) { ErrnoError error; // NOTE: We ignore the error from fclose(). This is because // users calling this function are interested in the return value // of read(). Also an unsuccessful fclose() does not affect the // read. fclose(file); return error; } fclose(file); return result; } } // namespace os { #endif // __STOUT_OS_READ_HPP__ <|endoftext|>
<commit_before>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/platform_thread.h" #include <errno.h> #include <sched.h> #if defined(OS_MACOSX) #include <mach/mach.h> #elif defined(OS_LINUX) #include <sys/syscall.h> #include <unistd.h> #endif static void* ThreadFunc(void* closure) { PlatformThread::Delegate* delegate = static_cast<PlatformThread::Delegate*>(closure); delegate->ThreadMain(); return NULL; } // static int PlatformThread::CurrentId() { // Pthreads doesn't have the concept of a thread ID, so we have to reach down // into the kernel. #if defined(OS_MACOSX) return mach_thread_self(); #elif defined(OS_LINUX) return syscall(__NR_gettid); #endif } // static void PlatformThread::YieldCurrentThread() { sched_yield(); } // static void PlatformThread::Sleep(int duration_ms) { struct timespec sleep_time, remaining; // Contains the portion of duration_ms >= 1 sec. sleep_time.tv_sec = duration_ms / 1000; duration_ms -= sleep_time.tv_sec * 1000; // Contains the portion of duration_ms < 1 sec. sleep_time.tv_nsec = duration_ms * 1000 * 1000; // nanoseconds. while (nanosleep(&sleep_time, &remaining) == -1 && errno == EINTR) sleep_time = remaining; } // static void PlatformThread::SetName(const char* name) { // TODO(darin): implement me! } // static bool PlatformThread::Create(size_t stack_size, Delegate* delegate, PlatformThreadHandle* thread_handle) { bool success = false; pthread_attr_t attributes; pthread_attr_init(&attributes); // Pthreads are joinable by default, so we don't need to specify any special // attributes to be able to call pthread_join later. if (stack_size > 0) pthread_attr_setstacksize(&attributes, stack_size); success = !pthread_create(thread_handle, &attributes, ThreadFunc, delegate); pthread_attr_destroy(&attributes); return success; } // static void PlatformThread::Join(PlatformThreadHandle thread_handle) { pthread_join(thread_handle, NULL); } <commit_msg>Updated comment in thread naming.<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/platform_thread.h" #include <errno.h> #include <sched.h> #if defined(OS_MACOSX) #include <mach/mach.h> #elif defined(OS_LINUX) #include <sys/syscall.h> #include <unistd.h> #endif static void* ThreadFunc(void* closure) { PlatformThread::Delegate* delegate = static_cast<PlatformThread::Delegate*>(closure); delegate->ThreadMain(); return NULL; } // static int PlatformThread::CurrentId() { // Pthreads doesn't have the concept of a thread ID, so we have to reach down // into the kernel. #if defined(OS_MACOSX) return mach_thread_self(); #elif defined(OS_LINUX) return syscall(__NR_gettid); #endif } // static void PlatformThread::YieldCurrentThread() { sched_yield(); } // static void PlatformThread::Sleep(int duration_ms) { struct timespec sleep_time, remaining; // Contains the portion of duration_ms >= 1 sec. sleep_time.tv_sec = duration_ms / 1000; duration_ms -= sleep_time.tv_sec * 1000; // Contains the portion of duration_ms < 1 sec. sleep_time.tv_nsec = duration_ms * 1000 * 1000; // nanoseconds. while (nanosleep(&sleep_time, &remaining) == -1 && errno == EINTR) sleep_time = remaining; } // static void PlatformThread::SetName(const char* name) { // The POSIX standard does not provide for naming threads, and neither Linux // nor Mac OS X (our two POSIX targets) provide any non-portable way of doing // it either. (Some BSDs provide pthread_set_name_np but that isn't much of a // consolation prize.) // TODO(darin): decide whether stuffing the name in TLS or other in-memory // structure would be useful for debugging or not. } // static bool PlatformThread::Create(size_t stack_size, Delegate* delegate, PlatformThreadHandle* thread_handle) { bool success = false; pthread_attr_t attributes; pthread_attr_init(&attributes); // Pthreads are joinable by default, so we don't need to specify any special // attributes to be able to call pthread_join later. if (stack_size > 0) pthread_attr_setstacksize(&attributes, stack_size); success = !pthread_create(thread_handle, &attributes, ThreadFunc, delegate); pthread_attr_destroy(&attributes); return success; } // static void PlatformThread::Join(PlatformThreadHandle thread_handle) { pthread_join(thread_handle, NULL); } <|endoftext|>
<commit_before><commit_msg>Basic: scanner should'nt use 0xFF mask on characters<commit_after><|endoftext|>
<commit_before>#include "StdInc.h" #include <ServerInstanceBase.h> #include <HttpServerManager.h> #include <GameServer.h> #include <ResourceManager.h> #include <VFSManager.h> #include <botan/base64.h> #include <json.hpp> #include <fs_utils.h> using json = nlohmann::json; static InitFunction initFunction([]() { fx::ServerInstanceBase::OnServerCreate.Connect([](fx::ServerInstanceBase *instance) { // TODO: make instanceable static auto instanceRef = instance; static auto ivVar = instance->AddVariable<int>("sv_infoVersion", ConVar_ServerInfo, 0); static auto maxClientsVar = instance->AddVariable<int>("sv_maxClients", ConVar_ServerInfo, 30); auto epPrivacy = instance->AddVariable<bool>("sv_endpointPrivacy", ConVar_None, false); // max clients cap maxClientsVar->GetHelper()->SetConstraints(1, 32); struct InfoData { json infoJson; int infoHash; InfoData() : infoHash(0), infoJson({ { "server", "FXServer-pre" },{ "enhancedHostSupport", true },{ "resources",{} } }) { Update(); } void Update() { auto varman = instanceRef->GetComponent<console::Context>()->GetVariableManager(); infoJson["vars"] = json::object(); varman->ForAllVariables([&](const std::string& name, int flags, const std::shared_ptr<internal::ConsoleVariableEntryBase>& var) { // don't return more variable information if (name == "sv_infoVersion" || name == "sv_hostname") { return; } infoJson["vars"][name] = var->GetValue(); }, ConVar_ServerInfo); infoJson["version"] = 0; infoHash = static_cast<int>(std::hash<std::string>()(infoJson.dump()) & 0x7FFFFFFF); infoJson["version"] = infoHash; infoJson["resources"] = json::object(); infoJson["resources"]["hardcap"] = json::object(); auto resman = instanceRef->GetComponent<fx::ResourceManager>(); resman->ForAllResources([&](fwRefContainer<fx::Resource> resource) { // we've already listed hardcap, no need to actually return it again if (resource->GetName() == "hardcap") { return; } //if (resource->GetState == fx::ResourceState::) infoJson["resources"][resource->GetName()] = json::object(); char* state = fs::StateToString(resource); infoJson["resources"][resource->GetName()]["state"] = (state); }); ivVar->GetHelper()->SetRawValue(infoHash); } }; static auto infoData = std::make_shared<InfoData>(); instance->GetComponent<fx::HttpServerManager>()->AddEndpoint("/fsdata", [=](const fwRefContainer<net::HttpRequest>& request, const fwRefContainer<net::HttpResponse>& response) { auto auth = request->GetHeader("auth"); auto rcon_password = instance->GetComponent<fx::GameServer>()->GetRconPassword(); trace(rcon_password.c_str(),"fivem-web"); if(auth.compare(rcon_password)){ response->SetStatusCode(403); response->Write(""); response->End(); } else { infoData->Update(); response->End(infoData->infoJson.dump()); } }); instance->GetComponent<fx::HttpServerManager>()->AddEndpoint("/fsdata", [](const fwRefContainer<net::HttpRequest>&request, const fwRefContainer<net::HttpResponse>& response) { if (request->GetRequestMethod() == "POST") { } }); }, 1500); } );<commit_msg>added http Basic Autb<commit_after>#include "StdInc.h" #include <ServerInstanceBase.h> #include <HttpServerManager.h> #include <GameServer.h> #include <ResourceManager.h> #include <VFSManager.h> #include <botan\bcrypt.h> #include <base64.h> #include <json.hpp> #include <fs_utils.h> using json = nlohmann::json; bool isAuthed(fwRefContainer<net::HttpRequest> const request, fwRefContainer<net::HttpResponse> const response, std::string rcon_password); static InitFunction initFunction([]() { fx::ServerInstanceBase::OnServerCreate.Connect([](fx::ServerInstanceBase *instance) { // TODO: make instanceable static auto instanceRef = instance; static auto ivVar = instance->AddVariable<int>("sv_infoVersion", ConVar_ServerInfo, 0); static auto maxClientsVar = instance->AddVariable<int>("sv_maxClients", ConVar_ServerInfo, 30); auto epPrivacy = instance->AddVariable<bool>("sv_endpointPrivacy", ConVar_None, false); // max clients cap maxClientsVar->GetHelper()->SetConstraints(1, 32); struct InfoData { json infoJson; int infoHash; InfoData() : infoHash(0), infoJson({ { "server", "FXServer-pre" },{ "enhancedHostSupport", true },{ "resources",{} } }) { Update(); } void Update() { auto varman = instanceRef->GetComponent<console::Context>()->GetVariableManager(); infoJson["vars"] = json::object(); varman->ForAllVariables([&](const std::string& name, int flags, const std::shared_ptr<internal::ConsoleVariableEntryBase>& var) { // don't return more variable information if (name == "sv_infoVersion" || name == "sv_hostname") { return; } infoJson["vars"][name] = var->GetValue(); }, ConVar_ServerInfo); infoJson["version"] = 0; infoHash = static_cast<int>(std::hash<std::string>()(infoJson.dump()) & 0x7FFFFFFF); infoJson["version"] = infoHash; infoJson["resources"] = json::object(); infoJson["resources"]["hardcap"] = json::object(); auto resman = instanceRef->GetComponent<fx::ResourceManager>(); resman->ForAllResources([&](fwRefContainer<fx::Resource> resource) { // we've already listed hardcap, no need to actually return it again if (resource->GetName() == "hardcap") { return; } //if (resource->GetState == fx::ResourceState::) infoJson["resources"][resource->GetName()] = json::object(); char* state = fs::StateToString(resource); infoJson["resources"][resource->GetName()]["state"] = (state); }); ivVar->GetHelper()->SetRawValue(infoHash); } }; static auto infoData = std::make_shared<InfoData>(); instance->GetComponent<fx::HttpServerManager>()->AddEndpoint("/fsdata", [=](const fwRefContainer<net::HttpRequest>& request, const fwRefContainer<net::HttpResponse>& response) { auto rcon_password = instance->GetComponent<fx::GameServer>()->GetRconPassword(); if (isAuthed(request, response, rcon_password)) { infoData->Update(); response->End(infoData->infoJson.dump()); } }); instance->GetComponent<fx::HttpServerManager>()->AddEndpoint("/fsdata", [](const fwRefContainer<net::HttpRequest>&request, const fwRefContainer<net::HttpResponse>& response) { if (request->GetRequestMethod() == "POST") { } }); }, 1500); } ); bool isAuthed(fwRefContainer<net::HttpRequest> const request, fwRefContainer<net::HttpResponse> const response, std::string rcon_password) { if (request->GetHeader("Authorization") == std::string()) { response->SetStatusCode(401); response->SetHeader("WWW-Authenticate", "BASIC realm=\"hdhdn\""); response->Write(""); response->End(); return false; } else if (request->GetHeader("Authorization").length() > 0) { auto auth = request->GetHeader("Authorization"); std::string srvpass("Basic "); auto const pass = ":" + rcon_password; auto buf_sz = size_t(); auto const buf_ptr = base64_encode (reinterpret_cast<const unsigned char*>(pass.c_str()) , pass.size() , &buf_sz ); srvpass.append(buf_ptr, buf_ptr + buf_sz); free(buf_ptr); if (!srvpass.compare(auth)) { return true; } else { response->SetStatusCode(403); response->End(""); return false; } } }<|endoftext|>
<commit_before>/* * %CopyrightBegin% * * Copyright Ericsson AB 2020-2021. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * %CopyrightEnd% */ #include <algorithm> #include <float.h> #include "beam_asm.hpp" using namespace asmjit; #ifdef BEAMASM_DUMP_SIZES # include <mutex> typedef std::pair<Uint64, Uint64> op_stats; static std::unordered_map<char *, op_stats> sizes; static std::mutex size_lock; extern "C" void beamasm_dump_sizes() { std::lock_guard<std::mutex> lock(size_lock); std::vector<std::pair<char *, op_stats>> flat(sizes.cbegin(), sizes.cend()); double total_size = 0.0; for (const auto &op : flat) { total_size += op.second.second; } /* Sort instructions by total size, in descending order. */ std::sort( flat.begin(), flat.end(), [](std::pair<char *, op_stats> &a, std::pair<char *, op_stats> &b) { return a.second.second > b.second.second; }); for (const auto &op : flat) { fprintf(stderr, "%34s:\t%zu\t%f\t%zu\t%zu\r\n", op.first, op.second.second, op.second.second / total_size, op.second.first, op.second.first ? (op.second.second / op.second.first) : 0); } } #endif ErtsCodePtr BeamModuleAssembler::getCode(BeamLabel label) { ASSERT(label < rawLabels.size() + 1); return (ErtsCodePtr)getCode(rawLabels[label]); } ErtsCodePtr BeamModuleAssembler::getLambda(unsigned index) { const auto &lambda = lambdas[index]; return (ErtsCodePtr)getCode(lambda.trampoline); } BeamModuleAssembler::BeamModuleAssembler(BeamGlobalAssembler *ga, Eterm mod, int num_labels, int num_functions, const BeamFile *file) : BeamModuleAssembler(ga, mod, num_labels, file) { codeHeader = a.newLabel(); a.align(kAlignCode, 8); a.bind(codeHeader); embed_zeros(sizeof(BeamCodeHeader) + sizeof(ErtsCodeInfo *) * num_functions); /* Shared trampoline for function_clause errors, which can't jump straight * to `i_func_info_shared` due to size restrictions. */ funcInfo = a.newLabel(); a.align(kAlignCode, 8); a.bind(funcInfo); abs_jmp(ga->get_i_func_info_shared()); /* Shared trampoline for yielding on function ingress. */ yieldEnter = a.newLabel(); a.align(kAlignCode, 8); a.bind(yieldEnter); abs_jmp(ga->get_i_test_yield_shared()); /* Shared trampoline for yielding on function return. */ yieldReturn = a.newLabel(); a.align(kAlignCode, 8); a.bind(yieldReturn); abs_jmp(ga->get_dispatch_return()); /* Setup the early_nif/breakpoint trampoline. */ genericBPTramp = a.newLabel(); a.align(kAlignCode, 16); a.bind(genericBPTramp); { a.ret(); a.align(kAlignCode, 16); ASSERT(a.offset() - code.labelOffsetFromBase(genericBPTramp) == 16 * 1); abs_jmp(ga->get_call_nif_early()); a.align(kAlignCode, 16); ASSERT(a.offset() - code.labelOffsetFromBase(genericBPTramp) == 16 * 2); aligned_call(ga->get_generic_bp_local()); a.ret(); a.align(kAlignCode, 16); ASSERT(a.offset() - code.labelOffsetFromBase(genericBPTramp) == 16 * 3); aligned_call(ga->get_generic_bp_local()); abs_jmp(ga->get_call_nif_early()); } } Label BeamModuleAssembler::embed_vararg_rodata(const Span<ArgVal> &args, int y_offset) { Label label = a.newLabel(); #if !defined(NATIVE_ERLANG_STACK) y_offset = CP_SIZE; #endif a.section(rodata); a.bind(label); for (const ArgVal &arg : args) { union { BeamInstr as_beam; char as_char[1]; } data; a.align(kAlignData, 8); switch (arg.getType()) { case ArgVal::XReg: data.as_beam = make_loader_x_reg(arg.getValue()); a.embed(&data.as_char, sizeof(data.as_beam)); break; case ArgVal::YReg: data.as_beam = make_loader_y_reg(arg.getValue() + y_offset); a.embed(&data.as_char, sizeof(data.as_beam)); break; case ArgVal::Literal: make_word_patch(literals[arg.getValue()].patches); break; case ArgVal::Label: a.embedLabel(resolve_beam_label(arg)); break; case ArgVal::Immediate: case ArgVal::Word: data.as_beam = arg.getValue(); a.embed(&data.as_char, sizeof(data.as_beam)); break; default: erts_fprintf(stderr, "tag: %li\n", arg.getType()); ERTS_ASSERT(!"error"); } } a.section(code.textSection()); return label; } void BeamModuleAssembler::emit_i_nif_padding() { const size_t minimum_size = sizeof(UWord[BEAM_NATIVE_MIN_FUNC_SZ]); size_t prev_func_start, diff; prev_func_start = code.labelOffsetFromBase(rawLabels[functions.back() + 1]); diff = a.offset() - prev_func_start; if (diff < minimum_size) { embed_zeros(minimum_size - diff); } } void BeamModuleAssembler::emit_i_breakpoint_trampoline() { /* This little prologue is used by nif loading and tracing to insert * alternative instructions. The call is filled with a relative call to a * trampoline in the module header and then the jmp target is zeroed so that * it effectively becomes a nop */ Label next = a.newLabel(); a.short_().jmp(next); /* We embed a zero byte here, which is used to flag whether to make an early * nif call, call a breakpoint handler, or both. */ a.embedUInt8(ERTS_ASM_BP_FLAG_NONE); if (genericBPTramp.isValid()) { a.call(genericBPTramp); } else { /* NIF or BIF stub; we're not going to use this trampoline as-is, but * we need to reserve space for it. */ a.ud2(); } a.align(kAlignCode, 8); a.bind(next); ASSERT((a.offset() - code.labelOffsetFromBase(currLabel)) == BEAM_ASM_FUNC_PROLOGUE_SIZE); } static void i_emit_nyi(char *msg) { erts_exit(ERTS_ERROR_EXIT, "NYI: %s\n", msg); } void BeamModuleAssembler::emit_nyi(const char *msg) { emit_enter_runtime(); a.mov(ARG1, imm(msg)); runtime_call<1>(i_emit_nyi); /* Never returns */ } void BeamModuleAssembler::emit_nyi() { emit_nyi("<unspecified>"); } bool BeamModuleAssembler::emit(unsigned specific_op, const Span<ArgVal> &args) { comment(opc[specific_op].name); #ifdef BEAMASM_DUMP_SIZES uint64_t before = a.offset(); #endif #define InstrCnt() switch (specific_op) { #include "beamasm_emit.h" default: ERTS_ASSERT(0 && "Invalid instruction"); break; } if (getOffset() == last_error_offset) { /* * The previous PC where an exception may occur is equal to the * current offset, which is also the offset of the next * instruction. If the next instruction happens to be a * line instruction, the location for the exception will * be that line instruction, which is probably wrong. * To avoid that, bump the instruction offset. */ a.nop(); } #ifdef BEAMASM_DUMP_SIZES { std::lock_guard<std::mutex> lock(size_lock); sizes[opc[specific_op].name].first++; sizes[opc[specific_op].name].second += a.offset() - before; } #endif return true; } /* * Here follows meta instructions. */ void BeamGlobalAssembler::emit_i_func_info_shared() { /* Pop the ErtsCodeInfo address into ARG1 and mask out the offset added by * the call instruction. */ a.pop(ARG1); a.and_(ARG1, ~0x7); a.lea(ARG1, x86::qword_ptr(ARG1, offsetof(ErtsCodeInfo, mfa))); a.mov(x86::qword_ptr(c_p, offsetof(Process, freason)), EXC_FUNCTION_CLAUSE); a.mov(x86::qword_ptr(c_p, offsetof(Process, current)), ARG1); mov_imm(ARG2, 0); mov_imm(ARG4, 0); a.jmp(labels[raise_exception_shared]); } void BeamModuleAssembler::emit_i_func_info(const ArgVal &Label, const ArgVal &Module, const ArgVal &Function, const ArgVal &Arity) { ErtsCodeInfo info; functions.push_back(Label.getValue()); info.mfa.module = Module.getValue(); info.mfa.function = Function.getValue(); info.mfa.arity = Arity.getValue(); info.u.gen_bp = NULL; comment("%T:%T/%d", info.mfa.module, info.mfa.function, info.mfa.arity); /* This is an ErtsCodeInfo structure that has a valid x86 opcode as its `op` * field, which *calls* the funcInfo trampoline so we can trace it back to * this particular function. * * We make a relative call to a trampoline in the module header because this * needs to fit into a word, and an directly call to `i_func_info_shared` * would be too large. */ if (funcInfo.isValid()) { a.call(funcInfo); } else { a.nop(); } a.align(kAlignCode, sizeof(UWord)); a.embed(&info.u.gen_bp, sizeof(info.u.gen_bp)); a.embed(&info.mfa, sizeof(info.mfa)); } void BeamModuleAssembler::emit_label(const ArgVal &Label) { ASSERT(Label.isLabel()); currLabel = rawLabels[Label.getValue()]; a.bind(currLabel); } void BeamModuleAssembler::emit_aligned_label(const ArgVal &Label, const ArgVal &Alignment) { ASSERT(Alignment.isWord()); a.align(kAlignCode, Alignment.getValue()); emit_label(Label); } void BeamModuleAssembler::emit_on_load() { on_load = currLabel; } void BeamModuleAssembler::emit_int_code_end() { /* This label is used to figure out the end of the last function */ code_end = a.newLabel(); a.bind(code_end); emit_nyi("int_code_end"); } void BeamModuleAssembler::emit_line(const ArgVal &) { /* * There is no need to align the line instruction. In the loaded * code, the type of the pointer will be void* and that pointer * will only be used in comparisons. */ } void BeamModuleAssembler::emit_func_line(const ArgVal &Loc) { emit_line(Loc); } void BeamModuleAssembler::emit_empty_func_line() { } /* * Here follows stubs for instructions that should never be called. */ void BeamModuleAssembler::emit_i_debug_breakpoint() { emit_nyi("i_debug_breakpoint should never be called"); } void BeamModuleAssembler::emit_i_generic_breakpoint() { emit_nyi("i_generic_breakpoint should never be called"); } void BeamModuleAssembler::emit_trace_jump(const ArgVal &) { emit_nyi("trace_jump should never be called"); } void BeamModuleAssembler::emit_call_error_handler() { emit_nyi("call_error_handler should never be called"); } unsigned BeamModuleAssembler::patchCatches(char *rw_base) { unsigned catch_no = BEAM_CATCHES_NIL; for (const auto &c : catches) { const auto &patch = c.patch; ErtsCodePtr handler; handler = (ErtsCodePtr)getCode(c.handler); catch_no = beam_catches_cons(handler, catch_no, nullptr); /* Patch the `mov` instruction with the catch tag */ auto offset = code.labelOffsetFromBase(patch.where); auto where = (unsigned *)&rw_base[offset + patch.ptr_offs]; ASSERT(0x7fffffff == *where); Eterm catch_term = make_catch(catch_no); /* With the current tag scheme, more than 33 million * catches can exist at once. */ ERTS_ASSERT(catch_term >> 31 == 0); *where = (unsigned)catch_term; } return catch_no; } void BeamModuleAssembler::patchImport(char *rw_base, unsigned index, BeamInstr I) { for (const auto &patch : imports[index].patches) { auto offset = code.labelOffsetFromBase(patch.where); auto where = (Eterm *)&rw_base[offset + patch.ptr_offs]; ASSERT(LLONG_MAX == *where); *where = I + patch.val_offs; } } void BeamModuleAssembler::patchLambda(char *rw_base, unsigned index, BeamInstr I) { for (const auto &patch : lambdas[index].patches) { auto offset = code.labelOffsetFromBase(patch.where); auto where = (Eterm *)&rw_base[offset + patch.ptr_offs]; ASSERT(LLONG_MAX == *where); *where = I + patch.val_offs; } } void BeamModuleAssembler::patchLiteral(char *rw_base, unsigned index, Eterm lit) { for (const auto &patch : literals[index].patches) { auto offset = code.labelOffsetFromBase(patch.where); auto where = (Eterm *)&rw_base[offset + patch.ptr_offs]; ASSERT(LLONG_MAX == *where); *where = lit + patch.val_offs; } } void BeamModuleAssembler::patchStrings(char *rw_base, const byte *string_table) { for (const auto &patch : strings) { auto offset = code.labelOffsetFromBase(patch.where); auto where = (const byte **)&rw_base[offset + 2]; ASSERT(LLONG_MAX == (Eterm)*where); *where = string_table + patch.val_offs; } } <commit_msg>jit: Clean up func_info<commit_after>/* * %CopyrightBegin% * * Copyright Ericsson AB 2020-2021. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * %CopyrightEnd% */ #include <algorithm> #include <float.h> #include "beam_asm.hpp" using namespace asmjit; #ifdef BEAMASM_DUMP_SIZES # include <mutex> typedef std::pair<Uint64, Uint64> op_stats; static std::unordered_map<char *, op_stats> sizes; static std::mutex size_lock; extern "C" void beamasm_dump_sizes() { std::lock_guard<std::mutex> lock(size_lock); std::vector<std::pair<char *, op_stats>> flat(sizes.cbegin(), sizes.cend()); double total_size = 0.0; for (const auto &op : flat) { total_size += op.second.second; } /* Sort instructions by total size, in descending order. */ std::sort( flat.begin(), flat.end(), [](std::pair<char *, op_stats> &a, std::pair<char *, op_stats> &b) { return a.second.second > b.second.second; }); for (const auto &op : flat) { fprintf(stderr, "%34s:\t%zu\t%f\t%zu\t%zu\r\n", op.first, op.second.second, op.second.second / total_size, op.second.first, op.second.first ? (op.second.second / op.second.first) : 0); } } #endif ErtsCodePtr BeamModuleAssembler::getCode(BeamLabel label) { ASSERT(label < rawLabels.size() + 1); return (ErtsCodePtr)getCode(rawLabels[label]); } ErtsCodePtr BeamModuleAssembler::getLambda(unsigned index) { const auto &lambda = lambdas[index]; return (ErtsCodePtr)getCode(lambda.trampoline); } BeamModuleAssembler::BeamModuleAssembler(BeamGlobalAssembler *ga, Eterm mod, int num_labels, int num_functions, const BeamFile *file) : BeamModuleAssembler(ga, mod, num_labels, file) { codeHeader = a.newLabel(); a.align(kAlignCode, 8); a.bind(codeHeader); embed_zeros(sizeof(BeamCodeHeader) + sizeof(ErtsCodeInfo *) * num_functions); /* Shared trampoline for function_clause errors, which can't jump straight * to `i_func_info_shared` due to size restrictions. */ funcInfo = a.newLabel(); a.align(kAlignCode, 8); a.bind(funcInfo); abs_jmp(ga->get_i_func_info_shared()); /* Shared trampoline for yielding on function ingress. */ yieldEnter = a.newLabel(); a.align(kAlignCode, 8); a.bind(yieldEnter); abs_jmp(ga->get_i_test_yield_shared()); /* Shared trampoline for yielding on function return. */ yieldReturn = a.newLabel(); a.align(kAlignCode, 8); a.bind(yieldReturn); abs_jmp(ga->get_dispatch_return()); /* Setup the early_nif/breakpoint trampoline. */ genericBPTramp = a.newLabel(); a.align(kAlignCode, 16); a.bind(genericBPTramp); { a.ret(); a.align(kAlignCode, 16); ASSERT(a.offset() - code.labelOffsetFromBase(genericBPTramp) == 16 * 1); abs_jmp(ga->get_call_nif_early()); a.align(kAlignCode, 16); ASSERT(a.offset() - code.labelOffsetFromBase(genericBPTramp) == 16 * 2); aligned_call(ga->get_generic_bp_local()); a.ret(); a.align(kAlignCode, 16); ASSERT(a.offset() - code.labelOffsetFromBase(genericBPTramp) == 16 * 3); aligned_call(ga->get_generic_bp_local()); abs_jmp(ga->get_call_nif_early()); } } Label BeamModuleAssembler::embed_vararg_rodata(const Span<ArgVal> &args, int y_offset) { Label label = a.newLabel(); #if !defined(NATIVE_ERLANG_STACK) y_offset = CP_SIZE; #endif a.section(rodata); a.bind(label); for (const ArgVal &arg : args) { union { BeamInstr as_beam; char as_char[1]; } data; a.align(kAlignData, 8); switch (arg.getType()) { case ArgVal::XReg: data.as_beam = make_loader_x_reg(arg.getValue()); a.embed(&data.as_char, sizeof(data.as_beam)); break; case ArgVal::YReg: data.as_beam = make_loader_y_reg(arg.getValue() + y_offset); a.embed(&data.as_char, sizeof(data.as_beam)); break; case ArgVal::Literal: make_word_patch(literals[arg.getValue()].patches); break; case ArgVal::Label: a.embedLabel(resolve_beam_label(arg)); break; case ArgVal::Immediate: case ArgVal::Word: data.as_beam = arg.getValue(); a.embed(&data.as_char, sizeof(data.as_beam)); break; default: erts_fprintf(stderr, "tag: %li\n", arg.getType()); ERTS_ASSERT(!"error"); } } a.section(code.textSection()); return label; } void BeamModuleAssembler::emit_i_nif_padding() { const size_t minimum_size = sizeof(UWord[BEAM_NATIVE_MIN_FUNC_SZ]); size_t prev_func_start, diff; prev_func_start = code.labelOffsetFromBase(rawLabels[functions.back() + 1]); diff = a.offset() - prev_func_start; if (diff < minimum_size) { embed_zeros(minimum_size - diff); } } void BeamModuleAssembler::emit_i_breakpoint_trampoline() { /* This little prologue is used by nif loading and tracing to insert * alternative instructions. The call is filled with a relative call to a * trampoline in the module header and then the jmp target is zeroed so that * it effectively becomes a nop */ Label next = a.newLabel(); a.short_().jmp(next); /* We embed a zero byte here, which is used to flag whether to make an early * nif call, call a breakpoint handler, or both. */ a.embedUInt8(ERTS_ASM_BP_FLAG_NONE); if (genericBPTramp.isValid()) { a.call(genericBPTramp); } else { /* NIF or BIF stub; we're not going to use this trampoline as-is, but * we need to reserve space for it. */ a.ud2(); } a.align(kAlignCode, 8); a.bind(next); ASSERT((a.offset() - code.labelOffsetFromBase(currLabel)) == BEAM_ASM_FUNC_PROLOGUE_SIZE); } static void i_emit_nyi(char *msg) { erts_exit(ERTS_ERROR_EXIT, "NYI: %s\n", msg); } void BeamModuleAssembler::emit_nyi(const char *msg) { emit_enter_runtime(); a.mov(ARG1, imm(msg)); runtime_call<1>(i_emit_nyi); /* Never returns */ } void BeamModuleAssembler::emit_nyi() { emit_nyi("<unspecified>"); } bool BeamModuleAssembler::emit(unsigned specific_op, const Span<ArgVal> &args) { comment(opc[specific_op].name); #ifdef BEAMASM_DUMP_SIZES uint64_t before = a.offset(); #endif #define InstrCnt() switch (specific_op) { #include "beamasm_emit.h" default: ERTS_ASSERT(0 && "Invalid instruction"); break; } if (getOffset() == last_error_offset) { /* * The previous PC where an exception may occur is equal to the * current offset, which is also the offset of the next * instruction. If the next instruction happens to be a * line instruction, the location for the exception will * be that line instruction, which is probably wrong. * To avoid that, bump the instruction offset. */ a.nop(); } #ifdef BEAMASM_DUMP_SIZES { std::lock_guard<std::mutex> lock(size_lock); sizes[opc[specific_op].name].first++; sizes[opc[specific_op].name].second += a.offset() - before; } #endif return true; } /* * Here follows meta instructions. */ void BeamGlobalAssembler::emit_i_func_info_shared() { /* Pop the ErtsCodeInfo address into ARG1 and mask out the offset added by * the call instruction. */ a.pop(ARG1); a.and_(ARG1, imm(~0x7)); a.add(ARG1, imm(offsetof(ErtsCodeInfo, mfa))); a.mov(x86::qword_ptr(c_p, offsetof(Process, freason)), EXC_FUNCTION_CLAUSE); a.mov(x86::qword_ptr(c_p, offsetof(Process, current)), ARG1); mov_imm(ARG2, 0); mov_imm(ARG4, 0); a.jmp(labels[raise_exception_shared]); } void BeamModuleAssembler::emit_i_func_info(const ArgVal &Label, const ArgVal &Module, const ArgVal &Function, const ArgVal &Arity) { ErtsCodeInfo info; functions.push_back(Label.getValue()); info.mfa.module = Module.getValue(); info.mfa.function = Function.getValue(); info.mfa.arity = Arity.getValue(); info.u.gen_bp = NULL; comment("%T:%T/%d", info.mfa.module, info.mfa.function, info.mfa.arity); /* This is an ErtsCodeInfo structure that has a valid x86 opcode as its `op` * field, which *calls* the funcInfo trampoline so we can trace it back to * this particular function. * * We make a relative call to a trampoline in the module header because this * needs to fit into a word, and an directly call to `i_func_info_shared` * would be too large. */ if (funcInfo.isValid()) { a.call(funcInfo); } else { a.nop(); } a.align(kAlignCode, sizeof(UWord)); a.embed(&info.u.gen_bp, sizeof(info.u.gen_bp)); a.embed(&info.mfa, sizeof(info.mfa)); } void BeamModuleAssembler::emit_label(const ArgVal &Label) { ASSERT(Label.isLabel()); currLabel = rawLabels[Label.getValue()]; a.bind(currLabel); } void BeamModuleAssembler::emit_aligned_label(const ArgVal &Label, const ArgVal &Alignment) { ASSERT(Alignment.isWord()); a.align(kAlignCode, Alignment.getValue()); emit_label(Label); } void BeamModuleAssembler::emit_on_load() { on_load = currLabel; } void BeamModuleAssembler::emit_int_code_end() { /* This label is used to figure out the end of the last function */ code_end = a.newLabel(); a.bind(code_end); emit_nyi("int_code_end"); } void BeamModuleAssembler::emit_line(const ArgVal &) { /* * There is no need to align the line instruction. In the loaded * code, the type of the pointer will be void* and that pointer * will only be used in comparisons. */ } void BeamModuleAssembler::emit_func_line(const ArgVal &Loc) { emit_line(Loc); } void BeamModuleAssembler::emit_empty_func_line() { } /* * Here follows stubs for instructions that should never be called. */ void BeamModuleAssembler::emit_i_debug_breakpoint() { emit_nyi("i_debug_breakpoint should never be called"); } void BeamModuleAssembler::emit_i_generic_breakpoint() { emit_nyi("i_generic_breakpoint should never be called"); } void BeamModuleAssembler::emit_trace_jump(const ArgVal &) { emit_nyi("trace_jump should never be called"); } void BeamModuleAssembler::emit_call_error_handler() { emit_nyi("call_error_handler should never be called"); } unsigned BeamModuleAssembler::patchCatches(char *rw_base) { unsigned catch_no = BEAM_CATCHES_NIL; for (const auto &c : catches) { const auto &patch = c.patch; ErtsCodePtr handler; handler = (ErtsCodePtr)getCode(c.handler); catch_no = beam_catches_cons(handler, catch_no, nullptr); /* Patch the `mov` instruction with the catch tag */ auto offset = code.labelOffsetFromBase(patch.where); auto where = (unsigned *)&rw_base[offset + patch.ptr_offs]; ASSERT(0x7fffffff == *where); Eterm catch_term = make_catch(catch_no); /* With the current tag scheme, more than 33 million * catches can exist at once. */ ERTS_ASSERT(catch_term >> 31 == 0); *where = (unsigned)catch_term; } return catch_no; } void BeamModuleAssembler::patchImport(char *rw_base, unsigned index, BeamInstr I) { for (const auto &patch : imports[index].patches) { auto offset = code.labelOffsetFromBase(patch.where); auto where = (Eterm *)&rw_base[offset + patch.ptr_offs]; ASSERT(LLONG_MAX == *where); *where = I + patch.val_offs; } } void BeamModuleAssembler::patchLambda(char *rw_base, unsigned index, BeamInstr I) { for (const auto &patch : lambdas[index].patches) { auto offset = code.labelOffsetFromBase(patch.where); auto where = (Eterm *)&rw_base[offset + patch.ptr_offs]; ASSERT(LLONG_MAX == *where); *where = I + patch.val_offs; } } void BeamModuleAssembler::patchLiteral(char *rw_base, unsigned index, Eterm lit) { for (const auto &patch : literals[index].patches) { auto offset = code.labelOffsetFromBase(patch.where); auto where = (Eterm *)&rw_base[offset + patch.ptr_offs]; ASSERT(LLONG_MAX == *where); *where = lit + patch.val_offs; } } void BeamModuleAssembler::patchStrings(char *rw_base, const byte *string_table) { for (const auto &patch : strings) { auto offset = code.labelOffsetFromBase(patch.where); auto where = (const byte **)&rw_base[offset + 2]; ASSERT(LLONG_MAX == (Eterm)*where); *where = string_table + patch.val_offs; } } <|endoftext|>
<commit_before>#include "configure.hpp" #include <silicium/file_operations.hpp> #include <silicium/cmake.hpp> #include <fstream> namespace { Si::absolute_path build_configure( Si::absolute_path const &application_source, Si::absolute_path const &temporary, Si::optional<Si::absolute_path> const &boost_root, Si::Sink<char, Si::success>::interface &output) { Si::absolute_path const cdm = Si::parent( Si::parent(*Si::absolute_path::create(__FILE__)).or_throw( []{ throw std::runtime_error("Could not find parent directory of this file: " __FILE__); } ) ).or_throw( []{ throw std::runtime_error("Could not find the cdm directory"); } ); Si::absolute_path const original_main_cpp = cdm / Si::relative_path("configure_cmdline/main.cpp"); Si::absolute_path const source = temporary / Si::relative_path("source"); Si::recreate_directories(source, Si::throw_); Si::absolute_path const copied_main_cpp = source / Si::relative_path("main.cpp"); Si::copy(original_main_cpp, copied_main_cpp, Si::throw_); { Si::absolute_path const cmakeLists = source / Si::relative_path("CMakeLists.txt"); std::ofstream cmakeListsFile(cmakeLists.c_str()); cmakeListsFile << "cmake_minimum_required(VERSION 2.8)\n"; cmakeListsFile << "project(configure_cmdline_generated)\n"; cmakeListsFile << "if(UNIX)\n"; cmakeListsFile << " execute_process(COMMAND ${CMAKE_CXX_COMPILER} -dumpversion OUTPUT_VARIABLE GCC_VERSION)\n"; cmakeListsFile << " if(GCC_VERSION VERSION_GREATER 4.7)\n"; cmakeListsFile << " add_definitions(-std=c++1y)\n"; cmakeListsFile << " else()\n"; cmakeListsFile << " add_definitions(-std=c++0x)\n"; cmakeListsFile << " endif()\n"; cmakeListsFile << "endif()\n"; cmakeListsFile << "if(MSVC)\n"; cmakeListsFile << " set(Boost_USE_STATIC_LIBS ON)\n"; cmakeListsFile << "endif()\n"; cmakeListsFile << "find_package(Boost REQUIRED filesystem coroutine program_options thread context system)\n"; cmakeListsFile << "set(CMAKE_EXE_LINKER_FLAGS \"${CMAKE_EXE_LINKER_FLAGS} /SAFESEH:NO\")\n"; cmakeListsFile << "include_directories(SYSTEM ${SILICIUM_INCLUDE_DIR} ${Boost_INCLUDE_DIR} ${CDM_CONFIGURE_INCLUDE_DIRS})\n"; cmakeListsFile << "link_directories(${Boost_LIBRARY_DIR})\n"; cmakeListsFile << "add_executable(configure main.cpp)\n"; cmakeListsFile << "target_link_libraries(configure ${Boost_LIBRARIES})\n"; if (!cmakeListsFile) { throw std::runtime_error(("Could not generate " + Si::to_utf8_string(cmakeLists)).c_str()); } } Si::absolute_path const build = temporary / Si::relative_path("build"); Si::recreate_directories(build, Si::throw_); { std::vector<Si::os_string> arguments; { Si::absolute_path const repository_root = Si::parent(cdm).or_throw([] { throw std::runtime_error("Could not find the silicium directory"); }); Si::absolute_path const silicium = repository_root / Si::relative_path("dependencies/silicium"); arguments.emplace_back(SILICIUM_SYSTEM_LITERAL("-DSILICIUM_INCLUDE_DIR=") + to_os_string(silicium)); } if (boost_root) { arguments.emplace_back(SILICIUM_SYSTEM_LITERAL("-DBOOST_ROOT=") + to_os_string(*boost_root)); } Si::absolute_path const modules = cdm / Si::relative_path("modules"); arguments.emplace_back(SILICIUM_SYSTEM_LITERAL("-DCDM_CONFIGURE_INCLUDE_DIRS=") + Si::to_os_string(application_source) + SILICIUM_SYSTEM_LITERAL(";") + Si::to_os_string(modules)); arguments.emplace_back(Si::to_os_string(source)); #ifdef _MSC_VER arguments.emplace_back(SILICIUM_SYSTEM_LITERAL("-G \"Visual Studio 12 2013\"")); #endif if (Si::run_process(Si::cmake_exe, arguments, build, output).get() != 0) { throw std::runtime_error("Could not CMake-configure the cdm configure executable"); } } { std::vector<Si::os_string> arguments; arguments.emplace_back(SILICIUM_SYSTEM_LITERAL("--build")); arguments.emplace_back(SILICIUM_SYSTEM_LITERAL(".")); if (Si::run_process(Si::cmake_exe, arguments, build, output).get() != 0) { throw std::runtime_error("Could not CMake --build the cdm configure executable"); } } Si::absolute_path built_executable = build / Si::relative_path( #ifdef _MSC_VER SILICIUM_SYSTEM_LITERAL("Debug/") #endif SILICIUM_SYSTEM_LITERAL("configure") #ifdef _WIN32 SILICIUM_SYSTEM_LITERAL(".exe") #endif ); return built_executable; } void run_configure( Si::absolute_path const &configure_executable, Si::absolute_path const &module_permanent, Si::absolute_path const &application_source, Si::absolute_path const &application_build_dir, Si::Sink<char, Si::success>::interface &output) { Si::create_directories(module_permanent, Si::throw_); Si::create_directories(application_build_dir, Si::throw_); std::vector<Si::os_string> arguments; arguments.emplace_back(SILICIUM_SYSTEM_LITERAL("-m")); arguments.emplace_back(Si::to_os_string(module_permanent)); arguments.emplace_back(SILICIUM_SYSTEM_LITERAL("-a")); arguments.emplace_back(Si::to_os_string(application_source)); arguments.emplace_back(SILICIUM_SYSTEM_LITERAL("-b")); arguments.emplace_back(Si::to_os_string(application_build_dir)); int const rc = Si::run_process(configure_executable, arguments, application_build_dir, output).get(); if (rc != 0) { throw std::runtime_error("Could not configure the application: " + boost::lexical_cast<std::string>(rc)); } } } namespace cdm { void do_configure( Si::absolute_path const &temporary, Si::absolute_path const &module_permanent, Si::absolute_path const &application_source, Si::absolute_path const &application_build_dir, Si::optional<Si::absolute_path> const &boost_root, Si::Sink<char, Si::success>::interface &output ) { Si::absolute_path const configure_executable = build_configure(application_source, temporary, boost_root, output); run_configure(configure_executable, module_permanent, application_source, application_build_dir, output); } } <commit_msg>the Boost.Context flag is only required for VC++<commit_after>#include "configure.hpp" #include <silicium/file_operations.hpp> #include <silicium/cmake.hpp> #include <fstream> namespace { Si::absolute_path build_configure( Si::absolute_path const &application_source, Si::absolute_path const &temporary, Si::optional<Si::absolute_path> const &boost_root, Si::Sink<char, Si::success>::interface &output) { Si::absolute_path const cdm = Si::parent( Si::parent(*Si::absolute_path::create(__FILE__)).or_throw( []{ throw std::runtime_error("Could not find parent directory of this file: " __FILE__); } ) ).or_throw( []{ throw std::runtime_error("Could not find the cdm directory"); } ); Si::absolute_path const original_main_cpp = cdm / Si::relative_path("configure_cmdline/main.cpp"); Si::absolute_path const source = temporary / Si::relative_path("source"); Si::recreate_directories(source, Si::throw_); Si::absolute_path const copied_main_cpp = source / Si::relative_path("main.cpp"); Si::copy(original_main_cpp, copied_main_cpp, Si::throw_); { Si::absolute_path const cmakeLists = source / Si::relative_path("CMakeLists.txt"); std::ofstream cmakeListsFile(cmakeLists.c_str()); cmakeListsFile << "cmake_minimum_required(VERSION 2.8)\n"; cmakeListsFile << "project(configure_cmdline_generated)\n"; cmakeListsFile << "if(UNIX)\n"; cmakeListsFile << " execute_process(COMMAND ${CMAKE_CXX_COMPILER} -dumpversion OUTPUT_VARIABLE GCC_VERSION)\n"; cmakeListsFile << " if(GCC_VERSION VERSION_GREATER 4.7)\n"; cmakeListsFile << " add_definitions(-std=c++1y)\n"; cmakeListsFile << " else()\n"; cmakeListsFile << " add_definitions(-std=c++0x)\n"; cmakeListsFile << " endif()\n"; cmakeListsFile << "endif()\n"; cmakeListsFile << "if(MSVC)\n"; cmakeListsFile << " set(Boost_USE_STATIC_LIBS ON)\n"; cmakeListsFile << " set(CMAKE_EXE_LINKER_FLAGS \"${CMAKE_EXE_LINKER_FLAGS} /SAFESEH:NO\")\n"; cmakeListsFile << "endif()\n"; cmakeListsFile << "find_package(Boost REQUIRED filesystem coroutine program_options thread context system)\n"; cmakeListsFile << "include_directories(SYSTEM ${SILICIUM_INCLUDE_DIR} ${Boost_INCLUDE_DIR} ${CDM_CONFIGURE_INCLUDE_DIRS})\n"; cmakeListsFile << "link_directories(${Boost_LIBRARY_DIR})\n"; cmakeListsFile << "add_executable(configure main.cpp)\n"; cmakeListsFile << "target_link_libraries(configure ${Boost_LIBRARIES})\n"; if (!cmakeListsFile) { throw std::runtime_error(("Could not generate " + Si::to_utf8_string(cmakeLists)).c_str()); } } Si::absolute_path const build = temporary / Si::relative_path("build"); Si::recreate_directories(build, Si::throw_); { std::vector<Si::os_string> arguments; { Si::absolute_path const repository_root = Si::parent(cdm).or_throw([] { throw std::runtime_error("Could not find the silicium directory"); }); Si::absolute_path const silicium = repository_root / Si::relative_path("dependencies/silicium"); arguments.emplace_back(SILICIUM_SYSTEM_LITERAL("-DSILICIUM_INCLUDE_DIR=") + to_os_string(silicium)); } if (boost_root) { arguments.emplace_back(SILICIUM_SYSTEM_LITERAL("-DBOOST_ROOT=") + to_os_string(*boost_root)); } Si::absolute_path const modules = cdm / Si::relative_path("modules"); arguments.emplace_back(SILICIUM_SYSTEM_LITERAL("-DCDM_CONFIGURE_INCLUDE_DIRS=") + Si::to_os_string(application_source) + SILICIUM_SYSTEM_LITERAL(";") + Si::to_os_string(modules)); arguments.emplace_back(Si::to_os_string(source)); #ifdef _MSC_VER arguments.emplace_back(SILICIUM_SYSTEM_LITERAL("-G \"Visual Studio 12 2013\"")); #endif if (Si::run_process(Si::cmake_exe, arguments, build, output).get() != 0) { throw std::runtime_error("Could not CMake-configure the cdm configure executable"); } } { std::vector<Si::os_string> arguments; arguments.emplace_back(SILICIUM_SYSTEM_LITERAL("--build")); arguments.emplace_back(SILICIUM_SYSTEM_LITERAL(".")); if (Si::run_process(Si::cmake_exe, arguments, build, output).get() != 0) { throw std::runtime_error("Could not CMake --build the cdm configure executable"); } } Si::absolute_path built_executable = build / Si::relative_path( #ifdef _MSC_VER SILICIUM_SYSTEM_LITERAL("Debug/") #endif SILICIUM_SYSTEM_LITERAL("configure") #ifdef _WIN32 SILICIUM_SYSTEM_LITERAL(".exe") #endif ); return built_executable; } void run_configure( Si::absolute_path const &configure_executable, Si::absolute_path const &module_permanent, Si::absolute_path const &application_source, Si::absolute_path const &application_build_dir, Si::Sink<char, Si::success>::interface &output) { Si::create_directories(module_permanent, Si::throw_); Si::create_directories(application_build_dir, Si::throw_); std::vector<Si::os_string> arguments; arguments.emplace_back(SILICIUM_SYSTEM_LITERAL("-m")); arguments.emplace_back(Si::to_os_string(module_permanent)); arguments.emplace_back(SILICIUM_SYSTEM_LITERAL("-a")); arguments.emplace_back(Si::to_os_string(application_source)); arguments.emplace_back(SILICIUM_SYSTEM_LITERAL("-b")); arguments.emplace_back(Si::to_os_string(application_build_dir)); int const rc = Si::run_process(configure_executable, arguments, application_build_dir, output).get(); if (rc != 0) { throw std::runtime_error("Could not configure the application: " + boost::lexical_cast<std::string>(rc)); } } } namespace cdm { void do_configure( Si::absolute_path const &temporary, Si::absolute_path const &module_permanent, Si::absolute_path const &application_source, Si::absolute_path const &application_build_dir, Si::optional<Si::absolute_path> const &boost_root, Si::Sink<char, Si::success>::interface &output ) { Si::absolute_path const configure_executable = build_configure(application_source, temporary, boost_root, output); run_configure(configure_executable, module_permanent, application_source, application_build_dir, output); } } <|endoftext|>
<commit_before><commit_msg>Add flag to ignore unknown disk id warnings<commit_after><|endoftext|>
<commit_before>#ifndef __STRESS_CLIENT_DISTR_HPP__ #define __STRESS_CLIENT_DISTR_HPP__ #include <stdio.h> #include <string> #include <string.h> #include <stdint.h> #include "utils.hpp" /* payload_t represents just a string of characters. It's designed so that its internal buffer can be reused over and over. */ struct payload_t { /* "first" is the buffer and "second" is how many bytes of the buffer are in use. The names are a holdover from when payload_t was defined as a std::pair<char*, size_t>. */ char *first; size_t second; int buffer_size; payload_t() : first(NULL), second(0), buffer_size(0) { } payload_t(int bs) : first(new char[bs]), second(0), buffer_size(bs) { } payload_t(const payload_t &p) : first(new char[p.buffer_size]), second(p.second), buffer_size(p.buffer_size) { memcpy(first, p.first, second); } payload_t &operator=(const payload_t &p) { delete[] first; first = new char[p.buffer_size]; second = p.second; buffer_size = p.buffer_size; memcpy(first, p.first, second); } ~payload_t() { delete[] first; } /* If the payload's buffer has less than this much space, then expand the payload's buffer. The contents of the payload's buffer after this operation are undefined. */ void grow_to(int size) { if (buffer_size < size) { delete[] first; first = new char[size]; buffer_size = size; } } }; inline void append(payload_t *p, payload_t *other) { p->second += other->second; memcpy(p->first + p->second, other->first, other->second); } inline void prepend(payload_t *p, payload_t *other) { p->second += other->second; memmove(p->first + p->second, p->first, p->second); memcpy(p->first, other->first, other->second); } /* Defines a distribution of values, from min to max. */ struct distr_t { public: distr_t(int _min, int _max) : min(_min), max(_max) {} distr_t() : min(8), max(16) {} void parse(const char *const_str) { std::string param(const_str); size_t hyphenIndex = param.find("-"); // Make sure the parameter only contains numerals and the (optional) hyphen if (param.find_first_not_of("0123456789-") != std::string::npos) { fprintf(stderr, "Invalid distr format (use NUM or MIN-MAX), brackets and +/- signs are not supported\n"); exit(-1); } if (hyphenIndex == std::string::npos) { min = max = atoi(param.c_str()); return; } // Protection against more than one hyphen if (param.rfind("-") != hyphenIndex) { fprintf(stderr, "Invalid distr format (use NUM or MIN-MAX), +/- signs are not supported\n"); exit(-1); } min = atoi(param.substr(0, hyphenIndex).c_str()); max = atoi(param.substr(hyphenIndex + 1, std::string::npos).c_str()); if (min > max) { fprintf(stderr, "Invalid distr format (use NUM or MIN-MAX, where MIN <= MAX)\n"); exit(-1); } } void print() { printf("%d-%d", min, max); } public: int min, max; }; #endif // __STRESS_CLIENT_DISTR_HPP__ <commit_msg>Fixed a previous bug that was causing the stress client to send garbage instead of strings that only contained A.<commit_after>#ifndef __STRESS_CLIENT_DISTR_HPP__ #define __STRESS_CLIENT_DISTR_HPP__ #include <stdio.h> #include <string> #include <string.h> #include <stdint.h> #include "utils.hpp" /* payload_t represents just a string of characters. It's designed so that its internal buffer can be reused over and over. */ struct payload_t { /* "first" is the buffer and "second" is how many bytes of the buffer are in use. The names are a holdover from when payload_t was defined as a std::pair<char*, size_t>. */ char *first; size_t second; int buffer_size; payload_t() : first(NULL), second(0), buffer_size(0) { } payload_t(int bs) : first(new char[bs]), second(0), buffer_size(bs) { } payload_t(const payload_t &p) : first(new char[p.buffer_size]), second(p.second), buffer_size(p.buffer_size) { memcpy(first, p.first, buffer_size); } payload_t &operator=(const payload_t &p) { delete[] first; first = new char[p.buffer_size]; second = p.second; buffer_size = p.buffer_size; memcpy(first, p.first, buffer_size); } ~payload_t() { delete[] first; } /* If the payload's buffer has less than this much space, then expand the payload's buffer. The contents of the payload's buffer after this operation are undefined. */ void grow_to(int size) { if (buffer_size < size) { delete[] first; first = new char[size]; buffer_size = size; } } }; inline void append(payload_t *p, payload_t *other) { p->second += other->second; memcpy(p->first + p->second, other->first, other->second); } inline void prepend(payload_t *p, payload_t *other) { p->second += other->second; memmove(p->first + p->second, p->first, p->second); memcpy(p->first, other->first, other->second); } /* Defines a distribution of values, from min to max. */ struct distr_t { public: distr_t(int _min, int _max) : min(_min), max(_max) {} distr_t() : min(8), max(16) {} void parse(const char *const_str) { std::string param(const_str); size_t hyphenIndex = param.find("-"); // Make sure the parameter only contains numerals and the (optional) hyphen if (param.find_first_not_of("0123456789-") != std::string::npos) { fprintf(stderr, "Invalid distr format (use NUM or MIN-MAX), brackets and +/- signs are not supported\n"); exit(-1); } if (hyphenIndex == std::string::npos) { min = max = atoi(param.c_str()); return; } // Protection against more than one hyphen if (param.rfind("-") != hyphenIndex) { fprintf(stderr, "Invalid distr format (use NUM or MIN-MAX), +/- signs are not supported\n"); exit(-1); } min = atoi(param.substr(0, hyphenIndex).c_str()); max = atoi(param.substr(hyphenIndex + 1, std::string::npos).c_str()); if (min > max) { fprintf(stderr, "Invalid distr format (use NUM or MIN-MAX, where MIN <= MAX)\n"); exit(-1); } } void print() { printf("%d-%d", min, max); } public: int min, max; }; #endif // __STRESS_CLIENT_DISTR_HPP__ <|endoftext|>
<commit_before>#include "xs_mesh_homogenized.hpp" #include <iomanip> #include <iostream> #include <sstream> using std::cout; using std::cin; using std::endl; namespace mocc { XSMeshHomogenized::XSMeshHomogenized( const CoreMesh& mesh ): mesh_( mesh ) { // Set up the non-xs part of the xs mesh eubounds_ = mesh_.mat_lib().g_bounds(); ng_ = eubounds_.size(); regions_ = std::vector<XSMeshRegion>( mesh_.n_pin() ); int ipin = 0; int first_reg = 0; for( const auto &pin: mesh_ ) { // Use the lexicographically-ordered pin index as the xs mesh index. // This is to put the indexing in a way that works best for the Sn // sweeper as it is implemented now. This is really brittle, and // should be replaced with some sort of Sn Mesh object, which both // the XS Mesh and the Sn sweeper will use to handle indexing. auto pos = mesh.pin_position(ipin); int ireg = mesh.index_lex( pos ); int ixsreg = mesh_.index_lex( pos ); regions_[ixsreg] = this->homogenize_region( ireg, *pin ); ipin++; first_reg += pin->n_reg(); } } /** * Update the XS mesh, incorporating a new estimate of the scalar flux. */ void XSMeshHomogenized::update( const ArrayF &flux ) { int ipin = 0; int first_reg = 0; for( const auto &pin: mesh_ ) { int ireg = mesh_.index_lex( mesh_.pin_position(ipin) ); int ixsreg = ireg; regions_[ixsreg] = this->homogenize_region_flux( ireg, first_reg, *pin, flux); ipin++; first_reg += pin->n_reg(); } return; } XSMeshRegion XSMeshHomogenized::homogenize_region( int i, const Pin& pin) const { VecI fsrs( 1, i ); VecF xstr( ng_, 0.0 ); VecF xsnf( ng_, 0.0 ); VecF xskf( ng_, 0.0 ); VecF xsch( ng_, 0.0 ); std::vector<VecF> scat( ng_, VecF(ng_, 0.0) ); auto mat_lib = mesh_.mat_lib(); auto &pin_mesh = pin.mesh(); auto vols = pin_mesh.vols(); for( size_t ig=0; ig<ng_; ig++ ) { int ireg = 0; int ixsreg = 0; real_t fvol = 0.0; for( auto &mat_id: pin.mat_ids() ) { auto mat = mat_lib.get_material_by_id(mat_id); const ScatteringRow& scat_row = mat.xssc().to(ig); int gmin = scat_row.min_g; int gmax = scat_row.max_g; real_t fsrc = 0.0; for( size_t igg=0; igg<ng_; igg++ ) { fsrc += mat.xsnf()[igg]; } for( size_t i=0; i<pin_mesh.n_fsrs(ixsreg); i++ ) { fvol += vols[ireg] * fsrc; xstr[ig] += vols[ireg] * mat.xstr()[ig]; xsnf[ig] += vols[ireg] * mat.xsnf()[ig]; xskf[ig] += vols[ireg] * mat.xskf()[ig]; xsch[ig] += vols[ireg] * fsrc * mat.xsch()[ig]; for( int igg=gmin; igg<=gmax; igg++ ) { scat[ig][igg] += scat_row.from[igg-gmin] * vols[ireg]; } ireg++; } ixsreg++; } xstr[ig] /= pin.vol(); xsnf[ig] /= pin.vol(); xskf[ig] /= pin.vol(); xsch[ig] /= fvol; for( auto &s: scat[ig] ) { s /= pin.vol(); } } ScatteringMatrix scat_mat(scat); return XSMeshRegion( fsrs, xstr, xsnf, xsch, xskf, scat_mat ); } XSMeshRegion XSMeshHomogenized::homogenize_region_flux( int i, int first_reg, const Pin& pin, const ArrayF &flux ) const { size_t n_reg = mesh_.n_reg(); // Set the FSRs to be one element, representing the coarse mesh index to // which this \ref XSMeshRegion belongs. VecI fsrs( 1, i ); VecF xstr( ng_, 0.0 ); VecF xsnf( ng_, 0.0 ); VecF xskf( ng_, 0.0 ); VecF xsch( ng_, 0.0 ); std::vector<VecF> scat( ng_, VecF(ng_, 0.0) ); auto mat_lib = mesh_.mat_lib(); auto &pin_mesh = pin.mesh(); auto vols = pin_mesh.vols(); // Precompute the fission source in each region, since it is the // wieghting factor for chi VecF fs( pin_mesh.n_reg(), 0.0 ); { int ixsreg = 0; for( auto &mat_id: pin.mat_ids() ) { auto mat = mat_lib.get_material_by_id(mat_id); for( size_t ig=0; ig<ng_; ig++ ) { int ireg = first_reg; // pin-local region index int ireg_local = 0; for( size_t i=0; i<pin_mesh.n_fsrs(ixsreg); i++ ) { fs[ireg_local] += mat.xsnf()[ig] * flux[ireg + ig*n_reg] * vols[ireg_local]; ireg++; ireg_local++; } } ixsreg++; } } real_t fs_sum = 0.0; for( auto &v: fs ) { fs_sum += v; } for( size_t ig=0; ig<ng_; ig++ ) { real_t fluxvolsum = 0.0; VecF scatsum(ng_, 0.0); int ireg = first_reg; // global region index int ireg_local = 0; // pin-local refion index int ixsreg = 0; for( auto &mat_id: pin.mat_ids() ) { auto mat = mat_lib.get_material_by_id(mat_id); const ScatteringRow& scat_row = mat.xssc().to(ig); int gmin = scat_row.min_g; int gmax = scat_row.max_g; for( size_t i=0; i<pin_mesh.n_fsrs(ixsreg); i++ ) { real_t v = vols[ireg_local]; real_t flux_i = flux[ireg + ig*n_reg]; fluxvolsum += v * flux_i; xstr[ig] += v * flux_i * mat.xstr()[ig]; xsnf[ig] += v * flux_i * mat.xsnf()[ig]; xskf[ig] += v * flux_i * mat.xskf()[ig]; xsch[ig] += fs[ireg_local] * mat.xsch()[ig]; for( int igg=0; igg<ng_; igg++ ){ real_t fluxgg = flux[ireg + igg*n_reg]; fluxgg = 1.0; scatsum[igg] += fluxgg * v; if( (igg >= gmin) && (igg <= gmax) ) { real_t scgg = scat_row.from[igg-gmin]; scat[ig][igg] += scgg * v * fluxgg; } } ireg++; ireg_local++; } ixsreg++; } for( size_t igg=0; igg<ng_; igg++ ) { if( scat[ig][igg] > 0.0 ) { scat[ig][igg] /= scatsum[igg]; } } xstr[ig] /= fluxvolsum; xsnf[ig] /= fluxvolsum; xskf[ig] /= fluxvolsum; xsch[ig] /= fs_sum; } ScatteringMatrix scat_mat(scat); return XSMeshRegion( fsrs, xstr, xsnf, xsch, xskf, scat_mat ); } void XSMeshHomogenized::output( H5::CommonFG *file ) const { file->createGroup( "/xsmesh" ); file->createGroup( "/xsmesh/xstr" ); auto d = mesh_.dimensions(); std::reverse(d.begin(), d.end()); for( size_t ig=0; ig<ng_; ig++ ) { // Transport cross section VecF xstr( this->size(), 0.0 ); int i = 0; for( auto xsr: regions_ ) { xstr[i] = xsr.xsmactr()[ig]; i++; } std::stringstream setname; setname << "/xsmesh/xstr/" << ig; HDF::Write( file, setname.str(), xstr, d ); } return; } } <commit_msg>Finish proper scattering xs homogenization<commit_after>#include "xs_mesh_homogenized.hpp" #include <iomanip> #include <iostream> #include <sstream> using std::cout; using std::cin; using std::endl; namespace mocc { XSMeshHomogenized::XSMeshHomogenized( const CoreMesh& mesh ): mesh_( mesh ) { // Set up the non-xs part of the xs mesh eubounds_ = mesh_.mat_lib().g_bounds(); ng_ = eubounds_.size(); regions_ = std::vector<XSMeshRegion>( mesh_.n_pin() ); int ipin = 0; int first_reg = 0; for( const auto &pin: mesh_ ) { // Use the lexicographically-ordered pin index as the xs mesh index. // This is to put the indexing in a way that works best for the Sn // sweeper as it is implemented now. This is really brittle, and // should be replaced with some sort of Sn Mesh object, which both // the XS Mesh and the Sn sweeper will use to handle indexing. auto pos = mesh.pin_position(ipin); int ireg = mesh.index_lex( pos ); int ixsreg = mesh_.index_lex( pos ); regions_[ixsreg] = this->homogenize_region( ireg, *pin ); ipin++; first_reg += pin->n_reg(); } } /** * Update the XS mesh, incorporating a new estimate of the scalar flux. */ void XSMeshHomogenized::update( const ArrayF &flux ) { int ipin = 0; int first_reg = 0; for( const auto &pin: mesh_ ) { int ireg = mesh_.index_lex( mesh_.pin_position(ipin) ); int ixsreg = ireg; regions_[ixsreg] = this->homogenize_region_flux( ireg, first_reg, *pin, flux); ipin++; first_reg += pin->n_reg(); } return; } XSMeshRegion XSMeshHomogenized::homogenize_region( int i, const Pin& pin) const { VecI fsrs( 1, i ); VecF xstr( ng_, 0.0 ); VecF xsnf( ng_, 0.0 ); VecF xskf( ng_, 0.0 ); VecF xsch( ng_, 0.0 ); std::vector<VecF> scat( ng_, VecF(ng_, 0.0) ); auto mat_lib = mesh_.mat_lib(); auto &pin_mesh = pin.mesh(); auto vols = pin_mesh.vols(); for( size_t ig=0; ig<ng_; ig++ ) { int ireg = 0; int ixsreg = 0; real_t fvol = 0.0; for( auto &mat_id: pin.mat_ids() ) { auto mat = mat_lib.get_material_by_id(mat_id); const ScatteringRow& scat_row = mat.xssc().to(ig); int gmin = scat_row.min_g; int gmax = scat_row.max_g; real_t fsrc = 0.0; for( size_t igg=0; igg<ng_; igg++ ) { fsrc += mat.xsnf()[igg]; } for( size_t i=0; i<pin_mesh.n_fsrs(ixsreg); i++ ) { fvol += vols[ireg] * fsrc; xstr[ig] += vols[ireg] * mat.xstr()[ig]; xsnf[ig] += vols[ireg] * mat.xsnf()[ig]; xskf[ig] += vols[ireg] * mat.xskf()[ig]; xsch[ig] += vols[ireg] * fsrc * mat.xsch()[ig]; for( int igg=gmin; igg<=gmax; igg++ ) { scat[ig][igg] += scat_row.from[igg-gmin] * vols[ireg]; } ireg++; } ixsreg++; } xstr[ig] /= pin.vol(); xsnf[ig] /= pin.vol(); xskf[ig] /= pin.vol(); xsch[ig] /= fvol; for( auto &s: scat[ig] ) { s /= pin.vol(); } } ScatteringMatrix scat_mat(scat); return XSMeshRegion( fsrs, xstr, xsnf, xsch, xskf, scat_mat ); } XSMeshRegion XSMeshHomogenized::homogenize_region_flux( int i, int first_reg, const Pin& pin, const ArrayF &flux ) const { size_t n_reg = mesh_.n_reg(); // Set the FSRs to be one element, representing the coarse mesh index to // which this \ref XSMeshRegion belongs. VecI fsrs( 1, i ); VecF xstr( ng_, 0.0 ); VecF xsnf( ng_, 0.0 ); VecF xskf( ng_, 0.0 ); VecF xsch( ng_, 0.0 ); std::vector<VecF> scat( ng_, VecF(ng_, 0.0) ); auto mat_lib = mesh_.mat_lib(); auto &pin_mesh = pin.mesh(); auto vols = pin_mesh.vols(); // Precompute the fission source in each region, since it is the // wieghting factor for chi VecF fs( pin_mesh.n_reg(), 0.0 ); { int ixsreg = 0; for( auto &mat_id: pin.mat_ids() ) { auto mat = mat_lib.get_material_by_id(mat_id); for( size_t ig=0; ig<ng_; ig++ ) { int ireg = first_reg; // pin-local region index int ireg_local = 0; for( size_t i=0; i<pin_mesh.n_fsrs(ixsreg); i++ ) { fs[ireg_local] += mat.xsnf()[ig] * flux[ireg + ig*n_reg] * vols[ireg_local]; ireg++; ireg_local++; } } ixsreg++; } } real_t fs_sum = 0.0; for( auto &v: fs ) { fs_sum += v; } for( size_t ig=0; ig<ng_; ig++ ) { real_t fluxvolsum = 0.0; VecF scatsum(ng_, 0.0); int ireg = first_reg; // global region index int ireg_local = 0; // pin-local refion index int ixsreg = 0; for( auto &mat_id: pin.mat_ids() ) { auto mat = mat_lib.get_material_by_id(mat_id); const ScatteringRow& scat_row = mat.xssc().to(ig); int gmin = scat_row.min_g; int gmax = scat_row.max_g; for( size_t i=0; i<pin_mesh.n_fsrs(ixsreg); i++ ) { real_t v = vols[ireg_local]; real_t flux_i = flux[ireg + ig*n_reg]; fluxvolsum += v * flux_i; xstr[ig] += v * flux_i * mat.xstr()[ig]; xsnf[ig] += v * flux_i * mat.xsnf()[ig]; xskf[ig] += v * flux_i * mat.xskf()[ig]; xsch[ig] += fs[ireg_local] * mat.xsch()[ig]; for( int igg=0; igg<ng_; igg++ ){ real_t fluxgg = flux[ireg + igg*n_reg]; scatsum[igg] += fluxgg * v; if( (igg >= gmin) && (igg <= gmax) ) { real_t scgg = scat_row.from[igg-gmin]; scat[ig][igg] += scgg * v * fluxgg; } } ireg++; ireg_local++; } ixsreg++; } for( size_t igg=0; igg<ng_; igg++ ) { if( scat[ig][igg] > 0.0 ) { scat[ig][igg] /= scatsum[igg]; } } xstr[ig] /= fluxvolsum; xsnf[ig] /= fluxvolsum; xskf[ig] /= fluxvolsum; xsch[ig] /= fs_sum; } ScatteringMatrix scat_mat(scat); return XSMeshRegion( fsrs, xstr, xsnf, xsch, xskf, scat_mat ); } void XSMeshHomogenized::output( H5::CommonFG *file ) const { file->createGroup( "/xsmesh" ); file->createGroup( "/xsmesh/xstr" ); file->createGroup( "/xsmesh/xsnf" ); auto d = mesh_.dimensions(); std::reverse(d.begin(), d.end()); for( size_t ig=0; ig<ng_; ig++ ) { // Transport cross section VecF xstr( this->size(), 0.0 ); VecF xsnf( this->size(), 0.0 ); int i = 0; for( auto xsr: regions_ ) { xstr[i] = xsr.xsmactr()[ig]; xsnf[i] = xsr.xsmacnf()[ig]; i++; } { std::stringstream setname; setname << "/xsmesh/xstr/" << ig; HDF::Write( file, setname.str(), xstr, d ); } { std::stringstream setname; setname << "/xsmesh/xsnf/" << ig; HDF::Write( file, setname.str(), xsnf, d ); } } // scattering matrix VecF scat( regions_.size()*ng_*ng_, 0.0 ); auto it = scat.begin(); for( const auto &reg: regions_ ){ auto reg_scat = reg.xsmacsc().as_vector(); std::copy( reg_scat.begin(), reg_scat.end(), it ); } VecI dims( 3 ); dims[0] = regions_.size(); dims[1] = ng_; dims[2] = ng_; HDF::Write( file, "/xsmesh/xssc", scat, dims ); return; } } <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the Qt Mobility Components. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <qgraphicsvideoitem.h> #include <qmediaobject.h> #include <qmediaservice.h> #include <qpaintervideosurface_p.h> #include <qvideooutputcontrol.h> #include <qvideorenderercontrol.h> #include <QtMultimedia/qvideosurfaceformat.h> QTM_BEGIN_NAMESPACE class QGraphicsVideoItemPrivate { public: QGraphicsVideoItemPrivate() : q_ptr(0) , surface(0) , mediaObject(0) , service(0) , outputControl(0) , rendererControl(0) { } QGraphicsVideoItem *q_ptr; QPainterVideoSurface *surface; QMediaObject *mediaObject; QMediaService *service; QVideoOutputControl *outputControl; QVideoRendererControl *rendererControl; QRect boundingRect; void clearService(); void _q_present(); void _q_formatChanged(const QVideoSurfaceFormat &format); void _q_serviceDestroyed(); void _q_mediaObjectDestroyed(); }; void QGraphicsVideoItemPrivate::clearService() { if (outputControl) { outputControl->setOutput(QVideoOutputControl::NoOutput); outputControl = 0; } if (rendererControl) { surface->stop(); rendererControl->setSurface(0); rendererControl = 0; } if (service) { QObject::disconnect(service, SIGNAL(destroyed()), q_ptr, SLOT(_q_serviceDestroyed())); service = 0; } } void QGraphicsVideoItemPrivate::_q_present() { q_ptr->update(boundingRect); } void QGraphicsVideoItemPrivate::_q_formatChanged(const QVideoSurfaceFormat &format) { q_ptr->prepareGeometryChange(); boundingRect = QRect(QPoint(0, 0), format.sizeHint()); boundingRect.moveCenter(QPoint(0, 0)); } void QGraphicsVideoItemPrivate::_q_serviceDestroyed() { rendererControl = 0; outputControl = 0; service = 0; surface->stop(); } void QGraphicsVideoItemPrivate::_q_mediaObjectDestroyed() { mediaObject = 0; clearService(); } /*! \class QGraphicsVideoItem \brief The QGraphicsVideoItem class provides a graphics item which display video produced by a QMediaObject. \ingroup multimedia Attaching a QGraphicsVideoItem to a QMediaObject allows it to display the video or image output of that media object. A QGraphicsVideoItem is attached to a media object by passing a pointer to the QMediaObject to the setMediaObject() function. \code player = new QMediaPlayer(this); QGraphicsVideoItem *item = new QGraphicsVideoItem; item->setMediaObject(player); graphicsView->scence()->addItem(item); graphicsView->show(); player->setMedia(video); player->play(); \endcode \bold {Note}: Only a single display output can be attached to a media object at one time. \sa QMediaObject, QMediaPlayer, QVideoWidget */ /*! Constructs a graphics item that displays video. The \a parent is passed to QGraphicsItem. */ QGraphicsVideoItem::QGraphicsVideoItem(QGraphicsItem *parent) : QGraphicsItem(parent) , d_ptr(new QGraphicsVideoItemPrivate) { d_ptr->q_ptr = this; d_ptr->surface = new QPainterVideoSurface; } /*! Destroys a video graphics item. */ QGraphicsVideoItem::~QGraphicsVideoItem() { if (d_ptr->outputControl) d_ptr->outputControl->setOutput(QVideoOutputControl::NoOutput); if (d_ptr->rendererControl) d_ptr->rendererControl->setSurface(0); delete d_ptr->surface; delete d_ptr; } /*! \property QGraphicsVideoItem::mediaObject \brief the media object which provides the video displayed by a graphics item. */ QMediaObject *QGraphicsVideoItem::mediaObject() const { return d_func()->mediaObject; } void QGraphicsVideoItem::setMediaObject(QMediaObject *object) { Q_D(QGraphicsVideoItem); if (object == d->mediaObject) return; d->clearService(); if (d->mediaObject) { disconnect(d->mediaObject, SIGNAL(destroyed()), this, SLOT(_q_mediaObjectDestroyed())); d->mediaObject->unbind(this); } d->mediaObject = object; if (d->mediaObject) { d->mediaObject->bind(this); connect(d->mediaObject, SIGNAL(destroyed()), this, SLOT(_q_mediaObjectDestroyed())); d->service = d->mediaObject->service(); if (d->service) { connect(d->service, SIGNAL(destroyed()), this, SLOT(_q_serviceDestroyed())); d->outputControl = qobject_cast<QVideoOutputControl *>( d->service->control(QVideoOutputControl_iid)); d->rendererControl = qobject_cast<QVideoRendererControl *>( d->service->control(QVideoRendererControl_iid)); if (d->outputControl != 0 && d->rendererControl != 0) { if (!d->surface) { d->surface = new QPainterVideoSurface; connect(d->surface, SIGNAL(frameChanged()), this, SLOT(_q_present())); connect(d->surface, SIGNAL(surfaceFormatChanged(QVideoSurfaceFormat)), this, SLOT(_q_formatChanged(QVideoSurfaceFormat))); connect(d->service, SIGNAL(destroyed()), this, SLOT(_q_serviceDestroyed())); } d->rendererControl->setSurface(d->surface); if (isVisible()) d->outputControl->setOutput(QVideoOutputControl::RendererOutput); } } } } /*! \reimp */ QRectF QGraphicsVideoItem::boundingRect() const { return d_func()->boundingRect; } /*! \reimp */ void QGraphicsVideoItem::paint( QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) { Q_D(QGraphicsVideoItem); Q_UNUSED(option); Q_UNUSED(widget); if (d->surface != 0) { d->surface->paint(painter, d->boundingRect); d->surface->setReady(true); } } /*! \reimp \internal */ QVariant QGraphicsVideoItem::itemChange(GraphicsItemChange change, const QVariant &value) { Q_D(QGraphicsVideoItem); if (change == ItemVisibleChange && d->outputControl != 0 && d->rendererControl != 0) { if (value.toBool()) { d->outputControl->setOutput(QVideoOutputControl::RendererOutput); return d->outputControl->output() == QVideoOutputControl::RendererOutput; } else { d->outputControl->setOutput(QVideoOutputControl::NoOutput); return value; } } else { return QGraphicsItem::itemChange(change, value); } } #include "moc_qgraphicsvideoitem.cpp" QTM_END_NAMESPACE <commit_msg>Fixed regression in QGraphicsVideoItem<commit_after>/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the Qt Mobility Components. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <qgraphicsvideoitem.h> #include <qmediaobject.h> #include <qmediaservice.h> #include <qpaintervideosurface_p.h> #include <qvideooutputcontrol.h> #include <qvideorenderercontrol.h> #include <QtMultimedia/qvideosurfaceformat.h> QTM_BEGIN_NAMESPACE class QGraphicsVideoItemPrivate { public: QGraphicsVideoItemPrivate() : q_ptr(0) , surface(0) , mediaObject(0) , service(0) , outputControl(0) , rendererControl(0) { } QGraphicsVideoItem *q_ptr; QPainterVideoSurface *surface; QMediaObject *mediaObject; QMediaService *service; QVideoOutputControl *outputControl; QVideoRendererControl *rendererControl; QRect boundingRect; void clearService(); void _q_present(); void _q_formatChanged(const QVideoSurfaceFormat &format); void _q_serviceDestroyed(); void _q_mediaObjectDestroyed(); }; void QGraphicsVideoItemPrivate::clearService() { if (outputControl) { outputControl->setOutput(QVideoOutputControl::NoOutput); outputControl = 0; } if (rendererControl) { surface->stop(); rendererControl->setSurface(0); rendererControl = 0; } if (service) { QObject::disconnect(service, SIGNAL(destroyed()), q_ptr, SLOT(_q_serviceDestroyed())); service = 0; } } void QGraphicsVideoItemPrivate::_q_present() { q_ptr->update(boundingRect); } void QGraphicsVideoItemPrivate::_q_formatChanged(const QVideoSurfaceFormat &format) { q_ptr->prepareGeometryChange(); boundingRect = QRect(QPoint(0, 0), format.sizeHint()); boundingRect.moveCenter(QPoint(0, 0)); } void QGraphicsVideoItemPrivate::_q_serviceDestroyed() { rendererControl = 0; outputControl = 0; service = 0; surface->stop(); } void QGraphicsVideoItemPrivate::_q_mediaObjectDestroyed() { mediaObject = 0; clearService(); } /*! \class QGraphicsVideoItem \brief The QGraphicsVideoItem class provides a graphics item which display video produced by a QMediaObject. \ingroup multimedia Attaching a QGraphicsVideoItem to a QMediaObject allows it to display the video or image output of that media object. A QGraphicsVideoItem is attached to a media object by passing a pointer to the QMediaObject to the setMediaObject() function. \code player = new QMediaPlayer(this); QGraphicsVideoItem *item = new QGraphicsVideoItem; item->setMediaObject(player); graphicsView->scence()->addItem(item); graphicsView->show(); player->setMedia(video); player->play(); \endcode \bold {Note}: Only a single display output can be attached to a media object at one time. \sa QMediaObject, QMediaPlayer, QVideoWidget */ /*! Constructs a graphics item that displays video. The \a parent is passed to QGraphicsItem. */ QGraphicsVideoItem::QGraphicsVideoItem(QGraphicsItem *parent) : QGraphicsItem(parent) , d_ptr(new QGraphicsVideoItemPrivate) { d_ptr->q_ptr = this; d_ptr->surface = new QPainterVideoSurface; connect(d_ptr->surface, SIGNAL(frameChanged()), this, SLOT(_q_present())); connect(d_ptr->surface, SIGNAL(surfaceFormatChanged(QVideoSurfaceFormat)), this, SLOT(_q_formatChanged(QVideoSurfaceFormat))); } /*! Destroys a video graphics item. */ QGraphicsVideoItem::~QGraphicsVideoItem() { if (d_ptr->outputControl) d_ptr->outputControl->setOutput(QVideoOutputControl::NoOutput); if (d_ptr->rendererControl) d_ptr->rendererControl->setSurface(0); delete d_ptr->surface; delete d_ptr; } /*! \property QGraphicsVideoItem::mediaObject \brief the media object which provides the video displayed by a graphics item. */ QMediaObject *QGraphicsVideoItem::mediaObject() const { return d_func()->mediaObject; } void QGraphicsVideoItem::setMediaObject(QMediaObject *object) { Q_D(QGraphicsVideoItem); if (object == d->mediaObject) return; d->clearService(); if (d->mediaObject) { disconnect(d->mediaObject, SIGNAL(destroyed()), this, SLOT(_q_mediaObjectDestroyed())); d->mediaObject->unbind(this); } d->mediaObject = object; if (d->mediaObject) { d->mediaObject->bind(this); connect(d->mediaObject, SIGNAL(destroyed()), this, SLOT(_q_mediaObjectDestroyed())); d->service = d->mediaObject->service(); if (d->service) { connect(d->service, SIGNAL(destroyed()), this, SLOT(_q_serviceDestroyed())); d->outputControl = qobject_cast<QVideoOutputControl *>( d->service->control(QVideoOutputControl_iid)); d->rendererControl = qobject_cast<QVideoRendererControl *>( d->service->control(QVideoRendererControl_iid)); if (d->outputControl != 0 && d->rendererControl != 0) { d->rendererControl->setSurface(d->surface); if (isVisible()) d->outputControl->setOutput(QVideoOutputControl::RendererOutput); } } } } /*! \reimp */ QRectF QGraphicsVideoItem::boundingRect() const { return d_func()->boundingRect; } /*! \reimp */ void QGraphicsVideoItem::paint( QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) { Q_D(QGraphicsVideoItem); Q_UNUSED(option); Q_UNUSED(widget); if (d->surface != 0) { d->surface->paint(painter, d->boundingRect); d->surface->setReady(true); } } /*! \reimp \internal */ QVariant QGraphicsVideoItem::itemChange(GraphicsItemChange change, const QVariant &value) { Q_D(QGraphicsVideoItem); if (change == ItemVisibleChange && d->outputControl != 0 && d->rendererControl != 0) { if (value.toBool()) { d->outputControl->setOutput(QVideoOutputControl::RendererOutput); return d->outputControl->output() == QVideoOutputControl::RendererOutput; } else { d->outputControl->setOutput(QVideoOutputControl::NoOutput); return value; } } else { return QGraphicsItem::itemChange(change, value); } } #include "moc_qgraphicsvideoitem.cpp" QTM_END_NAMESPACE <|endoftext|>
<commit_before>/***************************************************************************** Copyright 2004-2008 Steve Menard Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *****************************************************************************/ #include <jpype_python.h> PyObject* JPypeJavaArray::findArrayClass(PyObject* obj, PyObject* args) { try { char* cname; JPyArg::parseTuple(args, "s", &cname); JPTypeName name = JPTypeName::fromSimple(cname); JPArrayClass* claz = JPTypeManager::findArrayClass(name); if (claz == NULL) { Py_INCREF(Py_None); return Py_None; } PyObject* res = JPyCObject::fromVoidAndDesc((void*)claz, (void*)"jclass", NULL); return res; } PY_STANDARD_CATCH; PyErr_Clear(); Py_INCREF(Py_None); return Py_None; } PyObject* JPypeJavaArray::setJavaArrayClass(PyObject* self, PyObject* arg) { try { PyObject* t; JPyArg::parseTuple(arg, "O", &t); hostEnv->setJavaArrayClass(t); Py_INCREF(Py_None); return Py_None; } PY_STANDARD_CATCH return NULL; } PyObject* JPypeJavaArray::setGetJavaArrayClassMethod(PyObject* self, PyObject* arg) { try { PyObject* t; JPyArg::parseTuple(arg, "O", &t); hostEnv->setGetJavaArrayClassMethod(t); Py_INCREF(Py_None); return Py_None; } PY_STANDARD_CATCH return NULL; } PyObject* JPypeJavaArray::getArrayLength(PyObject* self, PyObject* arg) { try { PyObject* arrayObject; JPyArg::parseTuple(arg, "O!", &PyCObject_Type, &arrayObject); JPArray* a = (JPArray*)JPyCObject::asVoidPtr(arrayObject); int res = a->getLength(); return JPyInt::fromLong(res); } PY_STANDARD_CATCH return NULL; } PyObject* JPypeJavaArray::getArrayItem(PyObject* self, PyObject* arg) { try { PyObject* arrayObject; int ndx; JPyArg::parseTuple(arg, "O!i", &PyCObject_Type, &arrayObject, &ndx); JPArray* a = (JPArray*)JPyCObject::asVoidPtr(arrayObject); HostRef* res = a->getItem(ndx); return detachRef(res); } PY_STANDARD_CATCH return NULL; } PyObject* JPypeJavaArray::getArraySlice(PyObject* self, PyObject* arg) { try { PyObject* arrayObject; int lo = -1; int hi = -1; JPyArg::parseTuple(arg, "O!ii", &PyCObject_Type, &arrayObject, &lo, &hi); JPArray* a = (JPArray*)JPyCObject::asVoidPtr(arrayObject); int length = a->getLength(); // stolen from jcc, to get nice slice support if (lo < 0) lo = length + lo; if (lo < 0) lo = 0; else if (lo > length) lo = length; if (hi < 0) hi = length + hi; if (hi < 0) hi = 0; else if (hi > length) hi = length; if (lo > hi) lo = hi; const string& name = a->getType()->getObjectType().getComponentName().getNativeName(); switch(name[0]) { // for primitive types, we have fast sequence generation available case 'B': case 'S': case 'I': case 'J': case 'F': case 'D': case 'Z': case 'C': // fast return a->getSequenceFromRange(lo, hi); default: { // horrible slow vector<HostRef*> values = a->getRange(lo, hi); JPCleaner cleaner; PyObject* res = JPySequence::newList((int)values.size()); for (unsigned int i = 0; i < values.size(); i++) { JPySequence::setItem(res, i, (PyObject*)values[i]->data()); cleaner.add(values[i]); } return res; } } } PY_STANDARD_CATCH return NULL; } PyObject* JPypeJavaArray::setArraySlice(PyObject* self, PyObject* arg) { try { PyObject* arrayObject; int ndx = -1; int ndx2 = -1; PyObject* val; JPyArg::parseTuple(arg, "O!iiO", &PyCObject_Type, &arrayObject, &ndx, &ndx2, &val); JPArray* a = (JPArray*)JPyCObject::asVoidPtr(arrayObject); Py_ssize_t len = JPyObject::length(val); vector<HostRef*> values; JPCleaner cleaner; for (Py_ssize_t i = 0; i < len; i++) { HostRef* v = new HostRef(JPySequence::getItem(val, i), false); values.push_back(v); cleaner.add(v); } a->setRange(ndx, ndx2, values); Py_INCREF(Py_None); return Py_None; } PY_STANDARD_CATCH return NULL; } PyObject* JPypeJavaArray::setArrayItem(PyObject* self, PyObject* arg) { try { PyObject* arrayObject; int ndx; PyObject* value; JPyArg::parseTuple(arg, "O!iO", &PyCObject_Type, &arrayObject, &ndx, &value); JPArray* a = (JPArray*)JPyCObject::asVoidPtr(arrayObject); JPCleaner cleaner; HostRef* v = new HostRef(value); cleaner.add(v); a->setItem(ndx, v); Py_INCREF(Py_None); return Py_None; } PY_STANDARD_CATCH return NULL; } PyObject* JPypeJavaArray::newArray(PyObject* self, PyObject* arg) { try { PyObject* arrayObject; int sz; JPyArg::parseTuple(arg, "O!i", &PyCObject_Type, &arrayObject, &sz); JPArrayClass* a = (JPArrayClass*)JPyCObject::asVoidPtr(arrayObject); JPArray* v = a->newInstance(sz); PyObject* res = JPyCObject::fromVoidAndDesc(v, (void*)"JPArray", PythonHostEnvironment::deleteJPArrayDestructor); return res; } PY_STANDARD_CATCH return NULL; } PyObject* JPypeJavaArray::setArrayValues(PyObject* self, PyObject* arg) { try { PyObject* arrayObject; PyObject* values; JPyArg::parseTuple(arg, "O!O", &PyCObject_Type, &arrayObject, &values); JPArray* a = (JPArray*)JPyCObject::asVoidPtr(arrayObject); JPArrayClass* arrayClass = a->getClass(); HostRef valuesRef(values); JPCleaner cleaner; jarray arr = (jarray)a->getObject(); cleaner.addLocal(arr); arrayClass->getComponentType()->setArrayValues(arr, &valuesRef); Py_INCREF(Py_None); return Py_None; } PY_STANDARD_CATCH return NULL; } <commit_msg>impl setArraySlice with distinction for primitive types<commit_after>/***************************************************************************** Copyright 2004-2008 Steve Menard Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *****************************************************************************/ #include <jpype_python.h> namespace { // impl detail inline bool is_primitive(char t) { switch(t) { case 'B': case 'S': case 'I': case 'J': case 'F': case 'D': case 'Z': case 'C': return true; default: return false; } } } PyObject* JPypeJavaArray::findArrayClass(PyObject* obj, PyObject* args) { try { char* cname; JPyArg::parseTuple(args, "s", &cname); JPTypeName name = JPTypeName::fromSimple(cname); JPArrayClass* claz = JPTypeManager::findArrayClass(name); if (claz == NULL) { Py_INCREF(Py_None); return Py_None; } PyObject* res = JPyCObject::fromVoidAndDesc((void*)claz, (void*)"jclass", NULL); return res; } PY_STANDARD_CATCH; PyErr_Clear(); Py_INCREF(Py_None); return Py_None; } PyObject* JPypeJavaArray::setJavaArrayClass(PyObject* self, PyObject* arg) { try { PyObject* t; JPyArg::parseTuple(arg, "O", &t); hostEnv->setJavaArrayClass(t); Py_INCREF(Py_None); return Py_None; } PY_STANDARD_CATCH return NULL; } PyObject* JPypeJavaArray::setGetJavaArrayClassMethod(PyObject* self, PyObject* arg) { try { PyObject* t; JPyArg::parseTuple(arg, "O", &t); hostEnv->setGetJavaArrayClassMethod(t); Py_INCREF(Py_None); return Py_None; } PY_STANDARD_CATCH return NULL; } PyObject* JPypeJavaArray::getArrayLength(PyObject* self, PyObject* arg) { try { PyObject* arrayObject; JPyArg::parseTuple(arg, "O!", &PyCObject_Type, &arrayObject); JPArray* a = (JPArray*)JPyCObject::asVoidPtr(arrayObject); int res = a->getLength(); return JPyInt::fromLong(res); } PY_STANDARD_CATCH return NULL; } PyObject* JPypeJavaArray::getArrayItem(PyObject* self, PyObject* arg) { try { PyObject* arrayObject; int ndx; JPyArg::parseTuple(arg, "O!i", &PyCObject_Type, &arrayObject, &ndx); JPArray* a = (JPArray*)JPyCObject::asVoidPtr(arrayObject); HostRef* res = a->getItem(ndx); return detachRef(res); } PY_STANDARD_CATCH return NULL; } PyObject* JPypeJavaArray::getArraySlice(PyObject* self, PyObject* arg) { PyObject* arrayObject; int lo = -1; int hi = -1; try { JPyArg::parseTuple(arg, "O!ii", &PyCObject_Type, &arrayObject, &lo, &hi); JPArray* a = (JPArray*)JPyCObject::asVoidPtr(arrayObject); int length = a->getLength(); // stolen from jcc, to get nice slice support if (lo < 0) lo = length + lo; if (lo < 0) lo = 0; else if (lo > length) lo = length; if (hi < 0) hi = length + hi; if (hi < 0) hi = 0; else if (hi > length) hi = length; if (lo > hi) lo = hi; const string& name = a->getType()->getObjectType().getComponentName().getNativeName(); if(is_primitive(name[0])) { // for primitive types, we have fast sequence generation available return a->getSequenceFromRange(lo, hi); } else { // slow wrapped access for non primitives vector<HostRef*> values = a->getRange(lo, hi); JPCleaner cleaner; PyObject* res = JPySequence::newList((int)values.size()); for (unsigned int i = 0; i < values.size(); i++) { JPySequence::setItem(res, i, (PyObject*)values[i]->data()); cleaner.add(values[i]); } return res; } } PY_STANDARD_CATCH return NULL; } PyObject* JPypeJavaArray::setArraySlice(PyObject* self, PyObject* arg) { PyObject* arrayObject; int lo = -1; int hi = -1; PyObject* sequence; try { JPyArg::parseTuple(arg, "O!iiO", &PyCObject_Type, &arrayObject, &lo, &hi, &sequence); JPArray* a = (JPArray*)JPyCObject::asVoidPtr(arrayObject); Py_ssize_t length = a->getLength(); if (lo < 0) lo = length + lo; if (lo < 0) lo = 0; else if (lo > length) lo = length; if (hi < 0) hi = length + hi; if (hi < 0) hi = 0; else if (hi > length) hi = length; if (lo > hi) lo = hi; const string& name = a->getType()->getObjectType().getComponentName().getNativeName(); if(is_primitive(name[0])) { // for primitive types, we have fast setters available a->setRange(lo, hi, sequence); } else { // slow wrapped access for non primitive types vector<HostRef*> values; values.reserve(hi - lo); JPCleaner cleaner; for (Py_ssize_t i = 0; i < hi - lo; i++) { HostRef* v = new HostRef(JPySequence::getItem(sequence, i), false); values.push_back(v); cleaner.add(v); } a->setRange(lo, hi, values); } Py_RETURN_NONE; } PY_STANDARD_CATCH return NULL; } PyObject* JPypeJavaArray::setArrayItem(PyObject* self, PyObject* arg) { try { PyObject* arrayObject; int ndx; PyObject* value; JPyArg::parseTuple(arg, "O!iO", &PyCObject_Type, &arrayObject, &ndx, &value); JPArray* a = (JPArray*)JPyCObject::asVoidPtr(arrayObject); JPCleaner cleaner; HostRef* v = new HostRef(value); cleaner.add(v); a->setItem(ndx, v); Py_INCREF(Py_None); return Py_None; } PY_STANDARD_CATCH return NULL; } PyObject* JPypeJavaArray::newArray(PyObject* self, PyObject* arg) { try { PyObject* arrayObject; int sz; JPyArg::parseTuple(arg, "O!i", &PyCObject_Type, &arrayObject, &sz); JPArrayClass* a = (JPArrayClass*)JPyCObject::asVoidPtr(arrayObject); JPArray* v = a->newInstance(sz); PyObject* res = JPyCObject::fromVoidAndDesc(v, (void*)"JPArray", PythonHostEnvironment::deleteJPArrayDestructor); return res; } PY_STANDARD_CATCH return NULL; } PyObject* JPypeJavaArray::setArrayValues(PyObject* self, PyObject* arg) { try { PyObject* arrayObject; PyObject* values; JPyArg::parseTuple(arg, "O!O", &PyCObject_Type, &arrayObject, &values); JPArray* a = (JPArray*)JPyCObject::asVoidPtr(arrayObject); JPArrayClass* arrayClass = a->getClass(); HostRef valuesRef(values); JPCleaner cleaner; jarray arr = (jarray)a->getObject(); cleaner.addLocal(arr); arrayClass->getComponentType()->setArrayValues(arr, &valuesRef); Py_INCREF(Py_None); return Py_None; } PY_STANDARD_CATCH return NULL; } <|endoftext|>
<commit_before>#include "audiocapturefilter.h" #include "audiocapturedevice.h" #include "statisticsinterface.h" #include "common.h" #include <QAudioInput> #include <QDebug> #include <QTime> #include <QSettings> #include <QRegularExpression> const int AUDIO_BUFFER_SIZE = 65536; AudioCaptureFilter::AudioCaptureFilter(QString id, QAudioFormat format, StatisticsInterface *stats) : Filter(id, "Audio_Capture", stats, NONE, RAWAUDIO), deviceInfo_(), device_(nullptr), format_(format), audioInput_(nullptr), input_(nullptr), buffer_(AUDIO_BUFFER_SIZE, 0) {} AudioCaptureFilter::~AudioCaptureFilter(){} bool AudioCaptureFilter::init() { printNormal(this, "Initializing audio capture filter."); QList<QAudioDeviceInfo> microphones = QAudioDeviceInfo::availableDevices(QAudio::AudioInput); if (microphones.empty()) { printWarning(this, "No microphone detected!"); return false; } QSettings settings("kvazzup.ini", QSettings::IniFormat); QString deviceName = settings.value("audio/Device").toString(); int deviceID = settings.value("audio/DeviceID").toInt(); if (deviceID < microphones.size()) { QString parsedName = microphones[deviceID].deviceName(); // take only the device name from: "Microphone (device name)" QRegularExpression re_mic (".*\\((.+)\\).*"); QRegularExpressionMatch mic_match = re_mic.match(microphones[deviceID].deviceName()); if (mic_match.hasMatch() && mic_match.lastCapturedIndex() == 1) { // parsed extra text succesfully parsedName = mic_match.captured(1); } // if the device has changed between recording the settings and now. if (parsedName != deviceName) { // search for device with same name for(int i = 0; i < microphones.size(); ++i) { if(parsedName == deviceName) { qDebug() << "Found mic with name:" << microphones.at(i).deviceName() << "and id:" << i; deviceID = i; break; } } // previous camera could not be found, use first. qDebug() << "Did not find microphone name:" << deviceName << " Using first"; deviceID = 0; } } deviceInfo_ = microphones.at(deviceID); QAudioDeviceInfo info(deviceInfo_); printDebug(DEBUG_NORMAL, this, "", {"Chosen Device"}, {info.deviceName()}); if (!info.isFormatSupported(format_)) { printDebug(DEBUG_WARNING, this, "Default audio format not supported - trying to use nearest"); format_ = info.nearestFormat(format_); } if(format_.sampleRate() != -1) getStats()->audioInfo(format_.sampleRate(), format_.channelCount()); else getStats()->audioInfo(0, 0); if (device_) delete device_; device_ = new AudioCaptureDevice(format_, this); createAudioInput(); printDebug(DEBUG_NORMAL, this, "Audio initializing completed."); return true; } void AudioCaptureFilter::createAudioInput() { qDebug() << "Iniating," << metaObject()->className() << ": Creating audio input"; audioInput_ = new QAudioInput(deviceInfo_, format_, this); if (device_) device_->start(); if (audioInput_) input_ = audioInput_->start(); if (input_) connect(input_, SIGNAL(readyRead()), SLOT(readMore())); } void AudioCaptureFilter::readMore() { if (!audioInput_) { printDebug(DEBUG_WARNING, this, "No audio input in readMore"); return; } qint64 len = audioInput_->bytesReady(); if (len > AUDIO_BUFFER_SIZE) { len = AUDIO_BUFFER_SIZE; } quint64 l = 0; if (input_) l = input_->read(buffer_.data(), len); if (l > 0 && device_) { device_->write(buffer_.constData(), l); Data* newSample = new Data; // create audio data packet to be sent to filter graph timeval present_time; present_time.tv_sec = QDateTime::currentMSecsSinceEpoch()/1000; present_time.tv_usec = (QDateTime::currentMSecsSinceEpoch()%1000) * 1000; newSample->presentationTime = present_time; newSample->type = RAWAUDIO; newSample->data = std::unique_ptr<uint8_t[]>(new uint8_t[len]); memcpy(newSample->data.get(), buffer_.constData(), len); newSample->data_size = len; newSample->width = 0; newSample->height = 0; newSample->source = LOCAL; newSample->framerate = format_.sampleRate(); std::unique_ptr<Data> u_newSample( newSample ); sendOutput(std::move(u_newSample)); //qDebug() << "Audio capture: Generated sample with size:" << l; } } void AudioCaptureFilter::start() { qDebug() << "Audio," << metaObject()->className() << ": Resuming audio input."; if (audioInput_ && (audioInput_->state() == QAudio::SuspendedState || audioInput_->state() == QAudio::StoppedState)) { audioInput_->resume(); } } void AudioCaptureFilter::stop() { qDebug() << "Audio," << metaObject()->className() << ": Suspending input."; if (audioInput_ && audioInput_->state() == QAudio::ActiveState) { audioInput_->suspend(); } // just in case the filter part was running Filter::stop(); qDebug() << "Audio," << metaObject()->className() << ": input suspended."; } // changing of audio device mid stream. void AudioCaptureFilter::updateSettings() { printNormal(this, "Updating audio settings"); if (device_) device_->stop(); if (audioInput_) { audioInput_->stop(); audioInput_->disconnect(this); delete audioInput_; } init(); } void AudioCaptureFilter::volumeChanged(int value) { if(audioInput_) { audioInput_->setVolume(qreal(value) / 100); } } void AudioCaptureFilter::process() {} <commit_msg>feature(Processing): Try default audioinputdevice even if no devices was found.<commit_after>#include "audiocapturefilter.h" #include "audiocapturedevice.h" #include "statisticsinterface.h" #include "common.h" #include <QAudioInput> #include <QDebug> #include <QTime> #include <QSettings> #include <QRegularExpression> const int AUDIO_BUFFER_SIZE = 65536; AudioCaptureFilter::AudioCaptureFilter(QString id, QAudioFormat format, StatisticsInterface *stats) : Filter(id, "Audio_Capture", stats, NONE, RAWAUDIO), deviceInfo_(), device_(nullptr), format_(format), audioInput_(nullptr), input_(nullptr), buffer_(AUDIO_BUFFER_SIZE, 0) {} AudioCaptureFilter::~AudioCaptureFilter(){} bool AudioCaptureFilter::init() { printNormal(this, "Initializing audio capture filter."); QList<QAudioDeviceInfo> microphones = QAudioDeviceInfo::availableDevices(QAudio::AudioInput); if (!microphones.empty()) { QSettings settings("kvazzup.ini", QSettings::IniFormat); QString deviceName = settings.value("audio/Device").toString(); int deviceID = settings.value("audio/DeviceID").toInt(); if (deviceID < microphones.size()) { QString parsedName = microphones[deviceID].deviceName(); // take only the device name from: "Microphone (device name)" QRegularExpression re_mic (".*\\((.+)\\).*"); QRegularExpressionMatch mic_match = re_mic.match(microphones[deviceID].deviceName()); if (mic_match.hasMatch() && mic_match.lastCapturedIndex() == 1) { // parsed extra text succesfully parsedName = mic_match.captured(1); } // if the device has changed between recording the settings and now. if (parsedName != deviceName) { // search for device with same name for(int i = 0; i < microphones.size(); ++i) { if(parsedName == deviceName) { qDebug() << "Found mic with name:" << microphones.at(i).deviceName() << "and id:" << i; deviceID = i; break; } } // previous camera could not be found, use first. qDebug() << "Did not find microphone name:" << deviceName << " Using first"; deviceID = 0; } } deviceInfo_ = microphones.at(deviceID); } else { printWarning(this, "No available microphones found. Trying default"); deviceInfo_ = QAudioDeviceInfo::defaultInputDevice(); } QAudioDeviceInfo info(deviceInfo_); printDebug(DEBUG_NORMAL, this, "", {"Chosen Device"}, {info.deviceName()}); if (!info.isFormatSupported(format_)) { printDebug(DEBUG_WARNING, this, "Default audio format not supported - trying to use nearest"); format_ = info.nearestFormat(format_); } if(format_.sampleRate() != -1) getStats()->audioInfo(format_.sampleRate(), format_.channelCount()); else getStats()->audioInfo(0, 0); if (device_) delete device_; device_ = new AudioCaptureDevice(format_, this); createAudioInput(); printNormal(this, "Audio initializing completed."); return true; } void AudioCaptureFilter::createAudioInput() { qDebug() << "Iniating," << metaObject()->className() << ": Creating audio input"; audioInput_ = new QAudioInput(deviceInfo_, format_, this); if (device_) device_->start(); if (audioInput_) input_ = audioInput_->start(); if (input_) connect(input_, SIGNAL(readyRead()), SLOT(readMore())); } void AudioCaptureFilter::readMore() { if (!audioInput_) { printDebug(DEBUG_WARNING, this, "No audio input in readMore"); return; } qint64 len = audioInput_->bytesReady(); if (len > AUDIO_BUFFER_SIZE) { len = AUDIO_BUFFER_SIZE; } quint64 l = 0; if (input_) l = input_->read(buffer_.data(), len); if (l > 0 && device_) { device_->write(buffer_.constData(), l); Data* newSample = new Data; // create audio data packet to be sent to filter graph timeval present_time; present_time.tv_sec = QDateTime::currentMSecsSinceEpoch()/1000; present_time.tv_usec = (QDateTime::currentMSecsSinceEpoch()%1000) * 1000; newSample->presentationTime = present_time; newSample->type = RAWAUDIO; newSample->data = std::unique_ptr<uint8_t[]>(new uint8_t[len]); memcpy(newSample->data.get(), buffer_.constData(), len); newSample->data_size = len; newSample->width = 0; newSample->height = 0; newSample->source = LOCAL; newSample->framerate = format_.sampleRate(); std::unique_ptr<Data> u_newSample( newSample ); sendOutput(std::move(u_newSample)); //qDebug() << "Audio capture: Generated sample with size:" << l; } } void AudioCaptureFilter::start() { qDebug() << "Audio," << metaObject()->className() << ": Resuming audio input."; if (audioInput_ && (audioInput_->state() == QAudio::SuspendedState || audioInput_->state() == QAudio::StoppedState)) { audioInput_->resume(); } } void AudioCaptureFilter::stop() { qDebug() << "Audio," << metaObject()->className() << ": Suspending input."; if (audioInput_ && audioInput_->state() == QAudio::ActiveState) { audioInput_->suspend(); } // just in case the filter part was running Filter::stop(); qDebug() << "Audio," << metaObject()->className() << ": input suspended."; } // changing of audio device mid stream. void AudioCaptureFilter::updateSettings() { printNormal(this, "Updating audio settings"); if (device_) device_->stop(); if (audioInput_) { audioInput_->stop(); audioInput_->disconnect(this); delete audioInput_; } init(); } void AudioCaptureFilter::volumeChanged(int value) { if(audioInput_) { audioInput_->setVolume(qreal(value) / 100); } } void AudioCaptureFilter::process() {} <|endoftext|>
<commit_before>// Copyright (c) 2017 Sony Corporation. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <algorithm> #include <cmath> #include <limits> #include <nbla/solver/adabelief.hpp> #include <nbla/solver/clip_grad.hpp> #include <nbla/solver/mixed_precision_training.hpp> #include <nbla/solver/weight_decay.hpp> namespace nbla { using std::make_shared; using std::shared_ptr; NBLA_REGISTER_SOLVER_SOURCE(AdaBelief, float, float, float, float, bool, bool, bool, bool); template <typename T> AdaBelief<T>::AdaBelief(const Context &ctx, float alpha, float beta1, float beta2, float eps, bool amsgrad, bool weight_decouple, bool fixed_decay, bool rectify) : Solver(ctx), alpha_(alpha), beta1_(beta1), beta2_(beta2), eps_(eps), amsgrad_(amsgrad), weight_decouple_(weight_decouple), fixed_decay_(fixed_decay), rectify_(rectify) {} template <typename T> AdaBelief<T>::~AdaBelief() {} template <typename T> void AdaBelief<T>::set_state_impl(const string &key, VariablePtr param) { // Implement here } template <typename T> void AdaBelief<T>::remove_state_impl(const string &key) { // Implement here } template <typename T> void AdaBelief<T>::update_impl(const string &key, VariablePtr param) { // Implement here } NBLA_DEF_WEIGHT_DECAY(AdaBelief, weight_decay_cpu); NBLA_DEF_CLIP_GRAD_BY_NORM(AdaBelief, clip_grad_by_norm_cpu); NBLA_DEF_CHECK_INF_GRAD(AdaBelief, check_inf_grad_cpu); NBLA_DEF_CHECK_NAN_GRAD(AdaBelief, check_nan_grad_cpu); NBLA_DEF_CHECK_INF_OR_NAN_GRAD(AdaBelief, check_inf_or_nan_grad_cpu); NBLA_DEF_SCALE_GRAD(AdaBelief, scale_grad_impl_cpu); } <commit_msg>Add adabelief solver .cpp code<commit_after>// Copyright (c) 2017 Sony Corporation. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <algorithm> #include <cmath> #include <limits> #include <nbla/solver/adabelief.hpp> #include <nbla/solver/clip_grad.hpp> #include <nbla/solver/mixed_precision_training.hpp> #include <nbla/solver/weight_decay.hpp> namespace nbla { using std::make_shared; using std::shared_ptr; NBLA_REGISTER_SOLVER_SOURCE(AdaBelief, float, float, float, float, float, bool, bool, bool, bool); template <typename T> AdaBelief<T>::AdaBelief(const Context &ctx, float alpha, float beta1, float beta2, float eps, float wd, bool amsgrad, bool weight_decouple, bool fixed_decay, bool rectify) : Solver(ctx), alpha_(alpha), beta1_(beta1), beta2_(beta2), eps_(eps), wd_(wd), amsgrad_(amsgrad), weight_decouple_(weight_decouple), fixed_decay_(fixed_decay), rectify_(rectify) {} template <typename T> AdaBelief<T>::~AdaBelief() {} template <typename T> void AdaBelief<T>::set_state_impl(const string &key, VariablePtr param) { auto shape = param->shape(); auto m = make_shared<Variable>(shape); auto s = make_shared<Variable>(shape); auto max_s = make_shared<Variable>(shape); m->data()->zero(); s->data()->zero(); max_s->data()->zero(); unordered_map<string, VariablePtr> pstate{ {"mean", m}, {"sqr_var", s}, {"max_sqr_var", max_s}}; SolverState state{pstate, 0}; states_.insert({key, state}); } template <typename T> void AdaBelief<T>::remove_state_impl(const string &key) { states_.erase(key); } template <typename T> void AdaBelief<T>::update_impl(const string &key, VariablePtr param) { Size_t size = param->size(); auto &state = states_.at(key); auto &t = state.t; const T *g = param->get_grad_pointer<T>(this->ctx_); VariablePtr s1 = state.pstate["mean"]; VariablePtr s2 = state.pstate["sqr_var"]; VariablePtr s3 = state.pstate["max_sqr_var"]; T *m = s1->cast_data_and_get_pointer<T>(this->ctx_); T *s = s2->cast_data_and_get_pointer<T>(this->ctx_); T *max_s = s3->cast_data_and_get_pointer<T>(this->ctx_); T *theta = param->cast_data_and_get_pointer<T>(this->ctx_); t = std::min(t + 1, std::numeric_limits<uint32_t>::max() - 1); const T beta1_t = std::pow(beta1_, t); const T beta2_t = std::pow(beta2_, t); const T bias_correction = std::sqrt(1 - beta2_t) / (1 - beta1_t); T alpha_t = alpha_ * bias_correction; bool update_in_sgd_style = false; if (rectify_) { const T rho_inf = 2 / (1 - beta2_) - 1; const T rho_t = rho_inf - 2 * t * std::pow(beta2_, t) / (1 - std::pow(beta2_, t)); if (rho_t > 4.0) { const T rt = std::sqrt((rho_t - 4) * (rho_t - 2) * rho_inf / (rho_inf - 4) / (rho_inf - 2) / rho_t); alpha_t = rt * alpha_t; } else { alpha_t = alpha_; update_in_sgd_style = true; } } for (int i = 0; i < size; ++i) { m[i] = beta1_ * m[i] + (1 - beta1_) * g[i]; s[i] = beta2_ * s[i] + (1 - beta2_) * std::pow(g[i] - m[i], 2); T denom = std::sqrt(s[i] + eps_); if (amsgrad_) { max_s[i] = std::max(s[i], max_s[i]); denom = std::sqrt(max_s[i] + eps_); } if (weight_decouple_) { if (fixed_decay_) { theta[i] = theta[i] - theta[i] * wd_; } else { theta[i] = theta[i] - theta[i] * wd_ * alpha_; } } if (update_in_sgd_style) { theta[i] = theta[i] - alpha_t * m[i]; } else { theta[i] = theta[i] - alpha_t * m[i] / denom; } } } NBLA_DEF_WEIGHT_DECAY(AdaBelief, weight_decay_cpu); NBLA_DEF_CLIP_GRAD_BY_NORM(AdaBelief, clip_grad_by_norm_cpu); NBLA_DEF_CHECK_INF_GRAD(AdaBelief, check_inf_grad_cpu); NBLA_DEF_CHECK_NAN_GRAD(AdaBelief, check_nan_grad_cpu); NBLA_DEF_CHECK_INF_OR_NAN_GRAD(AdaBelief, check_inf_or_nan_grad_cpu); NBLA_DEF_SCALE_GRAD(AdaBelief, scale_grad_impl_cpu); } // namespace nbla <|endoftext|>
<commit_before>/** * Copyright 2016-2017 MICRORISC s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "LaunchUtils.h" #include "BaseService.h" #include "DpaTransactionTask.h" #include "DpaRaw.h" #include "IDaemon.h" #include "IqrfLogging.h" INIT_COMPONENT(IService, BaseService) BaseService::BaseService(const std::string & name) :m_name(name) , m_messaging(nullptr) , m_daemon(nullptr) { } BaseService::~BaseService() { } void BaseService::setDaemon(IDaemon* daemon) { m_daemon = daemon; } void BaseService::setSerializer(ISerializer* serializer) { m_serializerVect.push_back(serializer); } void BaseService::setMessaging(IMessaging* messaging) { m_messaging = messaging; m_messaging->registerMessageHandler([&](const ustring& msg) { handleMsgFromMessaging(msg); }); } void BaseService::update(const rapidjson::Value& cfg) { TRC_ENTER(""); m_asyncDpaMessage = jutils::getPossibleMemberAs<bool>("AsyncDpaMessage", cfg, m_asyncDpaMessage); TRC_LEAVE(""); } void BaseService::start() { TRC_ENTER(""); m_daemon->getScheduler()->registerMessageHandler(m_name, [&](const std::string& msg) { ustring msgu((unsigned char*)msg.data(), msg.size()); handleMsgFromMessaging(msgu); }); if (m_asyncDpaMessage) { TRC_INF("Set AsyncDpaMessageHandler :" << PAR(m_name)); m_daemon->registerAsyncMessageHandler(m_name, [&](const DpaMessage& dpaMessage) { handleAsyncDpaMessage(dpaMessage); }); } TRC_INF("BaseService :" << PAR(m_name) << " started"); TRC_LEAVE(""); } void BaseService::stop() { TRC_ENTER(""); m_daemon->getScheduler()->unregisterMessageHandler(m_name); TRC_INF("BaseService :" << PAR(m_name) << " stopped"); TRC_LEAVE(""); } void BaseService::handleMsgFromMessaging(const ustring& msg) { TRC_DBG("==================================" << std::endl << "Received from MESSAGING: " << std::endl << FORM_HEX(msg.data(), msg.size())); //to encode output message std::ostringstream os; //get input message std::string msgs((const char*)msg.data(), msg.size()); std::istringstream is(msgs); std::unique_ptr<DpaTask> dpaTask; std::string command; //parse bool handled = false; std::string ctype; std::string lastError = "Unknown ctype"; for (auto ser : m_serializerVect) { ctype = ser->parseCategory(msgs); if (ctype == CAT_DPA_STR) { dpaTask = ser->parseRequest(msgs); if (dpaTask) { DpaTransactionTask trans(*dpaTask); m_daemon->executeDpaTransaction(trans); int result = trans.waitFinish(); os << dpaTask->encodeResponse(trans.getErrorStr()); //TODO //just stupid hack for test async - remove it /////// //handleAsyncDpaMessage(dpaTask->getResponse()); //handleAsyncDpaMessage(dpaTask->getRequest()); /////// lastError = ser->getLastError(); handled = true; break; } } else if (ctype == CAT_CONF_STR) { command = ser->parseConfig(msgs); if (!command.empty()) { std::string response = m_daemon->doCommand(command); lastError = ser->getLastError(); os << ser->encodeConfig(msgs, response); handled = true; break; } } } if (!handled) { os << "PARSE ERROR: " << PAR(ctype) << PAR(lastError); } ustring msgu((unsigned char*)os.str().data(), os.str().size()); m_messaging->sendMessage(msgu); } void BaseService::handleAsyncDpaMessage(const DpaMessage& dpaMessage) { //TRC_ENTER(""); std::string sr = m_serializerVect[0]->encodeAsyncAsDpaRaw(dpaMessage); ustring msgu((unsigned char*)sr.data(), sr.size()); m_messaging->sendMessage(msgu); //TRC_LEAVE(""); } <commit_msg>Fix misleading report JsonDpaRequest parse error<commit_after>/** * Copyright 2016-2017 MICRORISC s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "LaunchUtils.h" #include "BaseService.h" #include "DpaTransactionTask.h" #include "DpaRaw.h" #include "IDaemon.h" #include "IqrfLogging.h" INIT_COMPONENT(IService, BaseService) BaseService::BaseService(const std::string & name) :m_name(name) , m_messaging(nullptr) , m_daemon(nullptr) { } BaseService::~BaseService() { } void BaseService::setDaemon(IDaemon* daemon) { m_daemon = daemon; } void BaseService::setSerializer(ISerializer* serializer) { m_serializerVect.push_back(serializer); } void BaseService::setMessaging(IMessaging* messaging) { m_messaging = messaging; m_messaging->registerMessageHandler([&](const ustring& msg) { handleMsgFromMessaging(msg); }); } void BaseService::update(const rapidjson::Value& cfg) { TRC_ENTER(""); m_asyncDpaMessage = jutils::getPossibleMemberAs<bool>("AsyncDpaMessage", cfg, m_asyncDpaMessage); TRC_LEAVE(""); } void BaseService::start() { TRC_ENTER(""); m_daemon->getScheduler()->registerMessageHandler(m_name, [&](const std::string& msg) { ustring msgu((unsigned char*)msg.data(), msg.size()); handleMsgFromMessaging(msgu); }); if (m_asyncDpaMessage) { TRC_INF("Set AsyncDpaMessageHandler :" << PAR(m_name)); m_daemon->registerAsyncMessageHandler(m_name, [&](const DpaMessage& dpaMessage) { handleAsyncDpaMessage(dpaMessage); }); } TRC_INF("BaseService :" << PAR(m_name) << " started"); TRC_LEAVE(""); } void BaseService::stop() { TRC_ENTER(""); m_daemon->getScheduler()->unregisterMessageHandler(m_name); TRC_INF("BaseService :" << PAR(m_name) << " stopped"); TRC_LEAVE(""); } void BaseService::handleMsgFromMessaging(const ustring& msg) { TRC_DBG("==================================" << std::endl << "Received from MESSAGING: " << std::endl << FORM_HEX(msg.data(), msg.size())); //to encode output message std::ostringstream os; //get input message std::string msgs((const char*)msg.data(), msg.size()); std::istringstream is(msgs); std::unique_ptr<DpaTask> dpaTask; std::string command; //parse bool handled = false; std::string ctype; std::string lastError = "Unknown ctype"; for (auto ser : m_serializerVect) { ctype = ser->parseCategory(msgs); if (ctype == CAT_DPA_STR) { dpaTask = ser->parseRequest(msgs); if (dpaTask) { DpaTransactionTask trans(*dpaTask); m_daemon->executeDpaTransaction(trans); int result = trans.waitFinish(); os << dpaTask->encodeResponse(trans.getErrorStr()); //TODO //just stupid hack for test async - remove it /////// //handleAsyncDpaMessage(dpaTask->getResponse()); //handleAsyncDpaMessage(dpaTask->getRequest()); /////// handled = true; } lastError = ser->getLastError(); break; } else if (ctype == CAT_CONF_STR) { command = ser->parseConfig(msgs); if (!command.empty()) { std::string response = m_daemon->doCommand(command); lastError = ser->getLastError(); os << ser->encodeConfig(msgs, response); handled = true; } lastError = ser->getLastError(); break; } } if (!handled) { os << "PARSE ERROR: " << PAR(ctype) << PAR(lastError); } ustring msgu((unsigned char*)os.str().data(), os.str().size()); m_messaging->sendMessage(msgu); } void BaseService::handleAsyncDpaMessage(const DpaMessage& dpaMessage) { //TRC_ENTER(""); std::string sr = m_serializerVect[0]->encodeAsyncAsDpaRaw(dpaMessage); ustring msgu((unsigned char*)sr.data(), sr.size()); m_messaging->sendMessage(msgu); //TRC_LEAVE(""); } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: fieldmappingpage.hxx,v $ * * $Revision: 1.6 $ * * last change: $Author: kz $ $Date: 2008-03-06 18:38:33 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef EXTENSIONS_ABP_FIELDMAPPINGPAGE_HXX #define EXTENSIONS_ABP_FIELDMAPPINGPAGE_HXX #ifndef EXTENSIONS_ABP_ABSPAGE_HXX #include "abspage.hxx" #endif //......................................................................... namespace abp { //......................................................................... //===================================================================== //= FieldMappingPage //===================================================================== class FieldMappingPage : public AddressBookSourcePage { protected: FixedText m_aExplanation; PushButton m_aInvokeDialog; FixedText m_aHint; public: FieldMappingPage( OAddessBookSourcePilot* _pParent ); protected: // OWizardPage overridables virtual void initializePage(); // TabDialog overridables virtual void ActivatePage(); virtual void DeactivatePage(); private: DECL_LINK( OnInvokeDialog, void* ); void implUpdateHint(); }; //......................................................................... } // namespace abp //......................................................................... #endif // EXTENSIONS_ABP_FIELDMAPPINGPAGE_HXX <commit_msg>INTEGRATION: CWS changefileheader (1.6.14); FILE MERGED 2008/04/01 12:29:40 thb 1.6.14.2: #i85898# Stripping all external header guards 2008/03/31 12:31:20 rt 1.6.14.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: fieldmappingpage.hxx,v $ * $Revision: 1.7 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifndef EXTENSIONS_ABP_FIELDMAPPINGPAGE_HXX #define EXTENSIONS_ABP_FIELDMAPPINGPAGE_HXX #include "abspage.hxx" //......................................................................... namespace abp { //......................................................................... //===================================================================== //= FieldMappingPage //===================================================================== class FieldMappingPage : public AddressBookSourcePage { protected: FixedText m_aExplanation; PushButton m_aInvokeDialog; FixedText m_aHint; public: FieldMappingPage( OAddessBookSourcePilot* _pParent ); protected: // OWizardPage overridables virtual void initializePage(); // TabDialog overridables virtual void ActivatePage(); virtual void DeactivatePage(); private: DECL_LINK( OnInvokeDialog, void* ); void implUpdateHint(); }; //......................................................................... } // namespace abp //......................................................................... #endif // EXTENSIONS_ABP_FIELDMAPPINGPAGE_HXX <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: propertyeditor.hxx,v $ * * $Revision: 1.11 $ * * last change: $Author: rt $ $Date: 2005-09-08 20:24:37 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _EXTENSIONS_PROPCTRLR_PROPERTYEDITOR_HXX_ #define _EXTENSIONS_PROPCTRLR_PROPERTYEDITOR_HXX_ #ifndef _SV_TABCTRL_HXX #include <vcl/tabctrl.hxx> #endif #ifndef _EXTENSIONS_PROPCTRLR_PCRCOMMON_HXX_ #include "pcrcommon.hxx" #endif #include <map> //............................................................................ namespace pcr { //............................................................................ class IBrowserControl; class IPropertyLineListener; class OBrowserPage; struct OLineDescriptor; //======================================================================== //= OPropertyEditor //======================================================================== class OPropertyEditor : public Control { private: typedef ::std::map< ::rtl::OUString, sal_uInt16 > MapStringToPageId; struct HiddenPage { sal_uInt16 nPos; TabPage* pPage; HiddenPage() : nPos( 0 ), pPage( NULL ) { } HiddenPage( sal_uInt16 _nPos, TabPage* _pPage ) : nPos( _nPos ), pPage( _pPage ) { } }; private: TabControl m_aTabControl; IPropertyLineListener* m_pListener; sal_uInt16 m_nNextId; Link m_aPageActivationHandler; MapStringToPageId m_aPropertyPageIds; ::std::map< sal_uInt16, HiddenPage > m_aHiddenPages; protected: void Resize(); void GetFocus(); public: OPropertyEditor (Window* pParent, WinBits nWinStyle = WB_DIALOGCONTROL); ~OPropertyEditor(); sal_uInt16 CalcVisibleLines(); void EnableUpdate(); void DisableUpdate(); void SetLineListener(IPropertyLineListener *); void SetHelpId( sal_uInt32 nHelpId ); sal_uInt16 AppendPage( const String& r,sal_uInt32 nHelpId=0); void SetPage( sal_uInt16 ); void RemovePage(sal_uInt16 nID); sal_uInt16 GetCurPage(); void ClearAll(); void SetPropertyValue(const ::rtl::OUString & rEntryName, const ::rtl::OUString & rValue ); ::rtl::OUString GetPropertyValue(const ::rtl::OUString & rEntryName ) const; sal_uInt16 GetPropertyPos(const ::rtl::OUString& rEntryName ) const; IBrowserControl* GetPropertyControl( const ::rtl::OUString& rEntryName ); void EnablePropertyLine( const ::rtl::OUString& _rEntryName, bool _bEnable ); void EnablePropertyControls( const ::rtl::OUString& _rEntryName, bool _bEnableInput, bool _bEnablePrimaryButton, bool _bEnableSecondaryButton = false ); sal_Bool IsPropertyInputEnabled( const ::rtl::OUString& _rEntryName ) const; void ShowPropertyPage( sal_uInt16 _nPageId, bool _bShow ); sal_uInt16 InsertEntry( const OLineDescriptor&, sal_uInt16 nPos = EDITOR_LIST_APPEND, sal_uInt16 _nPageId = EDITOR_PAGE_CURRENT ); void RemoveEntry( const ::rtl::OUString& _rName ); void ChangeEntry( const OLineDescriptor& ); void SetFirstVisibleEntry(sal_uInt16 nPos); sal_uInt16 GetFirstVisibleEntry(); void SetSelectedEntry(sal_uInt16 nPos); sal_uInt16 GetSelectedEntry(); void setPageActivationHandler(const Link& _rHdl) { m_aPageActivationHandler = _rHdl; } Link getPageActivationHandler() const { return m_aPageActivationHandler; } // #95343# ------------------------------- sal_Int32 getMinimumWidth(); void CommitModified(); private: OBrowserPage* getPage( sal_uInt16& _rPageId ); const OBrowserPage* getPage( sal_uInt16& _rPageId ) const; OBrowserPage* getPage( const ::rtl::OUString& _rPropertyName ); const OBrowserPage* getPage( const ::rtl::OUString& _rPropertyName ) const; protected: DECL_LINK(OnPageDeactivate, TabControl*); DECL_LINK(OnPageActivate, TabControl*); }; //............................................................................ } // namespace pcr //............................................................................ #endif // _EXTENSIONS_PROPCTRLR_PROPERTYEDITOR_HXX_ <commit_msg>INTEGRATION: CWS pbrwuno (1.10.158); FILE MERGED 2005/10/05 07:07:28 fs 1.10.158.5: RESYNC: (1.10-1.11); FILE MERGED 2005/09/05 07:41:54 fs 1.10.158.4: #i53095# phase 3, part 1: introduced XPropertyControl and relatives, describing one control in the ObjectInspector, responsible for one property known issues: - rebuildPropertyUI can cause problems now: If the user clicks into the control for property A, which causes property B to be committed, which causes the UI for property A to be rebuilt, then this will crash currently. Reason: rebuildPropertyUI now synchronously replaces the VCL-Window of the rebuilt control, which is exactly the one which is still in some MouseButtonDown-handler. possible solutions: - see if rebuiltPropertyUI can be obsoleted - handlers should be able to just obtain the XPropertyControl from the PropertyUI, and re-initialize the control. Shouldn't they?` - make one of the steps in the chain (mouse-click, handler-call, rebuildPropertyUI-callback) asynchronous. 2005/08/18 12:44:34 fs 1.10.158.3: #i53095#, phase 2<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: propertyeditor.hxx,v $ * * $Revision: 1.12 $ * * last change: $Author: vg $ $Date: 2006-03-14 11:30:21 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _EXTENSIONS_PROPCTRLR_PROPERTYEDITOR_HXX_ #define _EXTENSIONS_PROPCTRLR_PROPERTYEDITOR_HXX_ #ifndef _EXTENSIONS_PROPCTRLR_PCRCOMMON_HXX_ #include "pcrcommon.hxx" #endif /** === begin UNO includes === **/ #ifndef _COM_SUN_STAR_INSPECTION_XPROPERTYCONTROL_HPP_ #include <com/sun/star/inspection/XPropertyControl.hpp> #endif /** === end UNO includes === **/ #ifndef _SV_TABCTRL_HXX #include <vcl/tabctrl.hxx> #endif #include <map> //............................................................................ namespace pcr { //............................................................................ class IPropertyLineListener; class OBrowserPage; struct OLineDescriptor; //======================================================================== //= OPropertyEditor //======================================================================== class OPropertyEditor : public Control { private: typedef ::std::map< ::rtl::OUString, sal_uInt16 > MapStringToPageId; struct HiddenPage { sal_uInt16 nPos; TabPage* pPage; HiddenPage() : nPos( 0 ), pPage( NULL ) { } HiddenPage( sal_uInt16 _nPos, TabPage* _pPage ) : nPos( _nPos ), pPage( _pPage ) { } }; private: TabControl m_aTabControl; IPropertyLineListener* m_pListener; sal_uInt16 m_nNextId; Link m_aPageActivationHandler; MapStringToPageId m_aPropertyPageIds; ::std::map< sal_uInt16, HiddenPage > m_aHiddenPages; protected: void Resize(); void GetFocus(); public: OPropertyEditor (Window* pParent, WinBits nWinStyle = WB_DIALOGCONTROL); ~OPropertyEditor(); sal_uInt16 CalcVisibleLines(); void EnableUpdate(); void DisableUpdate(); void SetLineListener(IPropertyLineListener *); void SetHelpId( sal_uInt32 nHelpId ); sal_uInt16 AppendPage( const String& r,sal_uInt32 nHelpId=0); void SetPage( sal_uInt16 ); void RemovePage(sal_uInt16 nID); sal_uInt16 GetCurPage(); void ClearAll(); void SetPropertyValue(const ::rtl::OUString& _rEntryName, const ::com::sun::star::uno::Any& _rValue ); ::com::sun::star::uno::Any GetPropertyValue(const ::rtl::OUString& rEntryName ) const; sal_uInt16 GetPropertyPos(const ::rtl::OUString& rEntryName ) const; ::com::sun::star::uno::Reference< ::com::sun::star::inspection::XPropertyControl > GetPropertyControl( const ::rtl::OUString& rEntryName ); void EnablePropertyLine( const ::rtl::OUString& _rEntryName, bool _bEnable ); void EnablePropertyControls( const ::rtl::OUString& _rEntryName, sal_Int16 _nControls, bool _bEnable ); sal_Bool IsPropertyInputEnabled( const ::rtl::OUString& _rEntryName ) const; void ShowPropertyPage( sal_uInt16 _nPageId, bool _bShow ); sal_uInt16 InsertEntry( const OLineDescriptor&, sal_uInt16 _nPageId, sal_uInt16 nPos = EDITOR_LIST_APPEND ); void RemoveEntry( const ::rtl::OUString& _rName ); void ChangeEntry( const OLineDescriptor& ); void setPageActivationHandler(const Link& _rHdl) { m_aPageActivationHandler = _rHdl; } Link getPageActivationHandler() const { return m_aPageActivationHandler; } // #95343# ------------------------------- sal_Int32 getMinimumWidth(); void CommitModified(); private: OBrowserPage* getPage( sal_uInt16& _rPageId ); const OBrowserPage* getPage( sal_uInt16& _rPageId ) const; OBrowserPage* getPage( const ::rtl::OUString& _rPropertyName ); const OBrowserPage* getPage( const ::rtl::OUString& _rPropertyName ) const; protected: DECL_LINK(OnPageDeactivate, TabControl*); DECL_LINK(OnPageActivate, TabControl*); }; //............................................................................ } // namespace pcr //............................................................................ #endif // _EXTENSIONS_PROPCTRLR_PROPERTYEDITOR_HXX_ <|endoftext|>
<commit_before>////////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2007-2016 musikcube team // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // * Neither the name of the author nor the names of other contributors may // be used to endorse or promote products derived from this software // without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // ////////////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "TransportWindow.h" #include <cursespp/Screen.h> #include <cursespp/Colors.h> #include <cursespp/Message.h> #include <cursespp/Text.h> #include <app/util/Duration.h> #include <core/debug.h> #include <core/library/LocalLibraryConstants.h> #include <boost/format.hpp> #include <boost/algorithm/string.hpp> #include <boost/chrono.hpp> #include <boost/lexical_cast.hpp> #include <algorithm> #include <memory> using namespace musik::core; using namespace musik::core::audio; using namespace musik::core::library; using namespace musik::core::db; using namespace musik::box; using namespace boost::chrono; using namespace cursespp; #define REFRESH_TRANSPORT_READOUT 1001 #define REFRESH_INTERVAL_MS 1000 #define DEFAULT_TIME -1.0f #define TIME_SLOP 3.0f #define DEBOUNCE_REFRESH(x) \ this->RemoveMessage(REFRESH_TRANSPORT_READOUT); \ this->PostMessage(REFRESH_TRANSPORT_READOUT, 0, 0, x); #define DEBOUNCE_REFRESH_AND_SYNC_TIME() \ this->lastTime = this->transport.Position(); \ DEBOUNCE_REFRESH(0) static std::string playingFormat = "playing $title from $album"; struct Token { enum Type { Normal, Placeholder }; static std::unique_ptr<Token> New(const std::string& value, Type type) { return std::unique_ptr<Token>(new Token(value, type)); } Token(const std::string& value, Type type) { this->value = value; this->type = type; } std::string value; Type type; }; typedef std::unique_ptr<Token> TokenPtr; typedef std::vector<TokenPtr> TokenList; /* tokenizes an input string that has $placeholder values */ void tokenize(const std::string& format, TokenList& tokens) { tokens.clear(); Token::Type type = Token::Normal; size_t i = 0; size_t start = 0; while (i < format.size()) { char c = format[i]; if ((type == Token::Placeholder && c == ' ') || (type == Token::Normal && c == '$')) { /* escape $ with $$ */ if (c == '$' && i < format.size() - 1 && format[i + 1] == '$') { i++; } else { if (i > start) { tokens.push_back(Token::New(format.substr(start, i - start), type)); } start = i; type = (c == ' ') ? Token::Normal : Token::Placeholder; } } ++i; } if (i > 0) { tokens.push_back(Token::New(format.substr(start, i - start), type)); } } /* writes the colorized formatted string to the specified window. accounts for utf8 characters and ellipsizing */ size_t writePlayingFormat( WINDOW *w, std::string title, std::string album, size_t width) { TokenList tokens; tokenize(playingFormat, tokens); int64 gb = COLOR_PAIR(CURSESPP_TEXT_ACTIVE); size_t remaining = width; auto it = tokens.begin(); while (it != tokens.end() && remaining > 0) { Token *token = it->get(); int64 attr = -1; std::string value; if (token->type == Token::Placeholder) { attr = gb; if (token->value == "$title") { value = title; } else if (token->value == "$album") { value = album; } } if (!value.size()) { value = token->value; } size_t len = u8cols(value); if (len > remaining) { value = text::Ellipsize(value, remaining); len = remaining; } if (attr != -1) { wattron(w, attr); } wprintw(w, value.c_str()); if (attr != -1) { wattroff(w, attr); } remaining -= len; ++it; } return (width - remaining); } TransportWindow::TransportWindow(musik::box::PlaybackService& playback) : Window(NULL) , playback(playback) , transport(playback.GetTransport()) { this->SetFrameVisible(false); this->playback.TrackChanged.connect(this, &TransportWindow::OnPlaybackServiceTrackChanged); this->playback.ModeChanged.connect(this, &TransportWindow::OnPlaybackModeChanged); this->playback.Shuffled.connect(this, &TransportWindow::OnPlaybackShuffled); this->transport.VolumeChanged.connect(this, &TransportWindow::OnTransportVolumeChanged); this->transport.TimeChanged.connect(this, &TransportWindow::OnTransportTimeChanged); this->paused = false; this->lastTime = DEFAULT_TIME; } TransportWindow::~TransportWindow() { } void TransportWindow::Show() { Window::Show(); this->Update(); } void TransportWindow::ProcessMessage(IMessage &message) { int type = message.Type(); if (type == REFRESH_TRANSPORT_READOUT) { this->Update(); DEBOUNCE_REFRESH(REFRESH_INTERVAL_MS) } } void TransportWindow::OnPlaybackServiceTrackChanged(size_t index, TrackPtr track) { this->currentTrack = track; this->lastTime = DEFAULT_TIME; DEBOUNCE_REFRESH(0); } void TransportWindow::OnPlaybackModeChanged() { DEBOUNCE_REFRESH_AND_SYNC_TIME(); } void TransportWindow::OnTransportVolumeChanged() { DEBOUNCE_REFRESH_AND_SYNC_TIME(); } void TransportWindow::OnTransportTimeChanged(double time) { DEBOUNCE_REFRESH_AND_SYNC_TIME(); } void TransportWindow::OnPlaybackShuffled(bool shuffled) { DEBOUNCE_REFRESH_AND_SYNC_TIME(); } #define ON(w, a) if (a != -1) { wattron(w, a); } #define OFF(w, a) if (a != -1) { wattroff(w, a); } void TransportWindow::Update() { this->Clear(); WINDOW *c = this->GetContent(); size_t cx = (size_t) this->GetContentWidth(); bool paused = (transport.GetPlaybackState() == ITransport::PlaybackPaused); bool stopped = (transport.GetPlaybackState() == ITransport::PlaybackStopped); int64 gb = COLOR_PAIR(CURSESPP_TEXT_ACTIVE); int64 disabled = COLOR_PAIR(CURSESPP_TEXT_DISABLED); /* prepare the "shuffle" label */ std::string shuffleLabel = " shuffle"; size_t shuffleLabelLen = u8cols(shuffleLabel); /* playing SONG TITLE from ALBUM NAME */ std::string duration = "0"; if (stopped) { ON(c, disabled); wprintw(c, "playback is stopped"); OFF(c, disabled); } else { std::string title, album; if (this->currentTrack) { title = this->currentTrack->GetValue(constants::Track::TITLE); album = this->currentTrack->GetValue(constants::Track::ALBUM); duration = this->currentTrack->GetValue(constants::Track::DURATION); } title = title.size() ? title : "[song]"; album = album.size() ? album : "[album]"; duration = duration.size() ? duration : "0"; writePlayingFormat( c, title, album, cx - shuffleLabelLen); } wmove(c, 0, cx - shuffleLabelLen); int64 shuffleAttrs = this->playback.IsShuffled() ? gb : disabled; ON(c, shuffleAttrs); wprintw(c, shuffleLabel.c_str()); OFF(c, shuffleAttrs); wmove(c, 1, 0); /* move cursor to the second line */ /* volume slider */ int volumePercent = (size_t) round(this->transport.Volume() * 100.0f) - 1; int thumbOffset = std::min(9, (volumePercent * 10) / 100); std::string volume = "vol "; for (int i = 0; i < 10; i++) { volume += (i == thumbOffset) ? "■" : "─"; } volume += " "; wprintw(c, volume.c_str()); /* repeat mode setup */ PlaybackService::RepeatMode mode = this->playback.GetRepeatMode(); std::string repeatLabel = " ∞ "; std::string repeatModeLabel; int64 repeatAttrs = -1; switch (mode) { case PlaybackService::RepeatList: repeatModeLabel = "list"; repeatAttrs = gb; break; case PlaybackService::RepeatTrack: repeatModeLabel = "track"; repeatAttrs = gb; break; default: repeatModeLabel = "off"; repeatAttrs = disabled; break; } /* time slider */ int64 timerAttrs = 0; if (paused) { /* blink the track if paused */ int64 now = duration_cast<seconds>( system_clock::now().time_since_epoch()).count(); if (now % 2 == 0) { timerAttrs = COLOR_PAIR(CURSESPP_TEXT_HIDDEN); } } transport.Position(); /* calculating playback time is inexact because it's based on buffers that are sent to the output. here we use a simple smoothing function to hopefully mitigate jumping around. basically: draw the time as one second more than the last time we displayed, unless they are more than few seconds apart. note this only works if REFRESH_INTERVAL_MS is 1000. */ double smoothedTime = this->lastTime += 1.0f; /* 1000 millis */ double actualTime = transport.Position(); if (paused || stopped || fabs(smoothedTime - actualTime) > TIME_SLOP) { smoothedTime = actualTime; } this->lastTime = smoothedTime; /* end time smoothing */ int secondsCurrent = (int) round(smoothedTime); int secondsTotal = boost::lexical_cast<int>(duration); std::string currentTime = duration::Duration(std::min(secondsCurrent, secondsTotal)); std::string totalTime = duration::Duration(secondsTotal); size_t timerWidth = this->GetContentWidth() - u8cols(volume) - (u8cols(repeatLabel) + u8cols(repeatModeLabel)) - currentTime.size() - totalTime.size() - 2; /* padding */ thumbOffset = 0; if (secondsTotal) { size_t progress = (secondsCurrent * 100) / secondsTotal; thumbOffset = std::min(timerWidth - 1, (progress * timerWidth) / 100); } std::string timerTrack = ""; for (size_t i = 0; i < timerWidth; i++) { timerTrack += (i == thumbOffset) ? "■" : "─"; } wattron(c, timerAttrs); /* blink if paused */ wprintw(c, currentTime.c_str()); wattroff(c, timerAttrs); /* using wprintw() here on large displays (1440p+) will exceed the internal buffer length of 512 characters, so use boost format. */ std::string fmt = boost::str(boost::format( " %s %s") % timerTrack % totalTime); waddstr(c, fmt.c_str()); /* repeat mode draw */ wprintw(c, repeatLabel.c_str()); wattron(c, repeatAttrs); wprintw(c, repeatModeLabel.c_str()); wattroff(c, repeatAttrs); this->Repaint(); } <commit_msg>Just experimenting with transport metadata -- added the artist name.<commit_after>////////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2007-2016 musikcube team // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // * Neither the name of the author nor the names of other contributors may // be used to endorse or promote products derived from this software // without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // ////////////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "TransportWindow.h" #include <cursespp/Screen.h> #include <cursespp/Colors.h> #include <cursespp/Message.h> #include <cursespp/Text.h> #include <app/util/Duration.h> #include <core/debug.h> #include <core/library/LocalLibraryConstants.h> #include <boost/format.hpp> #include <boost/algorithm/string.hpp> #include <boost/chrono.hpp> #include <boost/lexical_cast.hpp> #include <algorithm> #include <memory> using namespace musik::core; using namespace musik::core::audio; using namespace musik::core::library; using namespace musik::core::db; using namespace musik::box; using namespace boost::chrono; using namespace cursespp; #define REFRESH_TRANSPORT_READOUT 1001 #define REFRESH_INTERVAL_MS 1000 #define DEFAULT_TIME -1.0f #define TIME_SLOP 3.0f #define DEBOUNCE_REFRESH(x) \ this->RemoveMessage(REFRESH_TRANSPORT_READOUT); \ this->PostMessage(REFRESH_TRANSPORT_READOUT, 0, 0, x); #define DEBOUNCE_REFRESH_AND_SYNC_TIME() \ this->lastTime = this->transport.Position(); \ DEBOUNCE_REFRESH(0) #define ON(w, a) if (a != -1) { wattron(w, a); } #define OFF(w, a) if (a != -1) { wattroff(w, a); } static std::string playingFormat = "playing $title by $artist from $album"; struct Token { enum Type { Normal, Placeholder }; static std::unique_ptr<Token> New(const std::string& value, Type type) { return std::unique_ptr<Token>(new Token(value, type)); } Token(const std::string& value, Type type) { this->value = value; this->type = type; } std::string value; Type type; }; typedef std::unique_ptr<Token> TokenPtr; typedef std::vector<TokenPtr> TokenList; /* tokenizes an input string that has $placeholder values */ void tokenize(const std::string& format, TokenList& tokens) { tokens.clear(); Token::Type type = Token::Normal; size_t i = 0; size_t start = 0; while (i < format.size()) { char c = format[i]; if ((type == Token::Placeholder && c == ' ') || (type == Token::Normal && c == '$')) { /* escape $ with $$ */ if (c == '$' && i < format.size() - 1 && format[i + 1] == '$') { i++; } else { if (i > start) { tokens.push_back(Token::New(format.substr(start, i - start), type)); } start = i; type = (c == ' ') ? Token::Normal : Token::Placeholder; } } ++i; } if (i > 0) { tokens.push_back(Token::New(format.substr(start, i - start), type)); } } /* writes the colorized formatted string to the specified window. accounts for utf8 characters and ellipsizing */ size_t writePlayingFormat( WINDOW *w, std::string title, std::string album, std::string artist, size_t width) { TokenList tokens; tokenize(playingFormat, tokens); int64 dim = COLOR_PAIR(CURSESPP_TEXT_DISABLED); int64 gb = COLOR_PAIR(CURSESPP_TEXT_ACTIVE); size_t remaining = width; auto it = tokens.begin(); while (it != tokens.end() && remaining > 0) { Token *token = it->get(); int64 attr = dim; std::string value; if (token->type == Token::Placeholder) { attr = gb; if (token->value == "$title") { value = title; } else if (token->value == "$album") { value = album; } else if (token->value == "$artist") { value = artist; } } if (!value.size()) { value = token->value; } size_t len = u8cols(value); if (len > remaining) { value = text::Ellipsize(value, remaining); len = remaining; } ON(w, attr); wprintw(w, value.c_str()); OFF(w, attr); remaining -= len; ++it; } return (width - remaining); } TransportWindow::TransportWindow(musik::box::PlaybackService& playback) : Window(NULL) , playback(playback) , transport(playback.GetTransport()) { this->SetFrameVisible(false); this->playback.TrackChanged.connect(this, &TransportWindow::OnPlaybackServiceTrackChanged); this->playback.ModeChanged.connect(this, &TransportWindow::OnPlaybackModeChanged); this->playback.Shuffled.connect(this, &TransportWindow::OnPlaybackShuffled); this->transport.VolumeChanged.connect(this, &TransportWindow::OnTransportVolumeChanged); this->transport.TimeChanged.connect(this, &TransportWindow::OnTransportTimeChanged); this->paused = false; this->lastTime = DEFAULT_TIME; } TransportWindow::~TransportWindow() { } void TransportWindow::Show() { Window::Show(); this->Update(); } void TransportWindow::ProcessMessage(IMessage &message) { int type = message.Type(); if (type == REFRESH_TRANSPORT_READOUT) { this->Update(); DEBOUNCE_REFRESH(REFRESH_INTERVAL_MS) } } void TransportWindow::OnPlaybackServiceTrackChanged(size_t index, TrackPtr track) { this->currentTrack = track; this->lastTime = DEFAULT_TIME; DEBOUNCE_REFRESH(0); } void TransportWindow::OnPlaybackModeChanged() { DEBOUNCE_REFRESH_AND_SYNC_TIME(); } void TransportWindow::OnTransportVolumeChanged() { DEBOUNCE_REFRESH_AND_SYNC_TIME(); } void TransportWindow::OnTransportTimeChanged(double time) { DEBOUNCE_REFRESH_AND_SYNC_TIME(); } void TransportWindow::OnPlaybackShuffled(bool shuffled) { DEBOUNCE_REFRESH_AND_SYNC_TIME(); } void TransportWindow::Update() { this->Clear(); WINDOW *c = this->GetContent(); size_t cx = (size_t) this->GetContentWidth(); bool paused = (transport.GetPlaybackState() == ITransport::PlaybackPaused); bool stopped = (transport.GetPlaybackState() == ITransport::PlaybackStopped); int64 gb = COLOR_PAIR(CURSESPP_TEXT_ACTIVE); int64 disabled = COLOR_PAIR(CURSESPP_TEXT_DISABLED); /* prepare the "shuffle" label */ std::string shuffleLabel = " shuffle"; size_t shuffleLabelLen = u8cols(shuffleLabel); /* playing SONG TITLE from ALBUM NAME */ std::string duration = "0"; if (stopped) { ON(c, disabled); wprintw(c, "playback is stopped"); OFF(c, disabled); } else { std::string title, album, artist; if (this->currentTrack) { title = this->currentTrack->GetValue(constants::Track::TITLE); album = this->currentTrack->GetValue(constants::Track::ALBUM); artist = this->currentTrack->GetValue(constants::Track::ARTIST); duration = this->currentTrack->GetValue(constants::Track::DURATION); } title = title.size() ? title : "[song]"; album = album.size() ? album : "[album]"; artist = artist.size() ? artist : "[artist]"; duration = duration.size() ? duration : "0"; writePlayingFormat( c, title, album, artist, cx - shuffleLabelLen); } wmove(c, 0, cx - shuffleLabelLen); int64 shuffleAttrs = this->playback.IsShuffled() ? gb : disabled; ON(c, shuffleAttrs); wprintw(c, shuffleLabel.c_str()); OFF(c, shuffleAttrs); wmove(c, 1, 0); /* move cursor to the second line */ /* volume slider */ int volumePercent = (size_t) round(this->transport.Volume() * 100.0f) - 1; int thumbOffset = std::min(9, (volumePercent * 10) / 100); std::string volume = "vol "; for (int i = 0; i < 10; i++) { volume += (i == thumbOffset) ? "■" : "─"; } volume += " "; wprintw(c, volume.c_str()); /* repeat mode setup */ PlaybackService::RepeatMode mode = this->playback.GetRepeatMode(); std::string repeatLabel = " ∞ "; std::string repeatModeLabel; int64 repeatAttrs = -1; switch (mode) { case PlaybackService::RepeatList: repeatModeLabel = "list"; repeatAttrs = gb; break; case PlaybackService::RepeatTrack: repeatModeLabel = "track"; repeatAttrs = gb; break; default: repeatModeLabel = "off"; repeatAttrs = disabled; break; } /* time slider */ int64 timerAttrs = 0; if (paused) { /* blink the track if paused */ int64 now = duration_cast<seconds>( system_clock::now().time_since_epoch()).count(); if (now % 2 == 0) { timerAttrs = COLOR_PAIR(CURSESPP_TEXT_HIDDEN); } } transport.Position(); /* calculating playback time is inexact because it's based on buffers that are sent to the output. here we use a simple smoothing function to hopefully mitigate jumping around. basically: draw the time as one second more than the last time we displayed, unless they are more than few seconds apart. note this only works if REFRESH_INTERVAL_MS is 1000. */ double smoothedTime = this->lastTime += 1.0f; /* 1000 millis */ double actualTime = transport.Position(); if (paused || stopped || fabs(smoothedTime - actualTime) > TIME_SLOP) { smoothedTime = actualTime; } this->lastTime = smoothedTime; /* end time smoothing */ int secondsCurrent = (int) round(smoothedTime); int secondsTotal = boost::lexical_cast<int>(duration); std::string currentTime = duration::Duration(std::min(secondsCurrent, secondsTotal)); std::string totalTime = duration::Duration(secondsTotal); size_t timerWidth = this->GetContentWidth() - u8cols(volume) - (u8cols(repeatLabel) + u8cols(repeatModeLabel)) - currentTime.size() - totalTime.size() - 2; /* padding */ thumbOffset = 0; if (secondsTotal) { size_t progress = (secondsCurrent * 100) / secondsTotal; thumbOffset = std::min(timerWidth - 1, (progress * timerWidth) / 100); } std::string timerTrack = ""; for (size_t i = 0; i < timerWidth; i++) { timerTrack += (i == thumbOffset) ? "■" : "─"; } wattron(c, timerAttrs); /* blink if paused */ wprintw(c, currentTime.c_str()); wattroff(c, timerAttrs); /* using wprintw() here on large displays (1440p+) will exceed the internal buffer length of 512 characters, so use boost format. */ std::string fmt = boost::str(boost::format( " %s %s") % timerTrack % totalTime); waddstr(c, fmt.c_str()); /* repeat mode draw */ wprintw(c, repeatLabel.c_str()); wattron(c, repeatAttrs); wprintw(c, repeatModeLabel.c_str()); wattroff(c, repeatAttrs); this->Repaint(); } <|endoftext|>
<commit_before>#include <iostream> #include <queue> #include <stdio.h> using namespace std; #include "Binary-tree.hpp" #include "pretty-print.hpp" // Функция создает сбалансированное дерево и возращает корневой узел дерева Node* createBalancedBTree(Node** node, int *&value, int cnt) { if (cnt <= 0) return NULL; if (node == NULL) { Node* tmp = NULL; node = &tmp; } if ((*node) == NULL) { (*node) = new Node(*value); ++value; --cnt; } int cntr = cnt / 2; int cntl = cnt - cntr; if (cntl > 0) createBalancedBTree(&(*node)->left, value, cntl); if (cntr > 0) createBalancedBTree(&(*node)->right, value, cntr); return (*node); } // Функция создает бинарное дерево поиска и возращает корневой узел дерева Node* insertSearchBTree(Node** node, int value) { if ((*node) == NULL) { (*node) = new Node(value); return *node; } if ((*node)->data > value) { return insertSearchBTree(&(*node)->left, value); } else if ((*node)->data < value) { return insertSearchBTree(&(*node)->right, value); } else { std::cout << "something going wrong! " << value << endl; } } // Функция создает бинарное дерево поиска и возращает корневой узел дерева Node* createSearchBTree(int *array, int size) { Node* node = NULL; for (int i = 0; i < size; ++i) insertSearchBTree(&node, array[i]); return node; } int main() { int data[] = {25, 50, 55, 0, 10, 5, 30, 40, 35, 15, 45, 60, 75, 70}; int size = sizeof(data) / (sizeof(data[0])); cout << "Exer.1 - Balanced B-Tree" << endl; int *it = (int *)&data; printPretty(createBalancedBTree(NULL, it, size)); cout << endl; cout << "Exer.2 - Search B-Tree" << endl; printPretty(createSearchBTree(data, size)); return 0; } <commit_msg>lab5 6<commit_after>#include <iostream> #include <queue> #include <stdio.h> using namespace std; #include "Binary-tree.hpp" #include "pretty-print.hpp" // Функция создает сбалансированное дерево и возращает корневой узел дерева Node* createBalancedBTree(Node** node, int *&value, int cnt) { if (cnt <= 0) return NULL; if (node == NULL) { Node* tmp = NULL; node = &tmp; } if ((*node) == NULL) { (*node) = new Node(*value); ++value; --cnt; } int cntr = cnt / 2; int cntl = cnt - cntr; if (cntl > 0) createBalancedBTree(&(*node)->left, value, cntl); if (cntr > 0) createBalancedBTree(&(*node)->right, value, cntr); return (*node); } // Функция создает бинарное дерево поиска и возращает корневой узел дерева Node* insertSearchBTree(Node** node, int value) { if ((*node) == NULL) { (*node) = new Node(value); return *node; } if ((*node)->data > value) { return insertSearchBTree(&(*node)->left, value); } else if ((*node)->data < value) { return insertSearchBTree(&(*node)->right, value); } else { std::cout << "something going wrong! " << value << endl; } } // Функция создает бинарное дерево поиска и возращает корневой узел дерева Node* createSearchBTree(int *array, int size) { Node* node = NULL; for (int i = 0; i < size; ++i) insertSearchBTree(&node, array[i]); return node; } void findRowsSumm(Node *node, int *rows, int currentDepth) { if (node == NULL) return; rows[currentDepth] += node->data; findRowsSumm(node->left, rows, currentDepth+1); findRowsSumm(node->right, rows, currentDepth+1); } int findRowWithMaxSumm(Node *node, int rowsCount) { if (node == NULL) return -1; int *rowsSumm = new int[rowsCount]; for (int i = 0; i < rowsCount; ++i) rowsSumm[i] = 0; findRowsSumm(node, rowsSumm, 0); int maxRow = -1; int maxValue = 0; for (int i = 0; i < rowsCount; i++) { if ((rowsSumm[i] >= 0) && (rowsSumm[i] > maxValue)) { maxRow = i; maxValue = rowsSumm[i]; } } return maxRow; } int main() { int data[] = {35, 55, 15, 50, 40, 0, 10, 45, 5, 30, 25}; int size = sizeof(data) / (sizeof(data[0])); cout << "Exer.1 - Balanced B-Tree" << endl; int *it = (int *)&data; Node* balancedBTreeRoot = createBalancedBTree(NULL, it, size); printPretty(balancedBTreeRoot); cout << endl; cout << "Exer.2 - Search B-Tree" << endl; Node* searchBTreeRoot = createSearchBTree(data, size); printPretty(searchBTreeRoot); cout << endl; cout << "Exer.6 - Find row with max summ of values from search B-Tree" << endl; printPretty(searchBTreeRoot); cout << "Count starts from 0, -1 = no values found" << endl; cout << "Answer is " << findRowWithMaxSumm(searchBTreeRoot, size) << endl; cout << endl; return 0; } <|endoftext|>
<commit_before>/****************************************************************************** * Copyright 2017 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/control/control.h" #include <iomanip> #include <string> #include "ros/include/std_msgs/String.h" #include "modules/localization/proto/localization.pb.h" #include "modules/common/adapters/adapter_gflags.h" #include "modules/common/adapters/adapter_manager.h" #include "modules/common/log.h" #include "modules/common/time/time.h" #include "modules/common/vehicle_state/vehicle_state.h" #include "modules/control/common/control_gflags.h" namespace apollo { namespace control { using apollo::canbus::Chassis; using apollo::common::ErrorCode; using apollo::common::Status; using apollo::common::adapter::AdapterManager; using apollo::common::monitor::MonitorMessageItem; using apollo::common::time::Clock; using apollo::localization::LocalizationEstimate; using apollo::planning::ADCTrajectory; std::string Control::Name() const { return FLAGS_node_name; } Status Control::Init() { AINFO << "Control init, starting ..."; CHECK(::apollo::common::util::GetProtoFromFile(FLAGS_control_conf_file, &control_conf_)) << "Unable to load control conf file: " + FLAGS_control_conf_file; AINFO << "Conf file: " << FLAGS_control_conf_file << " is loaded."; AdapterManager::Init(FLAGS_adapter_config_path); apollo::common::monitor::MonitorBuffer buffer(&monitor_); // set controller if (!controller_agent_.Init(&control_conf_).ok()) { std::string error_msg = "Control init controller failed! Stopping..."; buffer.ERROR(error_msg); return Status(ErrorCode::CONTROL_INIT_ERROR, error_msg); } // lock it in case for after sub, init_vehicle not ready, but msg trigger // come CHECK(AdapterManager::GetLocalization()) << "Localization is not initialized."; CHECK(AdapterManager::GetChassis()) << "Chassis is not initialized."; CHECK(AdapterManager::GetPlanning()) << "Planning is not initialized."; CHECK(AdapterManager::GetPad()) << "Pad is not initialized."; CHECK(AdapterManager::GetControlCommand()) << "ControlCommand publisher is not initialized."; AdapterManager::AddPadCallback(&Control::OnPad, this); AdapterManager::AddMonitorCallback(&Control::OnMonitor, this); return Status::OK(); } Status Control::Start() { // set initial vehicle state by cmd // need to sleep, because advertised channel is not ready immediately // simple test shows a short delay of 80 ms or so AINFO << "Control resetting vehicle state, sleeping for 1000 ms ..."; usleep(1000 * 1000); // should init_vehicle first, let car enter work status, then use status msg // trigger control AINFO << "Control default driving action is " << DrivingAction_Name(control_conf_.action()); pad_msg_.set_action(control_conf_.action()); timer_ = AdapterManager::CreateTimer( ros::Duration(control_conf_.control_period()), &Control::OnTimer, this); AINFO << "Control init done!"; apollo::common::monitor::MonitorBuffer buffer(&monitor_); buffer.INFO("control started"); return Status::OK(); } void Control::OnPad(const PadMessage &pad) { pad_msg_ = pad; ADEBUG << "Received Pad Msg:" << pad.DebugString(); AERROR_IF(!pad_msg_.has_action()) << "pad message check failed!"; // do something according to pad message if (pad_msg_.action() == DrivingAction::RESET) { AINFO << "Control received RESET action!"; estop_ = false; } pad_received_ = true; } void Control::OnMonitor( const apollo::common::monitor::MonitorMessage &monitor_message) { for (const auto &item : monitor_message.item()) { if (item.log_level() == MonitorMessageItem::FATAL) { estop_ = true; return; } } } Status Control::ProduceControlCommand(ControlCommand *control_command) { Status status = CheckInput(); // check data if (!status.ok()) { AERROR << "Control input data failed: " << status.error_message(); estop_ = true; } else { Status status_ts = CheckTimestamp(); if (!status_ts.ok()) { AERROR << "Input messages timeout"; estop_ = true; status = status_ts; } } // check estop estop_ = estop_ || trajectory_.estop().is_estop(); // if planning set estop, then no control process triggered if (!estop_) { if (chassis_.driving_mode() == Chassis::COMPLETE_MANUAL) { controller_agent_.Reset(); AINFO << "Reset Controllers in Manual Mode"; } auto debug = control_command->mutable_debug()->mutable_input_debug(); debug->mutable_localization_header()->CopyFrom(localization_.header()); debug->mutable_canbus_header()->CopyFrom(chassis_.header()); debug->mutable_trajectory_header()->CopyFrom(trajectory_.header()); Status status_compute = controller_agent_.ComputeControlCommand( &localization_, &chassis_, &trajectory_, control_command); if (!status_compute.ok()) { AERROR << "Control main function failed" << " with localization: " << localization_.ShortDebugString() << " with chassis: " << chassis_.ShortDebugString() << " with trajectory: " << trajectory_.ShortDebugString() << " with cmd: " << control_command->ShortDebugString() << " status:" << status_compute.error_message(); estop_ = true; status = status_compute; } } if (estop_) { AWARN << "Estop triggered! No control core method executed!"; // set Estop command control_command->set_speed(0); control_command->set_throttle(0); control_command->set_brake(control_conf_.soft_estop_brake()); control_command->set_gear_location(Chassis::GEAR_DRIVE); } // check signal if (trajectory_.has_signal()) { control_command->mutable_signal()->CopyFrom(trajectory_.signal()); } return status; } void Control::OnTimer(const ros::TimerEvent &) { double start_timestamp = Clock::NowInSecond(); ControlCommand control_command; Status status = ProduceControlCommand(&control_command); if (!status.ok()) { AERROR << "Failed to produce control command:" << status.error_message(); } double end_timestamp = Clock::NowInSecond(); if (pad_received_) { control_command.mutable_pad_msg()->CopyFrom(pad_msg_); pad_received_ = false; } const double time_diff_ms = (end_timestamp - start_timestamp) * 1000; control_command.mutable_latency_stats()->set_total_time_ms(time_diff_ms); AINFO_EVERY(1000) << "control cycle time is: " << time_diff_ms << " ms."; status.Save(control_command.mutable_header()->mutable_status()); SendCmd(&control_command); } Status Control::CheckInput() { AdapterManager::Observe(); auto localization_adapter = AdapterManager::GetLocalization(); if (localization_adapter->Empty()) { AWARN_EVERY(100) << "No Localization msg yet. "; return Status(ErrorCode::CONTROL_COMPUTE_ERROR, "No localization msg"); } localization_ = localization_adapter->GetLatestObserved(); ADEBUG << "Received localization:" << localization_.ShortDebugString(); auto chassis_adapter = AdapterManager::GetChassis(); if (chassis_adapter->Empty()) { AWARN_EVERY(100) << "No Chassis msg yet. "; return Status(ErrorCode::CONTROL_COMPUTE_ERROR, "No chassis msg"); } chassis_ = chassis_adapter->GetLatestObserved(); ADEBUG << "Received chassis:" << chassis_.ShortDebugString(); auto trajectory_adapter = AdapterManager::GetPlanning(); if (trajectory_adapter->Empty()) { AWARN_EVERY(100) << "No planning msg yet. "; return Status(ErrorCode::CONTROL_COMPUTE_ERROR, "No planning msg"); } trajectory_ = trajectory_adapter->GetLatestObserved(); if (trajectory_.trajectory_point_size() == 0) { AWARN_EVERY(100) << "planning has no trajectory point. "; return Status(ErrorCode::CONTROL_COMPUTE_ERROR, "planning has no trajectory point."); } common::VehicleState::instance()->Update(localization_, chassis_); return Status::OK(); } Status Control::CheckTimestamp() { if (!FLAGS_enable_input_timestamp_check || FLAGS_is_control_test_mode) { ADEBUG << "Skip input timestamp check by gflags."; return Status::OK(); } double current_timestamp = Clock::NowInSecond(); double localization_diff = current_timestamp - localization_.header().timestamp_sec(); if (localization_diff > (FLAGS_max_localization_miss_num * control_conf_.localization_period())) { AERROR << "Localization msg lost for " << std::setprecision(6) << localization_diff << "s"; return Status(ErrorCode::CONTROL_COMPUTE_ERROR, "Localization msg timeout"); } double chassis_diff = current_timestamp - chassis_.header().timestamp_sec(); if (chassis_diff > (FLAGS_max_chassis_miss_num * control_conf_.chassis_period())) { AERROR << "Chassis msg lost for " << std::setprecision(6) << chassis_diff << "s"; return Status(ErrorCode::CONTROL_COMPUTE_ERROR, "Chassis msg timeout"); } double trajectory_diff = current_timestamp - trajectory_.header().timestamp_sec(); if (trajectory_diff > (FLAGS_max_planning_miss_num * control_conf_.trajectory_period())) { AERROR << "Trajectory msg lost for " << std::setprecision(6) << trajectory_diff << "s"; return Status(ErrorCode::CONTROL_COMPUTE_ERROR, "Trajectory msg timeout"); } return Status::OK(); } void Control::SendCmd(ControlCommand *control_command) { // set header AdapterManager::FillControlCommandHeader(Name(), control_command); ADEBUG << control_command->ShortDebugString(); if (FLAGS_is_control_test_mode) { ADEBUG << "Skip publish control command in test mode"; return; } AdapterManager::PublishControlCommand(*control_command); } void Control::Stop() {} } // namespace control } // namespace apollo <commit_msg>control: reduce warning text<commit_after>/****************************************************************************** * Copyright 2017 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/control/control.h" #include <iomanip> #include <string> #include "ros/include/std_msgs/String.h" #include "modules/localization/proto/localization.pb.h" #include "modules/common/adapters/adapter_gflags.h" #include "modules/common/adapters/adapter_manager.h" #include "modules/common/log.h" #include "modules/common/time/time.h" #include "modules/common/vehicle_state/vehicle_state.h" #include "modules/control/common/control_gflags.h" namespace apollo { namespace control { using apollo::canbus::Chassis; using apollo::common::ErrorCode; using apollo::common::Status; using apollo::common::adapter::AdapterManager; using apollo::common::monitor::MonitorMessageItem; using apollo::common::time::Clock; using apollo::localization::LocalizationEstimate; using apollo::planning::ADCTrajectory; std::string Control::Name() const { return FLAGS_node_name; } Status Control::Init() { AINFO << "Control init, starting ..."; CHECK(::apollo::common::util::GetProtoFromFile(FLAGS_control_conf_file, &control_conf_)) << "Unable to load control conf file: " + FLAGS_control_conf_file; AINFO << "Conf file: " << FLAGS_control_conf_file << " is loaded."; AdapterManager::Init(FLAGS_adapter_config_path); apollo::common::monitor::MonitorBuffer buffer(&monitor_); // set controller if (!controller_agent_.Init(&control_conf_).ok()) { std::string error_msg = "Control init controller failed! Stopping..."; buffer.ERROR(error_msg); return Status(ErrorCode::CONTROL_INIT_ERROR, error_msg); } // lock it in case for after sub, init_vehicle not ready, but msg trigger // come CHECK(AdapterManager::GetLocalization()) << "Localization is not initialized."; CHECK(AdapterManager::GetChassis()) << "Chassis is not initialized."; CHECK(AdapterManager::GetPlanning()) << "Planning is not initialized."; CHECK(AdapterManager::GetPad()) << "Pad is not initialized."; CHECK(AdapterManager::GetControlCommand()) << "ControlCommand publisher is not initialized."; AdapterManager::AddPadCallback(&Control::OnPad, this); AdapterManager::AddMonitorCallback(&Control::OnMonitor, this); return Status::OK(); } Status Control::Start() { // set initial vehicle state by cmd // need to sleep, because advertised channel is not ready immediately // simple test shows a short delay of 80 ms or so AINFO << "Control resetting vehicle state, sleeping for 1000 ms ..."; usleep(1000 * 1000); // should init_vehicle first, let car enter work status, then use status msg // trigger control AINFO << "Control default driving action is " << DrivingAction_Name(control_conf_.action()); pad_msg_.set_action(control_conf_.action()); timer_ = AdapterManager::CreateTimer( ros::Duration(control_conf_.control_period()), &Control::OnTimer, this); AINFO << "Control init done!"; apollo::common::monitor::MonitorBuffer buffer(&monitor_); buffer.INFO("control started"); return Status::OK(); } void Control::OnPad(const PadMessage &pad) { pad_msg_ = pad; ADEBUG << "Received Pad Msg:" << pad.DebugString(); AERROR_IF(!pad_msg_.has_action()) << "pad message check failed!"; // do something according to pad message if (pad_msg_.action() == DrivingAction::RESET) { AINFO << "Control received RESET action!"; estop_ = false; } pad_received_ = true; } void Control::OnMonitor( const apollo::common::monitor::MonitorMessage &monitor_message) { for (const auto &item : monitor_message.item()) { if (item.log_level() == MonitorMessageItem::FATAL) { estop_ = true; return; } } } Status Control::ProduceControlCommand(ControlCommand *control_command) { Status status = CheckInput(); // check data if (!status.ok()) { AERROR << "Control input data failed: " << status.error_message(); estop_ = true; } else { Status status_ts = CheckTimestamp(); if (!status_ts.ok()) { AERROR << "Input messages timeout"; estop_ = true; status = status_ts; } } // check estop estop_ = estop_ || trajectory_.estop().is_estop(); // if planning set estop, then no control process triggered if (!estop_) { if (chassis_.driving_mode() == Chassis::COMPLETE_MANUAL) { controller_agent_.Reset(); AINFO << "Reset Controllers in Manual Mode"; } auto debug = control_command->mutable_debug()->mutable_input_debug(); debug->mutable_localization_header()->CopyFrom(localization_.header()); debug->mutable_canbus_header()->CopyFrom(chassis_.header()); debug->mutable_trajectory_header()->CopyFrom(trajectory_.header()); Status status_compute = controller_agent_.ComputeControlCommand( &localization_, &chassis_, &trajectory_, control_command); if (!status_compute.ok()) { AERROR << "Control main function failed" << " with localization: " << localization_.ShortDebugString() << " with chassis: " << chassis_.ShortDebugString() << " with trajectory: " << trajectory_.ShortDebugString() << " with cmd: " << control_command->ShortDebugString() << " status:" << status_compute.error_message(); estop_ = true; status = status_compute; } } if (estop_) { AWARN_EVERY(100) << "Estop triggered! No control core method executed!"; // set Estop command control_command->set_speed(0); control_command->set_throttle(0); control_command->set_brake(control_conf_.soft_estop_brake()); control_command->set_gear_location(Chassis::GEAR_DRIVE); } // check signal if (trajectory_.has_signal()) { control_command->mutable_signal()->CopyFrom(trajectory_.signal()); } return status; } void Control::OnTimer(const ros::TimerEvent &) { double start_timestamp = Clock::NowInSecond(); ControlCommand control_command; Status status = ProduceControlCommand(&control_command); if (!status.ok()) { AERROR << "Failed to produce control command:" << status.error_message(); } double end_timestamp = Clock::NowInSecond(); if (pad_received_) { control_command.mutable_pad_msg()->CopyFrom(pad_msg_); pad_received_ = false; } const double time_diff_ms = (end_timestamp - start_timestamp) * 1000; control_command.mutable_latency_stats()->set_total_time_ms(time_diff_ms); AINFO_EVERY(1000) << "control cycle time is: " << time_diff_ms << " ms."; status.Save(control_command.mutable_header()->mutable_status()); SendCmd(&control_command); } Status Control::CheckInput() { AdapterManager::Observe(); auto localization_adapter = AdapterManager::GetLocalization(); if (localization_adapter->Empty()) { AWARN_EVERY(100) << "No Localization msg yet. "; return Status(ErrorCode::CONTROL_COMPUTE_ERROR, "No localization msg"); } localization_ = localization_adapter->GetLatestObserved(); ADEBUG << "Received localization:" << localization_.ShortDebugString(); auto chassis_adapter = AdapterManager::GetChassis(); if (chassis_adapter->Empty()) { AWARN_EVERY(100) << "No Chassis msg yet. "; return Status(ErrorCode::CONTROL_COMPUTE_ERROR, "No chassis msg"); } chassis_ = chassis_adapter->GetLatestObserved(); ADEBUG << "Received chassis:" << chassis_.ShortDebugString(); auto trajectory_adapter = AdapterManager::GetPlanning(); if (trajectory_adapter->Empty()) { AWARN_EVERY(100) << "No planning msg yet. "; return Status(ErrorCode::CONTROL_COMPUTE_ERROR, "No planning msg"); } trajectory_ = trajectory_adapter->GetLatestObserved(); if (trajectory_.trajectory_point_size() == 0) { AWARN_EVERY(100) << "planning has no trajectory point. "; return Status(ErrorCode::CONTROL_COMPUTE_ERROR, "planning has no trajectory point."); } common::VehicleState::instance()->Update(localization_, chassis_); return Status::OK(); } Status Control::CheckTimestamp() { if (!FLAGS_enable_input_timestamp_check || FLAGS_is_control_test_mode) { ADEBUG << "Skip input timestamp check by gflags."; return Status::OK(); } double current_timestamp = Clock::NowInSecond(); double localization_diff = current_timestamp - localization_.header().timestamp_sec(); if (localization_diff > (FLAGS_max_localization_miss_num * control_conf_.localization_period())) { AERROR << "Localization msg lost for " << std::setprecision(6) << localization_diff << "s"; return Status(ErrorCode::CONTROL_COMPUTE_ERROR, "Localization msg timeout"); } double chassis_diff = current_timestamp - chassis_.header().timestamp_sec(); if (chassis_diff > (FLAGS_max_chassis_miss_num * control_conf_.chassis_period())) { AERROR << "Chassis msg lost for " << std::setprecision(6) << chassis_diff << "s"; return Status(ErrorCode::CONTROL_COMPUTE_ERROR, "Chassis msg timeout"); } double trajectory_diff = current_timestamp - trajectory_.header().timestamp_sec(); if (trajectory_diff > (FLAGS_max_planning_miss_num * control_conf_.trajectory_period())) { AERROR << "Trajectory msg lost for " << std::setprecision(6) << trajectory_diff << "s"; return Status(ErrorCode::CONTROL_COMPUTE_ERROR, "Trajectory msg timeout"); } return Status::OK(); } void Control::SendCmd(ControlCommand *control_command) { // set header AdapterManager::FillControlCommandHeader(Name(), control_command); ADEBUG << control_command->ShortDebugString(); if (FLAGS_is_control_test_mode) { ADEBUG << "Skip publish control command in test mode"; return; } AdapterManager::PublishControlCommand(*control_command); } void Control::Stop() {} } // namespace control } // namespace apollo <|endoftext|>
<commit_before>/***************************************************************************** * util.cpp : matroska demuxer ***************************************************************************** * Copyright (C) 2003-2004 VLC authors and VideoLAN * $Id$ * * Authors: Laurent Aimar <fenrir@via.ecp.fr> * Steve Lhomme <steve.lhomme@free.fr> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. *****************************************************************************/ #include "mkv.hpp" #include "util.hpp" #include "demux.hpp" #include <stdint.h> /***************************************************************************** * Local prototypes *****************************************************************************/ #ifdef HAVE_ZLIB_H int32_t zlib_decompress_extra( demux_t * p_demux, mkv_track_t * tk ) { int result; z_stream d_stream; size_t n = 0; uint8_t * p_new_extra = NULL; msg_Dbg(p_demux,"Inflating private data"); d_stream.zalloc = Z_NULL; d_stream.zfree = Z_NULL; d_stream.opaque = Z_NULL; if( inflateInit( &d_stream ) != Z_OK ) { msg_Err( p_demux, "Couldn't initiate inflation ignore track %d", tk->i_number ); free(tk->p_extra_data); delete tk; return 1; } d_stream.next_in = tk->p_extra_data; d_stream.avail_in = tk->i_extra_data; do { n++; p_new_extra = (uint8_t *) realloc(p_new_extra, n*1024); if( !p_new_extra ) { msg_Err( p_demux, "Couldn't allocate buffer to inflate data, ignore track %d", tk->i_number ); inflateEnd( &d_stream ); free(tk->p_extra_data); delete tk; return 1; } d_stream.next_out = &p_new_extra[(n - 1) * 1024]; d_stream.avail_out = 1024; result = inflate(&d_stream, Z_NO_FLUSH); if( result != Z_OK && result != Z_STREAM_END ) { msg_Err( p_demux, "Zlib decompression failed. Result: %d", result ); inflateEnd( &d_stream ); free(p_new_extra); free(tk->p_extra_data); delete tk; return 1; } } while ( d_stream.avail_out == 0 && d_stream.avail_in != 0 && result != Z_STREAM_END ); free( tk->p_extra_data ); tk->i_extra_data = d_stream.total_out; p_new_extra = (uint8_t *) realloc(p_new_extra, tk->i_extra_data); if( !p_new_extra ) { msg_Err( p_demux, "Couldn't allocate buffer to inflate data, ignore track %d", tk->i_number ); inflateEnd( &d_stream ); free(p_new_extra); delete tk; return 1; } tk->p_extra_data = p_new_extra; inflateEnd( &d_stream ); return 0; } block_t *block_zlib_decompress( vlc_object_t *p_this, block_t *p_in_block ) { int result, dstsize, n; unsigned char *dst; block_t *p_block; z_stream d_stream; d_stream.zalloc = (alloc_func)0; d_stream.zfree = (free_func)0; d_stream.opaque = (voidpf)0; result = inflateInit(&d_stream); if( result != Z_OK ) { msg_Dbg( p_this, "inflateInit() failed. Result: %d", result ); return NULL; } d_stream.next_in = (Bytef *)p_in_block->p_buffer; d_stream.avail_in = p_in_block->i_buffer; n = 0; p_block = block_Alloc( 0 ); dst = NULL; do { n++; p_block = block_Realloc( p_block, 0, n * 1000 ); dst = (unsigned char *)p_block->p_buffer; d_stream.next_out = (Bytef *)&dst[(n - 1) * 1000]; d_stream.avail_out = 1000; result = inflate(&d_stream, Z_NO_FLUSH); if( ( result != Z_OK ) && ( result != Z_STREAM_END ) ) { msg_Err( p_this, "Zlib decompression failed. Result: %d", result ); inflateEnd( &d_stream ); block_Release( p_block ); return p_in_block; } } while( ( d_stream.avail_out == 0 ) && ( d_stream.avail_in != 0 ) && ( result != Z_STREAM_END ) ); dstsize = d_stream.total_out; inflateEnd( &d_stream ); p_block = block_Realloc( p_block, 0, dstsize ); p_block->i_buffer = dstsize; block_Release( p_in_block ); return p_block; } #endif /* Utility function for BlockDecode */ block_t *MemToBlock( uint8_t *p_mem, size_t i_mem, size_t offset) { if( unlikely( i_mem > SIZE_MAX - offset ) ) return NULL; block_t *p_block = block_Alloc( i_mem + offset ); if( likely(p_block != NULL) ) { memcpy( p_block->p_buffer + offset, p_mem, i_mem ); } return p_block; } void handle_real_audio(demux_t * p_demux, mkv_track_t * p_tk, block_t * p_blk, mtime_t i_pts) { uint8_t * p_frame = p_blk->p_buffer; Cook_PrivateTrackData * p_sys = (Cook_PrivateTrackData *) p_tk->p_sys; size_t size = p_blk->i_buffer; if( p_tk->i_last_dts == VLC_TS_INVALID ) { for( size_t i = 0; i < p_sys->i_subpackets; i++) if( p_sys->p_subpackets[i] ) { block_Release(p_sys->p_subpackets[i]); p_sys->p_subpackets[i] = NULL; } p_sys->i_subpacket = 0; } if( p_tk->fmt.i_codec == VLC_CODEC_COOK || p_tk->fmt.i_codec == VLC_CODEC_ATRAC3 ) { const uint32_t i_num = p_sys->i_frame_size / p_sys->i_subpacket_size; const int y = p_sys->i_subpacket / ( p_sys->i_frame_size / p_sys->i_subpacket_size ); for( int i = 0; i < i_num; i++ ) { int i_index = p_sys->i_sub_packet_h * i + ((p_sys->i_sub_packet_h + 1) / 2) * (y&1) + (y>>1); if( i_index >= p_sys->i_subpackets ) return; block_t *p_block = block_Alloc( p_sys->i_subpacket_size ); if( !p_block ) return; if( size < p_sys->i_subpacket_size ) return; memcpy( p_block->p_buffer, p_frame, p_sys->i_subpacket_size ); p_block->i_dts = VLC_TS_INVALID; p_block->i_pts = VLC_TS_INVALID; if( !p_sys->i_subpacket ) { p_tk->i_last_dts = p_block->i_pts = i_pts + VLC_TS_0; } p_frame += p_sys->i_subpacket_size; size -= p_sys->i_subpacket_size; p_sys->i_subpacket++; p_sys->p_subpackets[i_index] = p_block; } } else { /*TODO*/ } if( p_sys->i_subpacket == p_sys->i_subpackets ) { for( size_t i = 0; i < p_sys->i_subpackets; i++) { es_out_Send( p_demux->out, p_tk->p_es, p_sys->p_subpackets[i]); p_sys->p_subpackets[i] = NULL; } p_sys->i_subpacket = 0; } } int32_t Cook_PrivateTrackData::Init() { i_subpackets = (size_t) i_sub_packet_h * (size_t) i_frame_size / (size_t) i_subpacket_size; p_subpackets = (block_t**) calloc(i_subpackets, sizeof(block_t*)); if( unlikely( !p_subpackets ) ) { i_subpackets = 0; return 1; } return 0; } Cook_PrivateTrackData::~Cook_PrivateTrackData() { for( size_t i = 0; i < i_subpackets; i++ ) if( p_subpackets[i] ) block_Release( p_subpackets[i] ); free( p_subpackets ); } static inline void fill_wvpk_block(uint16_t version, uint32_t block_samples, uint32_t flags, uint32_t crc, uint8_t * src, size_t srclen, uint8_t * dst) { const uint8_t wvpk_header[] = {'w','v','p','k', /* ckId */ 0x0, 0x0, 0x0, 0x0, /* ckSize */ 0x0, 0x0, /* version */ 0x0, /* track_no */ 0x0, /* index_no */ 0xFF, 0xFF, 0xFF, 0xFF, /* total_samples */ 0x0, 0x0, 0x0, 0x0 }; /* block_index */ memcpy( dst, wvpk_header, sizeof( wvpk_header ) ); SetDWLE( dst + 4, srclen + 24 ); SetWLE( dst + 8, version ); SetDWLE( dst + 20, block_samples ); SetDWLE( dst + 24, flags ); SetDWLE( dst + 28, crc ); memcpy( dst + 32, src, srclen ); } block_t * packetize_wavpack( mkv_track_t * p_tk, uint8_t * buffer, size_t size) { uint16_t version = 0x403; uint32_t block_samples; uint32_t flags; uint32_t crc; block_t * p_block = NULL; if( p_tk->i_extra_data >= 2 ) version = GetWLE( p_tk->p_extra_data ); if( size < 12 ) return NULL; block_samples = GetDWLE(buffer); buffer += 4; flags = GetDWLE(buffer); size -= 4; /* Check if WV_INITIAL_BLOCK and WV_FINAL_BLOCK are present */ if( ( flags & 0x1800 ) == 0x1800 ) { crc = GetDWLE(buffer+4); buffer += 8; size -= 8; p_block = block_Alloc( size + 32 ); if( !p_block ) return NULL; fill_wvpk_block(version, block_samples, flags, crc, buffer, size, p_block->p_buffer); } else { /* Multiblock */ size_t total_size = 0; p_block = block_Alloc( 0 ); if( !p_block ) return NULL; while(size >= 12) { flags = GetDWLE(buffer); buffer += 4; crc = GetDWLE(buffer); buffer += 4; uint32_t bsz = GetDWLE(buffer); buffer+= 4; size -= 12; bsz = (bsz < size)?bsz:size; total_size += bsz + 32; assert(total_size >= p_block->i_buffer); p_block = block_Realloc( p_block, 0, total_size ); if( !p_block ) return NULL; fill_wvpk_block(version, block_samples, flags, crc, buffer, bsz, p_block->p_buffer + total_size - bsz - 32 ); buffer += bsz; size -= bsz; } } return p_block; } <commit_msg>demux: mkv: fix warning & int overflow<commit_after>/***************************************************************************** * util.cpp : matroska demuxer ***************************************************************************** * Copyright (C) 2003-2004 VLC authors and VideoLAN * $Id$ * * Authors: Laurent Aimar <fenrir@via.ecp.fr> * Steve Lhomme <steve.lhomme@free.fr> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. *****************************************************************************/ #include "mkv.hpp" #include "util.hpp" #include "demux.hpp" #include <stdint.h> /***************************************************************************** * Local prototypes *****************************************************************************/ #ifdef HAVE_ZLIB_H int32_t zlib_decompress_extra( demux_t * p_demux, mkv_track_t * tk ) { int result; z_stream d_stream; size_t n = 0; uint8_t * p_new_extra = NULL; msg_Dbg(p_demux,"Inflating private data"); d_stream.zalloc = Z_NULL; d_stream.zfree = Z_NULL; d_stream.opaque = Z_NULL; if( inflateInit( &d_stream ) != Z_OK ) { msg_Err( p_demux, "Couldn't initiate inflation ignore track %d", tk->i_number ); free(tk->p_extra_data); delete tk; return 1; } d_stream.next_in = tk->p_extra_data; d_stream.avail_in = tk->i_extra_data; do { n++; p_new_extra = (uint8_t *) realloc(p_new_extra, n*1024); if( !p_new_extra ) { msg_Err( p_demux, "Couldn't allocate buffer to inflate data, ignore track %d", tk->i_number ); inflateEnd( &d_stream ); free(tk->p_extra_data); delete tk; return 1; } d_stream.next_out = &p_new_extra[(n - 1) * 1024]; d_stream.avail_out = 1024; result = inflate(&d_stream, Z_NO_FLUSH); if( result != Z_OK && result != Z_STREAM_END ) { msg_Err( p_demux, "Zlib decompression failed. Result: %d", result ); inflateEnd( &d_stream ); free(p_new_extra); free(tk->p_extra_data); delete tk; return 1; } } while ( d_stream.avail_out == 0 && d_stream.avail_in != 0 && result != Z_STREAM_END ); free( tk->p_extra_data ); tk->i_extra_data = d_stream.total_out; p_new_extra = (uint8_t *) realloc(p_new_extra, tk->i_extra_data); if( !p_new_extra ) { msg_Err( p_demux, "Couldn't allocate buffer to inflate data, ignore track %d", tk->i_number ); inflateEnd( &d_stream ); free(p_new_extra); delete tk; return 1; } tk->p_extra_data = p_new_extra; inflateEnd( &d_stream ); return 0; } block_t *block_zlib_decompress( vlc_object_t *p_this, block_t *p_in_block ) { int result, dstsize, n; unsigned char *dst; block_t *p_block; z_stream d_stream; d_stream.zalloc = (alloc_func)0; d_stream.zfree = (free_func)0; d_stream.opaque = (voidpf)0; result = inflateInit(&d_stream); if( result != Z_OK ) { msg_Dbg( p_this, "inflateInit() failed. Result: %d", result ); return NULL; } d_stream.next_in = (Bytef *)p_in_block->p_buffer; d_stream.avail_in = p_in_block->i_buffer; n = 0; p_block = block_Alloc( 0 ); dst = NULL; do { n++; p_block = block_Realloc( p_block, 0, n * 1000 ); dst = (unsigned char *)p_block->p_buffer; d_stream.next_out = (Bytef *)&dst[(n - 1) * 1000]; d_stream.avail_out = 1000; result = inflate(&d_stream, Z_NO_FLUSH); if( ( result != Z_OK ) && ( result != Z_STREAM_END ) ) { msg_Err( p_this, "Zlib decompression failed. Result: %d", result ); inflateEnd( &d_stream ); block_Release( p_block ); return p_in_block; } } while( ( d_stream.avail_out == 0 ) && ( d_stream.avail_in != 0 ) && ( result != Z_STREAM_END ) ); dstsize = d_stream.total_out; inflateEnd( &d_stream ); p_block = block_Realloc( p_block, 0, dstsize ); p_block->i_buffer = dstsize; block_Release( p_in_block ); return p_block; } #endif /* Utility function for BlockDecode */ block_t *MemToBlock( uint8_t *p_mem, size_t i_mem, size_t offset) { if( unlikely( i_mem > SIZE_MAX - offset ) ) return NULL; block_t *p_block = block_Alloc( i_mem + offset ); if( likely(p_block != NULL) ) { memcpy( p_block->p_buffer + offset, p_mem, i_mem ); } return p_block; } void handle_real_audio(demux_t * p_demux, mkv_track_t * p_tk, block_t * p_blk, mtime_t i_pts) { uint8_t * p_frame = p_blk->p_buffer; Cook_PrivateTrackData * p_sys = (Cook_PrivateTrackData *) p_tk->p_sys; size_t size = p_blk->i_buffer; if( p_tk->i_last_dts == VLC_TS_INVALID ) { for( size_t i = 0; i < p_sys->i_subpackets; i++) if( p_sys->p_subpackets[i] ) { block_Release(p_sys->p_subpackets[i]); p_sys->p_subpackets[i] = NULL; } p_sys->i_subpacket = 0; } if( p_tk->fmt.i_codec == VLC_CODEC_COOK || p_tk->fmt.i_codec == VLC_CODEC_ATRAC3 ) { const uint16_t i_num = p_sys->i_frame_size / p_sys->i_subpacket_size; const size_t y = p_sys->i_subpacket / ( p_sys->i_frame_size / p_sys->i_subpacket_size ); for( uint16_t i = 0; i < i_num; i++ ) { size_t i_index = (size_t) p_sys->i_sub_packet_h * i + ((p_sys->i_sub_packet_h + 1) / 2) * (y&1) + (y>>1); if( i_index >= p_sys->i_subpackets ) return; block_t *p_block = block_Alloc( p_sys->i_subpacket_size ); if( !p_block ) return; if( size < p_sys->i_subpacket_size ) return; memcpy( p_block->p_buffer, p_frame, p_sys->i_subpacket_size ); p_block->i_dts = VLC_TS_INVALID; p_block->i_pts = VLC_TS_INVALID; if( !p_sys->i_subpacket ) { p_tk->i_last_dts = p_block->i_pts = i_pts + VLC_TS_0; } p_frame += p_sys->i_subpacket_size; size -= p_sys->i_subpacket_size; p_sys->i_subpacket++; p_sys->p_subpackets[i_index] = p_block; } } else { /*TODO*/ } if( p_sys->i_subpacket == p_sys->i_subpackets ) { for( size_t i = 0; i < p_sys->i_subpackets; i++) { es_out_Send( p_demux->out, p_tk->p_es, p_sys->p_subpackets[i]); p_sys->p_subpackets[i] = NULL; } p_sys->i_subpacket = 0; } } int32_t Cook_PrivateTrackData::Init() { i_subpackets = (size_t) i_sub_packet_h * (size_t) i_frame_size / (size_t) i_subpacket_size; p_subpackets = (block_t**) calloc(i_subpackets, sizeof(block_t*)); if( unlikely( !p_subpackets ) ) { i_subpackets = 0; return 1; } return 0; } Cook_PrivateTrackData::~Cook_PrivateTrackData() { for( size_t i = 0; i < i_subpackets; i++ ) if( p_subpackets[i] ) block_Release( p_subpackets[i] ); free( p_subpackets ); } static inline void fill_wvpk_block(uint16_t version, uint32_t block_samples, uint32_t flags, uint32_t crc, uint8_t * src, size_t srclen, uint8_t * dst) { const uint8_t wvpk_header[] = {'w','v','p','k', /* ckId */ 0x0, 0x0, 0x0, 0x0, /* ckSize */ 0x0, 0x0, /* version */ 0x0, /* track_no */ 0x0, /* index_no */ 0xFF, 0xFF, 0xFF, 0xFF, /* total_samples */ 0x0, 0x0, 0x0, 0x0 }; /* block_index */ memcpy( dst, wvpk_header, sizeof( wvpk_header ) ); SetDWLE( dst + 4, srclen + 24 ); SetWLE( dst + 8, version ); SetDWLE( dst + 20, block_samples ); SetDWLE( dst + 24, flags ); SetDWLE( dst + 28, crc ); memcpy( dst + 32, src, srclen ); } block_t * packetize_wavpack( mkv_track_t * p_tk, uint8_t * buffer, size_t size) { uint16_t version = 0x403; uint32_t block_samples; uint32_t flags; uint32_t crc; block_t * p_block = NULL; if( p_tk->i_extra_data >= 2 ) version = GetWLE( p_tk->p_extra_data ); if( size < 12 ) return NULL; block_samples = GetDWLE(buffer); buffer += 4; flags = GetDWLE(buffer); size -= 4; /* Check if WV_INITIAL_BLOCK and WV_FINAL_BLOCK are present */ if( ( flags & 0x1800 ) == 0x1800 ) { crc = GetDWLE(buffer+4); buffer += 8; size -= 8; p_block = block_Alloc( size + 32 ); if( !p_block ) return NULL; fill_wvpk_block(version, block_samples, flags, crc, buffer, size, p_block->p_buffer); } else { /* Multiblock */ size_t total_size = 0; p_block = block_Alloc( 0 ); if( !p_block ) return NULL; while(size >= 12) { flags = GetDWLE(buffer); buffer += 4; crc = GetDWLE(buffer); buffer += 4; uint32_t bsz = GetDWLE(buffer); buffer+= 4; size -= 12; bsz = (bsz < size)?bsz:size; total_size += bsz + 32; assert(total_size >= p_block->i_buffer); p_block = block_Realloc( p_block, 0, total_size ); if( !p_block ) return NULL; fill_wvpk_block(version, block_samples, flags, crc, buffer, bsz, p_block->p_buffer + total_size - bsz - 32 ); buffer += bsz; size -= bsz; } } return p_block; } <|endoftext|>
<commit_before>/* Copyright 2013-present Barefoot Networks, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Antonin Bas (antonin@barefootnetworks.com) * */ #include <PI/pi.h> #include <PI/target/pi_imp.h> #include <string> #include <cstring> // for memset #include "conn_mgr.h" #include "common.h" #include "cpu_send_recv.h" #define NUM_DEVICES 256 namespace pibmv2 { conn_mgr_t *conn_mgr_state = NULL; device_info_t device_info_state[NUM_DEVICES]; extern void start_learn_listener(const std::string &addr, int rpc_port_num); extern void stop_learn_listener(); } // namespace pibmv2 namespace { pibmv2::CpuSendRecv *cpu_send_recv = nullptr; } // namespace extern "C" { pi_status_t _pi_init(void *extra) { (void) extra; memset(pibmv2::device_info_state, 0, sizeof(pibmv2::device_info_state)); pibmv2::conn_mgr_state = pibmv2::conn_mgr_create(); cpu_send_recv = new pibmv2::CpuSendRecv(); cpu_send_recv->start(); return PI_STATUS_SUCCESS; } pi_status_t _pi_assign_device(pi_dev_id_t dev_id, const pi_p4info_t *p4info, pi_assign_extra_t *extra) { pibmv2::device_info_t *d_info = pibmv2::get_device_info(dev_id); assert(!d_info->assigned); int rpc_port_num = -1; std::string bm_notifications_addr(""); for (; !extra->end_of_extras; extra++) { std::string key(extra->key); if (key == "port" && extra->v) { try { rpc_port_num = std::stoi(std::string(extra->v), nullptr, 0); } catch (const std::exception& e) { return PI_STATUS_INVALID_INIT_EXTRA_PARAM; } } else if (key == "notifications" && extra->v) { bm_notifications_addr = std::string(extra->v); } else if (key == "cpu_iface" && extra->v) { int rc = cpu_send_recv->add_device(std::string(extra->v), dev_id); if (rc < 0) return PI_STATUS_INVALID_INIT_EXTRA_PARAM; } } if (rpc_port_num == -1) return PI_STATUS_MISSING_INIT_EXTRA_PARAM; if (conn_mgr_client_init(pibmv2::conn_mgr_state, dev_id, rpc_port_num)) return PI_STATUS_TARGET_TRANSPORT_ERROR; if (bm_notifications_addr != "") pibmv2::start_learn_listener(bm_notifications_addr, rpc_port_num); d_info->p4info = p4info; d_info->assigned = 1; return PI_STATUS_SUCCESS; } pi_status_t _pi_update_device_start(pi_dev_id_t dev_id, const pi_p4info_t *p4info, const char *device_data, size_t device_data_size) { pibmv2::device_info_t *d_info = pibmv2::get_device_info(dev_id); std::string new_config(device_data, device_data_size); auto client = conn_mgr_client(pibmv2::conn_mgr_state, dev_id); try { client.c->bm_load_new_config(std::move(new_config)); } catch (InvalidSwapOperation &iso) { const char *what = _SwapOperationErrorCode_VALUES_TO_NAMES.find(iso.code)->second; std::cout << "Invalid swap operation (" << iso.code << "): " << what << std::endl; return static_cast<pi_status_t>(PI_STATUS_TARGET_ERROR + iso.code); } d_info->p4info = p4info; return PI_STATUS_SUCCESS; } pi_status_t _pi_update_device_end(pi_dev_id_t dev_id) { auto client = conn_mgr_client(pibmv2::conn_mgr_state, dev_id); try { client.c->bm_swap_configs(); } catch (InvalidSwapOperation &iso) { const char *what = _SwapOperationErrorCode_VALUES_TO_NAMES.find(iso.code)->second; std::cout << "Invalid swap operation (" << iso.code << "): " << what << std::endl; return static_cast<pi_status_t>(PI_STATUS_TARGET_ERROR + iso.code); } return PI_STATUS_SUCCESS; } pi_status_t _pi_remove_device(pi_dev_id_t dev_id) { pibmv2::device_info_t *d_info = pibmv2::get_device_info(dev_id); assert(d_info->assigned); pibmv2::conn_mgr_client_close(pibmv2::conn_mgr_state, dev_id); cpu_send_recv->remove_device(dev_id); d_info->assigned = 0; return PI_STATUS_SUCCESS; } pi_status_t _pi_destroy() { pibmv2::conn_mgr_destroy(pibmv2::conn_mgr_state); pibmv2::stop_learn_listener(); delete cpu_send_recv; return PI_STATUS_SUCCESS; } // bmv2 does not support transaction and has no use for the session_handle pi_status_t _pi_session_init(pi_session_handle_t *session_handle) { *session_handle = 0; return PI_STATUS_SUCCESS; } pi_status_t _pi_session_cleanup(pi_session_handle_t session_handle) { (void) session_handle; return PI_STATUS_SUCCESS; } pi_status_t _pi_packetout_send(pi_dev_id_t dev_id, const char *pkt, size_t size) { if (cpu_send_recv->send_pkt(dev_id, pkt, size) != static_cast<int>(size)) return PI_STATUS_PACKETOUT_SEND_ERROR; return PI_STATUS_SUCCESS; } } <commit_msg>fixed typo in bmv2 CPU receiver<commit_after>/* Copyright 2013-present Barefoot Networks, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Antonin Bas (antonin@barefootnetworks.com) * */ #include <PI/pi.h> #include <PI/target/pi_imp.h> #include <string> #include <cstring> // for memset #include "conn_mgr.h" #include "common.h" #include "cpu_send_recv.h" #define NUM_DEVICES 256 namespace pibmv2 { conn_mgr_t *conn_mgr_state = NULL; device_info_t device_info_state[NUM_DEVICES]; extern void start_learn_listener(const std::string &addr, int rpc_port_num); extern void stop_learn_listener(); } // namespace pibmv2 namespace { pibmv2::CpuSendRecv *cpu_send_recv = nullptr; } // namespace extern "C" { pi_status_t _pi_init(void *extra) { (void) extra; memset(pibmv2::device_info_state, 0, sizeof(pibmv2::device_info_state)); pibmv2::conn_mgr_state = pibmv2::conn_mgr_create(); cpu_send_recv = new pibmv2::CpuSendRecv(); cpu_send_recv->start(); return PI_STATUS_SUCCESS; } pi_status_t _pi_assign_device(pi_dev_id_t dev_id, const pi_p4info_t *p4info, pi_assign_extra_t *extra) { pibmv2::device_info_t *d_info = pibmv2::get_device_info(dev_id); assert(!d_info->assigned); int rpc_port_num = -1; std::string bm_notifications_addr(""); for (; !extra->end_of_extras; extra++) { std::string key(extra->key); if (key == "port" && extra->v) { try { rpc_port_num = std::stoi(std::string(extra->v), nullptr, 0); } catch (const std::exception& e) { return PI_STATUS_INVALID_INIT_EXTRA_PARAM; } } else if (key == "notifications" && extra->v) { bm_notifications_addr = std::string(extra->v); } else if (key == "cpu_iface" && extra->v) { int rc = cpu_send_recv->add_device(std::string(extra->v), dev_id); if (rc < 0) return PI_STATUS_INVALID_INIT_EXTRA_PARAM; } } if (rpc_port_num == -1) return PI_STATUS_MISSING_INIT_EXTRA_PARAM; if (conn_mgr_client_init(pibmv2::conn_mgr_state, dev_id, rpc_port_num)) return PI_STATUS_TARGET_TRANSPORT_ERROR; if (bm_notifications_addr != "") pibmv2::start_learn_listener(bm_notifications_addr, rpc_port_num); d_info->p4info = p4info; d_info->assigned = 1; return PI_STATUS_SUCCESS; } pi_status_t _pi_update_device_start(pi_dev_id_t dev_id, const pi_p4info_t *p4info, const char *device_data, size_t device_data_size) { pibmv2::device_info_t *d_info = pibmv2::get_device_info(dev_id); std::string new_config(device_data, device_data_size); auto client = conn_mgr_client(pibmv2::conn_mgr_state, dev_id); try { client.c->bm_load_new_config(std::move(new_config)); } catch (InvalidSwapOperation &iso) { const char *what = _SwapOperationErrorCode_VALUES_TO_NAMES.find(iso.code)->second; std::cout << "Invalid swap operation (" << iso.code << "): " << what << std::endl; return static_cast<pi_status_t>(PI_STATUS_TARGET_ERROR + iso.code); } d_info->p4info = p4info; return PI_STATUS_SUCCESS; } pi_status_t _pi_update_device_end(pi_dev_id_t dev_id) { auto client = conn_mgr_client(pibmv2::conn_mgr_state, dev_id); try { client.c->bm_swap_configs(); } catch (InvalidSwapOperation &iso) { const char *what = _SwapOperationErrorCode_VALUES_TO_NAMES.find(iso.code)->second; std::cout << "Invalid swap operation (" << iso.code << "): " << what << std::endl; return static_cast<pi_status_t>(PI_STATUS_TARGET_ERROR + iso.code); } return PI_STATUS_SUCCESS; } pi_status_t _pi_remove_device(pi_dev_id_t dev_id) { pibmv2::device_info_t *d_info = pibmv2::get_device_info(dev_id); assert(d_info->assigned); pibmv2::conn_mgr_client_close(pibmv2::conn_mgr_state, dev_id); cpu_send_recv->remove_device(dev_id); d_info->assigned = 0; return PI_STATUS_SUCCESS; } pi_status_t _pi_destroy() { pibmv2::conn_mgr_destroy(pibmv2::conn_mgr_state); pibmv2::stop_learn_listener(); delete cpu_send_recv; return PI_STATUS_SUCCESS; } // bmv2 does not support transaction and has no use for the session_handle pi_status_t _pi_session_init(pi_session_handle_t *session_handle) { *session_handle = 0; return PI_STATUS_SUCCESS; } pi_status_t _pi_session_cleanup(pi_session_handle_t session_handle) { (void) session_handle; return PI_STATUS_SUCCESS; } pi_status_t _pi_packetout_send(pi_dev_id_t dev_id, const char *pkt, size_t size) { if (cpu_send_recv->send_pkt(dev_id, pkt, size) != 0) return PI_STATUS_PACKETOUT_SEND_ERROR; return PI_STATUS_SUCCESS; } } <|endoftext|>
<commit_before>/** * Appcelerator Kroll - licensed under the Apache Public License 2 * see LICENSE in the root folder for details on the license. * Copyright (c) 2009 Appcelerator, Inc. All Rights Reserved. */ #include <signal.h> #include "php_module.h" #include <Poco/Path.h> #ifdef ZTS void ***tsrm_ls; #endif namespace kroll { KROLL_MODULE(PHPModule, STRING(MODULE_NAME), STRING(MODULE_VERSION)); static Logger* logger = Logger::Get("PHPModule"); const static std::string phpSuffix("module.php"); static bool buffering = false; PHPModule* PHPModule::instance_ = NULL; std::ostringstream PHPModule::buffer; std::string PHPModule::mimeType("text/html"); static int UnbufferedWrite(const char *, unsigned int TSRMLS_DC); static void SetIniDefault(HashTable*, const char*, const char*); static void IniDefaults(HashTable*); static void LogMessage(char*); static int HeaderHandler(sapi_header_struct*, sapi_header_op_enum, sapi_headers_struct* TSRMLS_DC); void PHPModule::Initialize() { PHPModule::instance_ = this; int argc = 1; char *argv[2] = { "php_kroll", NULL }; php_embed_module.ub_write = UnbufferedWrite; php_embed_module.log_message = LogMessage; php_embed_module.ini_defaults = IniDefaults; php_embed_module.header_handler = HeaderHandler; php_embed_init(argc, argv PTSRMLS_CC); PHPUtils::InitializePHPKrollClasses(); this->InitializeBinding(); host->AddModuleProvider(this); const char* resourcesPath = host->GetApplication()->GetResourcesPath().c_str(); zend_alter_ini_entry("include_path", sizeof("include_path"), (char*) resourcesPath, strlen(resourcesPath), ZEND_INI_USER, ZEND_INI_STAGE_RUNTIME); } /*static*/ void PHPModule::SetBuffering(bool newBuffering) { if (buffering) { buffer.str(""); } buffering = newBuffering; } void PHPModule::Stop() { PHPModule::instance_ = NULL; SharedKObject global = this->host->GetGlobalObject(); Script::GetInstance()->RemoveScriptEvaluator(this->binding); global->Set("PHP", Value::Undefined); this->binding->Set("evaluate", Value::Undefined); this->binding = 0; PHPModule::instance_ = 0; php_embed_shutdown(TSRMLS_C); } void PHPModule::InitializeBinding() { PHPModule::mimeType = SG(default_mimetype); SharedKObject global = this->host->GetGlobalObject(); this->binding = new PHPEvaluator(); global->Set("PHP", Value::NewObject(this->binding)); Script::GetInstance()->AddScriptEvaluator(this->binding); zval *titaniumValue = PHPUtils::ToPHPValue(Value::NewObject(global)); ZEND_SET_SYMBOL(&EG(symbol_table), PRODUCT_NAME, titaniumValue); } bool PHPModule::IsModule(std::string& path) { return (path.substr(path.length()-phpSuffix.length()) == phpSuffix); } Module* PHPModule::CreateModule(std::string& path) { zend_first_try { std::string includeScript = "include '" + path + "';"; if (SUCCESS != zend_eval_string((char *) includeScript.c_str(), NULL, (char *) path.c_str() TSRMLS_CC)) logger->Error("Error evaluating module at path: %s", path.c_str()); } zend_catch { logger->Error("Error evaluating module at path: %s", path.c_str()); } zend_end_try(); Poco::Path p(path); std::string name(p.getBaseName()); std::string moduledir(p.makeParent().toString()); logger->Info("Loading PHP module name=%s path=%s", name.c_str(), path.c_str()); return new PHPModuleInstance(host, path, moduledir, name); } static int UnbufferedWrite(const char *str, unsigned int length TSRMLS_DC) { std::string string(str, length); std::ostringstream& buffer = PHPModule::GetBuffer(); // This shouldn't need to be thread safe right? if (buffering) { buffer << string; } else { logger->Info(string.c_str()); } return length; } static void SetIniDefault(HashTable* config, const char* name, const char* value) { // Forgive me Martin, borrowed from php_cli.c line 409 // Thou are forgiven. zval tmp; Z_SET_REFCOUNT(tmp, 0); Z_UNSET_ISREF(tmp); ZVAL_STRINGL(&tmp, zend_strndup(value, sizeof(value)-1), sizeof(value)-1, 0); zend_hash_update(config, name, sizeof(name), &tmp, sizeof(zval), NULL); } static void IniDefaults(HashTable* configuration) { SetIniDefault(configuration, "display_errors", "1"); } static void LogMessage(char* message) { logger->Debug(message); } static int HeaderHandler(sapi_header_struct* sapiHeader, sapi_header_op_enum op, sapi_headers_struct* sapiHeaders TSRMLS_DC) { if (sapiHeaders && sapiHeaders->mimetype) { std::string& mimeType = PHPModule::GetMimeType(); mimeType = sapiHeaders->mimetype; } return op; } } <commit_msg>Fix for invalid memory access issue in PHP Module.<commit_after>/** * Appcelerator Kroll - licensed under the Apache Public License 2 * see LICENSE in the root folder for details on the license. * Copyright (c) 2009 Appcelerator, Inc. All Rights Reserved. */ #include <signal.h> #include "php_module.h" #include <Poco/Path.h> #ifdef ZTS void ***tsrm_ls; #endif namespace kroll { KROLL_MODULE(PHPModule, STRING(MODULE_NAME), STRING(MODULE_VERSION)); static Logger* logger = Logger::Get("PHPModule"); const static std::string phpSuffix("module.php"); static bool buffering = false; PHPModule* PHPModule::instance_ = NULL; std::ostringstream PHPModule::buffer; std::string PHPModule::mimeType("text/html"); static int UnbufferedWrite(const char *, unsigned int TSRMLS_DC); static void SetIniDefault(HashTable*, const char*, const char*); static void IniDefaults(HashTable*); static void LogMessage(char*); static int HeaderHandler(sapi_header_struct*, sapi_header_op_enum, sapi_headers_struct* TSRMLS_DC); void PHPModule::Initialize() { PHPModule::instance_ = this; int argc = 1; char *argv[2] = { "php_kroll", NULL }; php_embed_module.ub_write = UnbufferedWrite; php_embed_module.log_message = LogMessage; php_embed_module.ini_defaults = IniDefaults; php_embed_module.header_handler = HeaderHandler; php_embed_init(argc, argv PTSRMLS_CC); PHPUtils::InitializePHPKrollClasses(); this->InitializeBinding(); host->AddModuleProvider(this); std::string resourcesPath(host->GetApplication()->GetResourcesPath()); zend_alter_ini_entry("include_path", sizeof("include_path"), (char*) resourcesPath.c_str(), resourcesPath.size() - 1, ZEND_INI_USER, ZEND_INI_STAGE_RUNTIME); } /*static*/ void PHPModule::SetBuffering(bool newBuffering) { if (buffering) { buffer.str(""); } buffering = newBuffering; } void PHPModule::Stop() { PHPModule::instance_ = NULL; SharedKObject global = this->host->GetGlobalObject(); Script::GetInstance()->RemoveScriptEvaluator(this->binding); global->Set("PHP", Value::Undefined); this->binding->Set("evaluate", Value::Undefined); this->binding = 0; PHPModule::instance_ = 0; php_embed_shutdown(TSRMLS_C); } void PHPModule::InitializeBinding() { PHPModule::mimeType = SG(default_mimetype); SharedKObject global = this->host->GetGlobalObject(); this->binding = new PHPEvaluator(); global->Set("PHP", Value::NewObject(this->binding)); Script::GetInstance()->AddScriptEvaluator(this->binding); zval *titaniumValue = PHPUtils::ToPHPValue(Value::NewObject(global)); ZEND_SET_SYMBOL(&EG(symbol_table), PRODUCT_NAME, titaniumValue); } bool PHPModule::IsModule(std::string& path) { return (path.substr(path.length()-phpSuffix.length()) == phpSuffix); } Module* PHPModule::CreateModule(std::string& path) { zend_first_try { std::string includeScript = "include '" + path + "';"; if (SUCCESS != zend_eval_string((char *) includeScript.c_str(), NULL, (char *) path.c_str() TSRMLS_CC)) logger->Error("Error evaluating module at path: %s", path.c_str()); } zend_catch { logger->Error("Error evaluating module at path: %s", path.c_str()); } zend_end_try(); Poco::Path p(path); std::string name(p.getBaseName()); std::string moduledir(p.makeParent().toString()); logger->Info("Loading PHP module name=%s path=%s", name.c_str(), path.c_str()); return new PHPModuleInstance(host, path, moduledir, name); } static int UnbufferedWrite(const char *str, unsigned int length TSRMLS_DC) { std::string string(str, length); std::ostringstream& buffer = PHPModule::GetBuffer(); // This shouldn't need to be thread safe right? if (buffering) { buffer << string; } else { logger->Info(string.c_str()); } return length; } static void SetIniDefault(HashTable* config, const char* name, const char* value) { // Forgive me Martin, borrowed from php_cli.c line 409 // Thou are forgiven. zval tmp; Z_SET_REFCOUNT(tmp, 0); Z_UNSET_ISREF(tmp); ZVAL_STRINGL(&tmp, zend_strndup(value, sizeof(value)-1), sizeof(value)-1, 0); zend_hash_update(config, name, sizeof(name), &tmp, sizeof(zval), NULL); } static void IniDefaults(HashTable* configuration) { SetIniDefault(configuration, "display_errors", "1"); } static void LogMessage(char* message) { logger->Debug(message); } static int HeaderHandler(sapi_header_struct* sapiHeader, sapi_header_op_enum op, sapi_headers_struct* sapiHeaders TSRMLS_DC) { if (sapiHeaders && sapiHeaders->mimetype) { std::string& mimeType = PHPModule::GetMimeType(); mimeType = sapiHeaders->mimetype; } return op; } } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: brwview.hxx,v $ * * $Revision: 1.1 $ * * last change: $Author: oj $ $Date: 2000-10-26 14:45:26 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _SBX_BRWVIEW_HXX #define _SBX_BRWVIEW_HXX #ifndef _SV_WINDOW_HXX //autogen #include <vcl/window.hxx> #endif #ifndef _TOOLBOX_HXX //autogen #include <vcl/toolbox.hxx> #endif #ifndef _TOOLS_RESID_HXX //autogen wg. ResId #include <tools/resid.hxx> #endif #ifndef _COM_SUN_STAR_AWT_XCONTROLCONTAINER_HPP_ #include <com/sun/star/awt/XControlContainer.hpp> #endif #ifndef _COM_SUN_STAR_AWT_POSSIZE_HPP_ #include <com/sun/star/awt/PosSize.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_ #include <com/sun/star/lang/XMultiServiceFactory.hpp> #endif #ifndef _COM_SUN_STAR_UNO_REFERENCE_HXX_ #include <com/sun/star/uno/Reference.hxx> #endif // ========================================================================= class ResMgr; class Splitter; namespace dbaui { class DBTreeListModel; class DBTreeView; class SbaGridControl; class UnoDataBrowserView : public Window { protected: ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControlContainer > m_xMe; // our own UNO representation ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControl > m_xGrid; // our grid's UNO representation ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > m_xServiceFactory; // the service factory to work with DBTreeView* m_pTreeView; Splitter* m_pSplitter; ToolBox* m_pToolBox; // our toolbox (may be NULL) SbaGridControl* m_pVclControl; // our grid's VCL representation DECL_LINK( SplitHdl, void* ); // attribute access public: ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControl > getGridControl() const { return m_xGrid; } SbaGridControl* getVclControl() const { return m_pVclControl; } ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControlContainer > getContainer() const { return m_xMe; } ToolBox* getToolBox() const { return m_pToolBox; } public: UnoDataBrowserView(Window* pParent, const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& ); virtual ~UnoDataBrowserView(); /// late construction virtual void Construct(const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControlModel >& xModel); /** as columns may be hidden there is a difference between a columns model pos and its view pos so we you may use these translation function */ sal_uInt16 Model2ViewPos(sal_uInt16 nPos) const; sal_uInt16 View2ModelPos(sal_uInt16 nPos) const; /// for the same reason the view column count isn't the same as the model column count sal_uInt16 ViewColumnCount() const; /** use this if you want to have a ToolBox to be displayed at the top of the grid control The ownership of the window specified by pTB is transfered to this view object itself, i.e. it is deleted in the destructor (or in the next call to setToolBox). Specify a NULL pointer if you want to remove an existing ToolBox. */ void setToolBox(ToolBox* pTB); void setSplitter(Splitter* _pSplitter); void setTreeView(DBTreeView* _pTreeView); protected: // window overridables virtual void Resize(); virtual void GetFocus(); }; } #endif // _SBX_BRWVIEW_HXX <commit_msg>Resize is public now<commit_after>/************************************************************************* * * $RCSfile: brwview.hxx,v $ * * $Revision: 1.2 $ * * last change: $Author: fs $ $Date: 2000-12-08 21:12:31 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _SBX_BRWVIEW_HXX #define _SBX_BRWVIEW_HXX #ifndef _SV_WINDOW_HXX //autogen #include <vcl/window.hxx> #endif #ifndef _TOOLBOX_HXX //autogen #include <vcl/toolbox.hxx> #endif #ifndef _TOOLS_RESID_HXX //autogen wg. ResId #include <tools/resid.hxx> #endif #ifndef _COM_SUN_STAR_AWT_XCONTROLCONTAINER_HPP_ #include <com/sun/star/awt/XControlContainer.hpp> #endif #ifndef _COM_SUN_STAR_AWT_POSSIZE_HPP_ #include <com/sun/star/awt/PosSize.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_ #include <com/sun/star/lang/XMultiServiceFactory.hpp> #endif #ifndef _COM_SUN_STAR_UNO_REFERENCE_HXX_ #include <com/sun/star/uno/Reference.hxx> #endif // ========================================================================= class ResMgr; class Splitter; namespace dbaui { class DBTreeListModel; class DBTreeView; class SbaGridControl; class UnoDataBrowserView : public Window { protected: ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControlContainer > m_xMe; // our own UNO representation ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControl > m_xGrid; // our grid's UNO representation ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > m_xServiceFactory; // the service factory to work with DBTreeView* m_pTreeView; Splitter* m_pSplitter; ToolBox* m_pToolBox; // our toolbox (may be NULL) SbaGridControl* m_pVclControl; // our grid's VCL representation DECL_LINK( SplitHdl, void* ); // attribute access public: ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControl > getGridControl() const { return m_xGrid; } SbaGridControl* getVclControl() const { return m_pVclControl; } ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControlContainer > getContainer() const { return m_xMe; } ToolBox* getToolBox() const { return m_pToolBox; } public: UnoDataBrowserView(Window* pParent, const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& ); virtual ~UnoDataBrowserView(); /// late construction virtual void Construct(const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControlModel >& xModel); /** as columns may be hidden there is a difference between a columns model pos and its view pos so we you may use these translation function */ sal_uInt16 Model2ViewPos(sal_uInt16 nPos) const; sal_uInt16 View2ModelPos(sal_uInt16 nPos) const; /// for the same reason the view column count isn't the same as the model column count sal_uInt16 ViewColumnCount() const; /** use this if you want to have a ToolBox to be displayed at the top of the grid control The ownership of the window specified by pTB is transfered to this view object itself, i.e. it is deleted in the destructor (or in the next call to setToolBox). Specify a NULL pointer if you want to remove an existing ToolBox. */ void setToolBox(ToolBox* pTB); void setSplitter(Splitter* _pSplitter); void setTreeView(DBTreeView* _pTreeView); // window overridables virtual void Resize(); protected: virtual void GetFocus(); }; } #endif // _SBX_BRWVIEW_HXX <|endoftext|>
<commit_before>/// @file Merge.cpp /// /// The merging unit. /// /// @par Full Description /// The class defines the merging entity. /// /// @ingroup Merge /// /// @par Copyright (c) 2016 vcdMaker team /// /// Permission is hereby granted, free of charge, to any person obtaining a /// copy of this software and associated documentation files (the "Software"), /// to deal in the Software without restriction, including without limitation /// the rights to use, copy, modify, merge, publish, distribute, sublicense, /// and/or sell copies of the Software, and to permit persons to whom the /// Software is furnished to do so, subject to the following conditions: /// /// The above copyright notice and this permission notice shall be included /// in all copies or substantial portions of the Software. /// /// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS /// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, /// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL /// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER /// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, /// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS /// IN THE SOFTWARE. #include <algorithm> #include <ratio> #include "Merge.h" #include "Utils.h" const uint64_t MERGE::Merge::TEN_POWER[] = { 1ull, static_cast<uint64_t>(std::kilo::num), static_cast<uint64_t>(std::mega::num), static_cast<uint64_t>(std::giga::num), static_cast<uint64_t>(std::tera::num), static_cast<uint64_t>(std::peta::num) }; void MERGE::Merge::Run() { // Find the minimum merging unit. m_MinTimeUnit = FindMinUnit(); // If the output time unit is not forced use the minimum value. if (m_TimeUnit.empty()) { // The minimum time unit used in sources. m_TimeUnit = m_MinTimeUnit; } // Create the output signal database and set its base time unit. m_pMerged = std::make_unique<SIGNAL::SignalDb>(m_TimeUnit); // Find the longest leading time for among all sources. m_MaxLeadingTime = FindMaxLeadingTime(); // Merge Sources. for (const SignalSource *source : m_Sources) { // Get the source's time unit. const std::string sourceTimeUnit = source->GetTimeUnit(); // Source sync time in the target unit. const uint64_t transformedSourceSync = TransformTimestamp(source->GetSyncPoint(), m_MinTimeUnit, sourceTimeUnit); // Merge signals here. for (auto current_signal : source->Get()->GetSignals()) { SIGNAL::Signal *signal = current_signal->Clone(); // Set the signal's new timestamp. signal->SetTimestamp(CalculateNewTime(TransformTimestamp(signal->GetTimestamp(), m_MinTimeUnit, sourceTimeUnit), transformedSourceSync)); // Update its name. signal->SetName(source->GetPrefix() + signal->GetName()); // Add to the output signals database. m_pMerged->Add(signal); } } } std::string MERGE::Merge::FindMinUnit() { size_t maxIndex = 0; for (const SignalSource *const source : m_Sources) { const size_t index = UTILS::GetTimeUnitIndex(source->GetTimeUnit()); maxIndex = std::max(index, maxIndex); } return SIGNAL::Signal::TIME_UNITS[maxIndex]; } uint64_t MERGE::Merge::FindMaxLeadingTime() { uint64_t maxLeadingTime = 0; for (const SignalSource *const source : m_Sources) { uint64_t leadingTime = TransformTimestamp(source->GetLeadingTime(), m_MinTimeUnit, source->GetTimeUnit()); maxLeadingTime = std::max(leadingTime, maxLeadingTime); } return maxLeadingTime; } uint64_t MERGE::Merge::TransformTimestamp(uint64_t time, const std::string &targetTimeUnit, const std::string &sourceTimeUnit) { uint64_t newTime = time; uint32_t nominator = 0; uint32_t denominator = 0; const uint32_t targetPower = UTILS::GetTimeUnitIndex(targetTimeUnit); const uint32_t sourcePower = UTILS::GetTimeUnitIndex(sourceTimeUnit); if (targetPower > sourcePower) { nominator = (targetPower - sourcePower); } else if (targetPower < sourcePower) { denominator = (sourcePower - targetPower); /// @todo Range checking must be done. newTime = time + (TEN_POWER[denominator]) / 2); } const double unitsRatio = static_cast<double>(TEN_POWER[nominator]) / TEN_POWER[denominator]; /// @todo Range checking must be done. return static_cast<uint64_t>(newTime * unitsRatio); } uint64_t MERGE::Merge::CalculateNewTime(uint64_t time, uint64_t syncPoint) { /// @todo Detect uint64_t overflow. return (TransformTimestamp(time + m_MaxLeadingTime - syncPoint, m_TimeUnit, m_MinTimeUnit)); } <commit_msg>Typo fix (compilation error)<commit_after>/// @file Merge.cpp /// /// The merging unit. /// /// @par Full Description /// The class defines the merging entity. /// /// @ingroup Merge /// /// @par Copyright (c) 2016 vcdMaker team /// /// Permission is hereby granted, free of charge, to any person obtaining a /// copy of this software and associated documentation files (the "Software"), /// to deal in the Software without restriction, including without limitation /// the rights to use, copy, modify, merge, publish, distribute, sublicense, /// and/or sell copies of the Software, and to permit persons to whom the /// Software is furnished to do so, subject to the following conditions: /// /// The above copyright notice and this permission notice shall be included /// in all copies or substantial portions of the Software. /// /// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS /// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, /// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL /// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER /// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, /// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS /// IN THE SOFTWARE. #include <algorithm> #include <ratio> #include "Merge.h" #include "Utils.h" const uint64_t MERGE::Merge::TEN_POWER[] = { 1ull, static_cast<uint64_t>(std::kilo::num), static_cast<uint64_t>(std::mega::num), static_cast<uint64_t>(std::giga::num), static_cast<uint64_t>(std::tera::num), static_cast<uint64_t>(std::peta::num) }; void MERGE::Merge::Run() { // Find the minimum merging unit. m_MinTimeUnit = FindMinUnit(); // If the output time unit is not forced use the minimum value. if (m_TimeUnit.empty()) { // The minimum time unit used in sources. m_TimeUnit = m_MinTimeUnit; } // Create the output signal database and set its base time unit. m_pMerged = std::make_unique<SIGNAL::SignalDb>(m_TimeUnit); // Find the longest leading time for among all sources. m_MaxLeadingTime = FindMaxLeadingTime(); // Merge Sources. for (const SignalSource *source : m_Sources) { // Get the source's time unit. const std::string sourceTimeUnit = source->GetTimeUnit(); // Source sync time in the target unit. const uint64_t transformedSourceSync = TransformTimestamp(source->GetSyncPoint(), m_MinTimeUnit, sourceTimeUnit); // Merge signals here. for (auto current_signal : source->Get()->GetSignals()) { SIGNAL::Signal *signal = current_signal->Clone(); // Set the signal's new timestamp. signal->SetTimestamp(CalculateNewTime(TransformTimestamp(signal->GetTimestamp(), m_MinTimeUnit, sourceTimeUnit), transformedSourceSync)); // Update its name. signal->SetName(source->GetPrefix() + signal->GetName()); // Add to the output signals database. m_pMerged->Add(signal); } } } std::string MERGE::Merge::FindMinUnit() { size_t maxIndex = 0; for (const SignalSource *const source : m_Sources) { const size_t index = UTILS::GetTimeUnitIndex(source->GetTimeUnit()); maxIndex = std::max(index, maxIndex); } return SIGNAL::Signal::TIME_UNITS[maxIndex]; } uint64_t MERGE::Merge::FindMaxLeadingTime() { uint64_t maxLeadingTime = 0; for (const SignalSource *const source : m_Sources) { uint64_t leadingTime = TransformTimestamp(source->GetLeadingTime(), m_MinTimeUnit, source->GetTimeUnit()); maxLeadingTime = std::max(leadingTime, maxLeadingTime); } return maxLeadingTime; } uint64_t MERGE::Merge::TransformTimestamp(uint64_t time, const std::string &targetTimeUnit, const std::string &sourceTimeUnit) { uint64_t newTime = time; uint32_t nominator = 0; uint32_t denominator = 0; const uint32_t targetPower = UTILS::GetTimeUnitIndex(targetTimeUnit); const uint32_t sourcePower = UTILS::GetTimeUnitIndex(sourceTimeUnit); if (targetPower > sourcePower) { nominator = (targetPower - sourcePower); } else if (targetPower < sourcePower) { denominator = (sourcePower - targetPower); /// @todo Range checking must be done. newTime = time + (TEN_POWER[denominator] / 2); } const double unitsRatio = static_cast<double>(TEN_POWER[nominator]) / TEN_POWER[denominator]; /// @todo Range checking must be done. return static_cast<uint64_t>(newTime * unitsRatio); } uint64_t MERGE::Merge::CalculateNewTime(uint64_t time, uint64_t syncPoint) { /// @todo Detect uint64_t overflow. return (TransformTimestamp(time + m_MaxLeadingTime - syncPoint, m_TimeUnit, m_MinTimeUnit)); } <|endoftext|>
<commit_before>/* * Copyright (C) 2015 ScyllaDB */ /* * This file is part of Scylla. * * Scylla is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Scylla is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Scylla. If not, see <http://www.gnu.org/licenses/>. */ #define BOOST_TEST_MODULE core #include <boost/test/unit_test.hpp> #include <boost/range/algorithm/copy.hpp> #include "keys.hh" #include "schema.hh" #include "schema_builder.hh" #include "types.hh" #include "idl/keys.dist.hh" #include "serializer_impl.hh" #include "idl/keys.dist.impl.hh" BOOST_AUTO_TEST_CASE(test_key_is_prefixed_by) { schema s({}, "", "", {{"c1", bytes_type}}, {{"c2", bytes_type}, {"c3", bytes_type}, {"c4", bytes_type}}, {}, {}, utf8_type); auto key = clustering_key::from_exploded(s, {bytes("a"), bytes("b"), bytes("c")}); BOOST_REQUIRE(key.is_prefixed_by(s, clustering_key_prefix::from_exploded(s, {bytes("a")}))); BOOST_REQUIRE(key.is_prefixed_by(s, clustering_key_prefix::from_exploded(s, {bytes("a"), bytes("b")}))); BOOST_REQUIRE(key.is_prefixed_by(s, clustering_key_prefix::from_exploded(s, {bytes("a"), bytes("b"), bytes("c")}))); BOOST_REQUIRE(!key.is_prefixed_by(s, clustering_key_prefix::from_exploded(s, {bytes()}))); BOOST_REQUIRE(!key.is_prefixed_by(s, clustering_key_prefix::from_exploded(s, {bytes("b"), bytes("c")}))); BOOST_REQUIRE(!key.is_prefixed_by(s, clustering_key_prefix::from_exploded(s, {bytes("a"), bytes("c"), bytes("b")}))); BOOST_REQUIRE(!key.is_prefixed_by(s, clustering_key_prefix::from_exploded(s, {bytes("abc")}))); BOOST_REQUIRE(!key.is_prefixed_by(s, clustering_key_prefix::from_exploded(s, {bytes("ab")}))); } BOOST_AUTO_TEST_CASE(test_key_component_iterator) { schema s({}, "", "", { {"c1", bytes_type} }, { {"c2", bytes_type}, {"c3", bytes_type}, {"c4", bytes_type} }, {}, {}, utf8_type); auto key = clustering_key::from_exploded(s, {bytes("a"), bytes("b"), bytes("c")}); auto i = key.begin(s); auto end = key.end(s); BOOST_REQUIRE(i != end); BOOST_REQUIRE(*i == bytes_view(bytes("a"))); ++i; BOOST_REQUIRE(i != end); BOOST_REQUIRE(*i == bytes_view(bytes("b"))); ++i; BOOST_REQUIRE(i != end); BOOST_REQUIRE(*i == bytes_view(bytes("c"))); ++i; BOOST_REQUIRE(i == end); } BOOST_AUTO_TEST_CASE(test_legacy_ordering_for_non_composite_key) { schema s({}, "", "", {{"c1", bytes_type}}, {}, {}, {}, utf8_type); auto to_key = [&s] (sstring value) { return partition_key::from_single_value(s, to_bytes(value)); }; auto cmp = [&s] (const partition_key& k1, const partition_key& k2) { return k1.legacy_tri_compare(s, k2); }; BOOST_REQUIRE(cmp(to_key("A"), to_key("B")) < 0); BOOST_REQUIRE(cmp(to_key("AA"), to_key("B")) < 0); BOOST_REQUIRE(cmp(to_key("B"), to_key("AB")) > 0); BOOST_REQUIRE(cmp(to_key("B"), to_key("A")) > 0); BOOST_REQUIRE(cmp(to_key("A"), to_key("A")) == 0); } BOOST_AUTO_TEST_CASE(test_legacy_ordering_for_composite_keys) { schema s({}, "", "", {{"c1", bytes_type}, {"c2", bytes_type}}, {}, {}, {}, utf8_type); auto to_key = [&s] (sstring v1, sstring v2) { return partition_key::from_exploded(s, std::vector<bytes>{to_bytes(v1), to_bytes(v2)}); }; auto cmp = [&s] (const partition_key& k1, const partition_key& k2) { return k1.legacy_tri_compare(s, k2); }; BOOST_REQUIRE(cmp(to_key("A", "B"), to_key("A", "B")) == 0); BOOST_REQUIRE(cmp(to_key("A", "B"), to_key("A", "C")) < 0); BOOST_REQUIRE(cmp(to_key("A", "B"), to_key("B", "B")) < 0); BOOST_REQUIRE(cmp(to_key("A", "C"), to_key("B", "B")) < 0); BOOST_REQUIRE(cmp(to_key("B", "A"), to_key("A", "A")) > 0); BOOST_REQUIRE(cmp(to_key("AA", "B"), to_key("B", "B")) > 0); BOOST_REQUIRE(cmp(to_key("A", "AA"), to_key("A", "A")) > 0); BOOST_REQUIRE(cmp(to_key("", "A"), to_key("A", "A")) < 0); BOOST_REQUIRE(cmp(to_key("A", ""), to_key("A", "A")) < 0); } BOOST_AUTO_TEST_CASE(test_conversions_between_view_and_wrapper) { schema s({}, "", "", {{"c1", bytes_type}}, {}, {}, {}, utf8_type); auto key = partition_key::from_deeply_exploded(s, {data_value(bytes("value"))}); partition_key_view key_view = key; BOOST_REQUIRE(key_view.equal(s, key)); BOOST_REQUIRE(key.equal(s, key_view)); partition_key key2 = key_view; BOOST_REQUIRE(key2.equal(s, key)); BOOST_REQUIRE(key.equal(s, key2)); BOOST_REQUIRE(*key.begin(s) == bytes("value")); } template<typename T> inline T reserialize(const T& v) { auto buf = ser::serialize_to_buffer<bytes>(v); auto in = ser::as_input_stream(buf); return ser::deserialize(in, boost::type<T>()); } BOOST_AUTO_TEST_CASE(test_serialization) { auto s = schema_builder("ks", "cf") .with_column("pk", bytes_type, column_kind::partition_key) .with_column("v", bytes_type) .build(); auto pk_value = bytes("value"); partition_key key(std::vector<bytes>({pk_value})); BOOST_REQUIRE(key.equal(*s, reserialize(key))); } <commit_msg>keys_test: add a test for nodetool_style string<commit_after>/* * Copyright (C) 2015 ScyllaDB */ /* * This file is part of Scylla. * * Scylla is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Scylla is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Scylla. If not, see <http://www.gnu.org/licenses/>. */ #define BOOST_TEST_MODULE core #include <boost/test/unit_test.hpp> #include <boost/range/algorithm/copy.hpp> #include "keys.hh" #include "schema.hh" #include "schema_builder.hh" #include "types.hh" #include "idl/keys.dist.hh" #include "serializer_impl.hh" #include "idl/keys.dist.impl.hh" BOOST_AUTO_TEST_CASE(test_key_is_prefixed_by) { schema s({}, "", "", {{"c1", bytes_type}}, {{"c2", bytes_type}, {"c3", bytes_type}, {"c4", bytes_type}}, {}, {}, utf8_type); auto key = clustering_key::from_exploded(s, {bytes("a"), bytes("b"), bytes("c")}); BOOST_REQUIRE(key.is_prefixed_by(s, clustering_key_prefix::from_exploded(s, {bytes("a")}))); BOOST_REQUIRE(key.is_prefixed_by(s, clustering_key_prefix::from_exploded(s, {bytes("a"), bytes("b")}))); BOOST_REQUIRE(key.is_prefixed_by(s, clustering_key_prefix::from_exploded(s, {bytes("a"), bytes("b"), bytes("c")}))); BOOST_REQUIRE(!key.is_prefixed_by(s, clustering_key_prefix::from_exploded(s, {bytes()}))); BOOST_REQUIRE(!key.is_prefixed_by(s, clustering_key_prefix::from_exploded(s, {bytes("b"), bytes("c")}))); BOOST_REQUIRE(!key.is_prefixed_by(s, clustering_key_prefix::from_exploded(s, {bytes("a"), bytes("c"), bytes("b")}))); BOOST_REQUIRE(!key.is_prefixed_by(s, clustering_key_prefix::from_exploded(s, {bytes("abc")}))); BOOST_REQUIRE(!key.is_prefixed_by(s, clustering_key_prefix::from_exploded(s, {bytes("ab")}))); } BOOST_AUTO_TEST_CASE(test_key_component_iterator) { schema s({}, "", "", { {"c1", bytes_type} }, { {"c2", bytes_type}, {"c3", bytes_type}, {"c4", bytes_type} }, {}, {}, utf8_type); auto key = clustering_key::from_exploded(s, {bytes("a"), bytes("b"), bytes("c")}); auto i = key.begin(s); auto end = key.end(s); BOOST_REQUIRE(i != end); BOOST_REQUIRE(*i == bytes_view(bytes("a"))); ++i; BOOST_REQUIRE(i != end); BOOST_REQUIRE(*i == bytes_view(bytes("b"))); ++i; BOOST_REQUIRE(i != end); BOOST_REQUIRE(*i == bytes_view(bytes("c"))); ++i; BOOST_REQUIRE(i == end); } BOOST_AUTO_TEST_CASE(test_legacy_ordering_for_non_composite_key) { schema s({}, "", "", {{"c1", bytes_type}}, {}, {}, {}, utf8_type); auto to_key = [&s] (sstring value) { return partition_key::from_single_value(s, to_bytes(value)); }; auto cmp = [&s] (const partition_key& k1, const partition_key& k2) { return k1.legacy_tri_compare(s, k2); }; BOOST_REQUIRE(cmp(to_key("A"), to_key("B")) < 0); BOOST_REQUIRE(cmp(to_key("AA"), to_key("B")) < 0); BOOST_REQUIRE(cmp(to_key("B"), to_key("AB")) > 0); BOOST_REQUIRE(cmp(to_key("B"), to_key("A")) > 0); BOOST_REQUIRE(cmp(to_key("A"), to_key("A")) == 0); } BOOST_AUTO_TEST_CASE(test_legacy_ordering_for_composite_keys) { schema s({}, "", "", {{"c1", bytes_type}, {"c2", bytes_type}}, {}, {}, {}, utf8_type); auto to_key = [&s] (sstring v1, sstring v2) { return partition_key::from_exploded(s, std::vector<bytes>{to_bytes(v1), to_bytes(v2)}); }; auto cmp = [&s] (const partition_key& k1, const partition_key& k2) { return k1.legacy_tri_compare(s, k2); }; BOOST_REQUIRE(cmp(to_key("A", "B"), to_key("A", "B")) == 0); BOOST_REQUIRE(cmp(to_key("A", "B"), to_key("A", "C")) < 0); BOOST_REQUIRE(cmp(to_key("A", "B"), to_key("B", "B")) < 0); BOOST_REQUIRE(cmp(to_key("A", "C"), to_key("B", "B")) < 0); BOOST_REQUIRE(cmp(to_key("B", "A"), to_key("A", "A")) > 0); BOOST_REQUIRE(cmp(to_key("AA", "B"), to_key("B", "B")) > 0); BOOST_REQUIRE(cmp(to_key("A", "AA"), to_key("A", "A")) > 0); BOOST_REQUIRE(cmp(to_key("", "A"), to_key("A", "A")) < 0); BOOST_REQUIRE(cmp(to_key("A", ""), to_key("A", "A")) < 0); } BOOST_AUTO_TEST_CASE(test_conversions_between_view_and_wrapper) { schema s({}, "", "", {{"c1", bytes_type}}, {}, {}, {}, utf8_type); auto key = partition_key::from_deeply_exploded(s, {data_value(bytes("value"))}); partition_key_view key_view = key; BOOST_REQUIRE(key_view.equal(s, key)); BOOST_REQUIRE(key.equal(s, key_view)); partition_key key2 = key_view; BOOST_REQUIRE(key2.equal(s, key)); BOOST_REQUIRE(key.equal(s, key2)); BOOST_REQUIRE(*key.begin(s) == bytes("value")); } template<typename T> inline T reserialize(const T& v) { auto buf = ser::serialize_to_buffer<bytes>(v); auto in = ser::as_input_stream(buf); return ser::deserialize(in, boost::type<T>()); } BOOST_AUTO_TEST_CASE(test_serialization) { auto s = schema_builder("ks", "cf") .with_column("pk", bytes_type, column_kind::partition_key) .with_column("v", bytes_type) .build(); auto pk_value = bytes("value"); partition_key key(std::vector<bytes>({pk_value})); BOOST_REQUIRE(key.equal(*s, reserialize(key))); } BOOST_AUTO_TEST_CASE(test_from_nodetool_style_string) { auto s1 = make_lw_shared<schema>( schema({}, "", "", { {"c1", utf8_type} }, { {"c2", bytes_type}, {"c3", bytes_type}, {"c4", bytes_type} }, {}, {}, utf8_type)); auto pk_value = bytes("value"); partition_key key1(std::vector<bytes>({pk_value})); auto key2 = partition_key::from_nodetool_style_string(s1, "value"); BOOST_REQUIRE(key1.equal(*s1, key2)); auto s2 = make_lw_shared<schema>( schema({}, "", "", { {"c1", utf8_type}, {"c2", utf8_type} }, { {"c3", bytes_type}, {"c4", bytes_type} }, {}, {}, utf8_type)); auto pk_value1 = bytes("value1"); auto pk_value2 = bytes("value2"); partition_key key3(std::vector<bytes>({pk_value1, pk_value2})); auto key4 = partition_key::from_nodetool_style_string(s2, "value1:value2"); BOOST_REQUIRE(key3.equal(*s1, key4)); } <|endoftext|>
<commit_before>/* * Copyright (c) 2016 tildearrow * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * *The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include "font.h" int font::load(const char* filename, int size) { f=TTF_OpenFont(filename, size); if (f==NULL) {return 0;} else {return 1;} curfsize=64; formatcache=new char[curfsize]; } void font::setrenderer(SDL_Renderer* r) { renderer=r; } void font::drawf(int x, int y, SDL_Color col, int align, int valign, const char* format, ...) { int chars; va_list va; va_start(va,format); while (1) { chars=vsnprintf(formatcache,curfsize,format,va); if (chars>curfsize) { delete[] formatcache; curfsize*=2; formatcache=new char[curfsize]; } else { break; } } va_end(va); string tempstring; tempstring=formatcache; draw(x,y,col,align,valign,1,tempstring); } void font::draw(int x, int y, SDL_Color col, int align, int valign, bool nocache, string text) { temps=TTF_RenderUTF8_Blended(f, text.c_str(), col); if (temps==NULL) {printf("aaaa\n");} tempt=SDL_CreateTextureFromSurface(renderer, temps); tempr.x=x-((align==1)?(temps->clip_rect.w/2):(0)); tempr.y=y-((valign==1)?(temps->clip_rect.h/2):(0)); tempr.w=temps->clip_rect.w; tempr.h=temps->clip_rect.h; SDL_RenderCopy(renderer, tempt, &temps->clip_rect, &tempr); SDL_DestroyTexture(tempt); SDL_FreeSurface(temps); } <commit_msg>fixing drawf, thanks to vasprintf<commit_after>/* * Copyright (c) 2016 tildearrow * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * *The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include "font.h" int font::load(const char* filename, int size) { f=TTF_OpenFont(filename, size); if (f==NULL) {return 0;} else {return 1;} curfsize=64; formatcache=new char[curfsize]; } void font::setrenderer(SDL_Renderer* r) { renderer=r; } void font::drawf(int x, int y, SDL_Color col, int align, int valign, const char* format, ...) { int chars; chars=0; va_list va; va_start(va,format); char* fs; vasprintf(&fs,format,va); va_end(va); string tempstring; tempstring=fs; delete[] fs; draw(x,y,col,align,valign,1,tempstring); } void font::draw(int x, int y, SDL_Color col, int align, int valign, bool nocache, string text) { temps=TTF_RenderUTF8_Blended(f, text.c_str(), col); if (temps==NULL) {printf("aaaa\n");} tempt=SDL_CreateTextureFromSurface(renderer, temps); tempr.x=x-((align==1)?(temps->clip_rect.w/2):(0)); tempr.y=y-((valign==1)?(temps->clip_rect.h/2):(0)); tempr.w=temps->clip_rect.w; tempr.h=temps->clip_rect.h; SDL_RenderCopy(renderer, tempt, &temps->clip_rect, &tempr); SDL_DestroyTexture(tempt); SDL_FreeSurface(temps); } <|endoftext|>
<commit_before><commit_msg>Bugfix: add missing `#include` line.<commit_after><|endoftext|>
<commit_before><commit_msg>Remove unnecessary `#include` line.<commit_after><|endoftext|>
<commit_before>#ifndef _internal_hpp_INCLUDED #define _internal_hpp_INCLUDED #include <cassert> #include <climits> #include <cstdio> #include <vector> /*------------------------------------------------------------------------*/ using namespace std; /*------------------------------------------------------------------------*/ #include "avg.hpp" #include "arena.hpp" #include "ema.hpp" #include "format.hpp" #include "level.hpp" #include "logging.hpp" #include "options.hpp" #include "profile.hpp" #include "queue.hpp" #include "stats.hpp" #include "timer.hpp" #include "watch.hpp" #include "flags.hpp" /*------------------------------------------------------------------------*/ namespace CaDiCaL { class Proof; class File; class Internal { friend class Solver; friend class Arena; friend struct Logger; friend struct Message; friend class Parser; friend class Proof; friend struct Queue; friend struct Stats; friend struct trail_greater; friend struct trail_smaller; friend struct bump_earlier; /*----------------------------------------------------------------------*/ // The actual state of the solver is in this section. int max_var; // maximum variable index size_t vsize; // actually allocated variable data size Var * vtab; // variable table signed char * vals; // current partial assignment signed char * phases; // saved last assignment Watches * wtab; // table of watches for all literals Flags * ftab; // seen, poison, minimized flags Queue queue; // variable move to front decision queue bool unsat; // empty clause found or learned int level; // decision level (levels.size () - 1) vector<Level> control; // 'level + 1 == levels.size ()' vector<int> trail; // assigned literals size_t propagated; // next position on trail to propagate vector<int> clause; // temporary clause in parsing & learning vector<Clause*> clauses; // ordered collection of all clauses bool iterating; // report learned unit (iteration) vector<int> bump; // seen & bumped literals in 'analyze' vector<int> levels; // decision levels of 1st UIP clause vector<int> minimized; // marked removable or poison in 'minmize' vector<Clause*> resolved; // large clauses in 'analyze' Clause * conflict; // set in 'propagation', reset in 'analyze' bool clashing_unit; // set in 'parse_dimacs' EMA fast_glue_avg; // fast exponential moving average EMA slow_glue_avg; // slow exponential moving average AVG jump_avg; // average back jump level long reduce_limit; // conflict limit for next 'reduce' long restart_limit; // conflict limit for next 'restart' long recently_resolved; // to keep recently resolved clauses int fixed_limit; // remember last number of units long reduce_inc; // reduce interval increment long reduce_inc_inc; // reduce interval increment increment Proof * proof; // trace clausal proof if non zero Options opts; // run-time options Stats stats; // statistics signed char * solution; // for debugging (like 'vals' and 'phases') vector<int> original; // original CNF for debugging vector<Timer> timers; // active timers for profiling functions Profiles profiles; // global profiled time for functions Arena arena; // memory arena for moving garbage collector Format error; // last (persistent) error message Internal * internal; // proxy to 'this' in macros (redundant) /*----------------------------------------------------------------------*/ // Internal delegates and helpers for corresponding functions in 'Solver'. // void resize (int new_max_var); void add_original_lit (int lit); // Enlarge tables. // void enlarge_vtab (int new_vsize); void enlarge_vals (int new_vsize); void enlarge (int new_max_var); // Functions for monitoring resources. // size_t vector_bytes (); void inc_bytes (size_t); void dec_bytes (size_t); double seconds (); size_t max_bytes (); size_t current_bytes (); int active_variables () const { return max_var - stats.fixed; } // Regularly reports what is going on in 'report.cpp'. // void report (char type, bool verbose = false); // Unsigned literals (abs) with checks. // int vidx (int lit) const { int idx; assert (lit), assert (lit != INT_MIN); idx = abs (lit); assert (idx <= max_var); return idx; } // Get the index of variable (with checking). // int var2idx (Var * v) const { assert (v), assert (vtab < v), assert (v <= vtab + max_var); return v - vtab; } // Unsigned version with LSB denoting sign. This is used in indexing arrays // by literals. The idea is to keep the elements in such an array for both // the positive and negated version of a literal close together. // unsigned vlit (int lit) { return (lit < 0) + 2u * (unsigned) vidx (lit); } // Helper function to access variables and watches to avoid indexing bugs. // Var & var (int lit) { return vtab [vidx (lit)]; } Watches & watches (int lit) { return wtab [vlit (lit)]; } // Watch literal 'lit' in clause with blocking literal 'blit'. // Inlined here, since it occurs in the tight inner loop of 'propagate'. // inline void watch_literal (int lit, int blit, Clause * c, int size) { Watches & ws = watches (lit); ws.push_back (Watch (blit, c, size)); LOG (c, "watch %d blit %d in", lit, blit); } // Managing clauses in 'clause.cpp'. Without explicit 'Clause' argument // these functions work on the global temporary 'clause'. // void watch_clause (Clause *); size_t bytes_clause (int size); Clause * new_clause (bool red, int glue = 0); void deallocate_clause (Clause *); void delete_clause (Clause *); bool tautological_clause (); void add_new_original_clause (); Clause * new_learned_clause (int glue); // Forward reasoning through propagation in 'propagate.cpp'. // void assign (int lit, Clause * reason = 0); bool propagate (); // Undo and restart in 'backtrack.cpp'. // void unassign (int lit); void backtrack (int target_level = 0); // Learning from conflicts in 'analyze.cc'. // void learn_empty_clause (); void learn_unit_clause (int lit); bool minimize_literal (int lit, int depth = 0); void minimize_clause (); void bump_variable (Var * v); void bump_variables (); void bump_resolved_clauses (); void resolve_clause (Clause *); void clear_seen (); void clear_levels (); bool analyze_literal (int); void analyze (); void iterate (); // for reporting learned unit clause // Restarting policy in 'restart.cc'. // bool restarting (); int reuse_trail (); void restart (); // Reducing means garbage collecting useless clauses in 'reduce.cpp'. // bool reducing (); void protect_reasons (); void unprotect_reasons (); int clause_contains_fixed_literal (Clause *); void flush_falsified_literals (Clause *); void mark_satisfied_clauses_as_garbage (); void mark_useless_redundant_clauses_as_garbage (); void move_clause (Clause *); void move_non_garbage_clauses (); void delete_garbage_clauses (); void flush_watches (); void setup_watches (); void garbage_collection (); void reduce (); // Part on picking the next decision in 'decide.cpp'. // bool satisfied () const { return trail.size () == (size_t) max_var; } int next_decision_variable (); void decide (); // Main search functions in 'internal.cpp'. // int search (); // CDCL loop void init_solving (); int solve (); // Built in profiling in 'profile.cpp'. // void start_profiling (Profile * p); void stop_profiling (Profile * p); void update_all_timers (double now); void print_profile (double now); // Checking solutions (see 'solution.cpp'). // int sol (int lit) const; void check_clause (); void check (int (Internal::*assignment) (int) const); Internal (); ~Internal (); // Get the value of a literal: -1 = false, 0 = unassigned, 1 = true. // int val (int lit) const { assert (lit), assert (abs (lit) <= max_var); return vals[lit]; } // Get and manipulate variable flags. // Flags & flags (int lit) { return ftab[vidx (lit)]; } const Flags & flags (int lit) const { return ftab[vidx (lit)]; } bool seen (int lit) const { return flags (lit).seen (); } // As 'val' but restricted to the root-level value of a literal. // int fixed (int lit) { int idx = vidx (lit), res = vals[idx]; if (res && vtab[idx].level) res = 0; if (lit < 0) res = -res; return res; } // Parsing functions (handed over to 'parse.cpp'). // const char * parse_dimacs (FILE *); const char * parse_dimacs (const char *); const char * parse_solution (const char *); // Enable and disable proof logging. void close_proof (); void new_proof (File *, bool owned = false); }; }; #endif <commit_msg>renamed tags to flags<commit_after>#ifndef _internal_hpp_INCLUDED #define _internal_hpp_INCLUDED #include <cassert> #include <climits> #include <cstdio> #include <vector> /*------------------------------------------------------------------------*/ using namespace std; /*------------------------------------------------------------------------*/ #include "avg.hpp" #include "arena.hpp" #include "ema.hpp" #include "format.hpp" #include "level.hpp" #include "logging.hpp" #include "options.hpp" #include "profile.hpp" #include "queue.hpp" #include "stats.hpp" #include "timer.hpp" #include "watch.hpp" #include "flags.hpp" /*------------------------------------------------------------------------*/ namespace CaDiCaL { class Proof; class File; class Internal { friend class Solver; friend class Arena; friend struct Logger; friend struct Message; friend class Parser; friend class Proof; friend struct Queue; friend struct Stats; friend struct trail_greater; friend struct trail_smaller; friend struct bump_earlier; /*----------------------------------------------------------------------*/ // The actual state of the solver is in this section. int max_var; // maximum variable index size_t vsize; // actually allocated variable data size Var * vtab; // variable table signed char * vals; // current partial assignment signed char * phases; // saved last assignment Watches * wtab; // table of watches for all literals Flags * ftab; // seen, poison, minimized flags table Queue queue; // variable move to front decision queue bool unsat; // empty clause found or learned int level; // decision level (levels.size () - 1) vector<Level> control; // 'level + 1 == levels.size ()' vector<int> trail; // assigned literals size_t propagated; // next position on trail to propagate vector<int> clause; // temporary clause in parsing & learning vector<Clause*> clauses; // ordered collection of all clauses bool iterating; // report learned unit (iteration) vector<int> bump; // seen & bumped literals in 'analyze' vector<int> levels; // decision levels of 1st UIP clause vector<int> minimized; // marked removable or poison in 'minmize' vector<Clause*> resolved; // large clauses in 'analyze' Clause * conflict; // set in 'propagation', reset in 'analyze' bool clashing_unit; // set in 'parse_dimacs' EMA fast_glue_avg; // fast exponential moving average EMA slow_glue_avg; // slow exponential moving average AVG jump_avg; // average back jump level long reduce_limit; // conflict limit for next 'reduce' long restart_limit; // conflict limit for next 'restart' long recently_resolved; // to keep recently resolved clauses int fixed_limit; // remember last number of units long reduce_inc; // reduce interval increment long reduce_inc_inc; // reduce interval increment increment Proof * proof; // trace clausal proof if non zero Options opts; // run-time options Stats stats; // statistics signed char * solution; // for debugging (like 'vals' and 'phases') vector<int> original; // original CNF for debugging vector<Timer> timers; // active timers for profiling functions Profiles profiles; // global profiled time for functions Arena arena; // memory arena for moving garbage collector Format error; // last (persistent) error message Internal * internal; // proxy to 'this' in macros (redundant) /*----------------------------------------------------------------------*/ // Internal delegates and helpers for corresponding functions in 'Solver'. // void resize (int new_max_var); void add_original_lit (int lit); // Enlarge tables. // void enlarge_vtab (int new_vsize); void enlarge_vals (int new_vsize); void enlarge (int new_max_var); // Functions for monitoring resources. // size_t vector_bytes (); void inc_bytes (size_t); void dec_bytes (size_t); double seconds (); size_t max_bytes (); size_t current_bytes (); int active_variables () const { return max_var - stats.fixed; } // Regularly reports what is going on in 'report.cpp'. // void report (char type, bool verbose = false); // Unsigned literals (abs) with checks. // int vidx (int lit) const { int idx; assert (lit), assert (lit != INT_MIN); idx = abs (lit); assert (idx <= max_var); return idx; } // Get the index of variable (with checking). // int var2idx (Var * v) const { assert (v), assert (vtab < v), assert (v <= vtab + max_var); return v - vtab; } // Unsigned version with LSB denoting sign. This is used in indexing arrays // by literals. The idea is to keep the elements in such an array for both // the positive and negated version of a literal close together. // unsigned vlit (int lit) { return (lit < 0) + 2u * (unsigned) vidx (lit); } // Helper function to access variables and watches to avoid indexing bugs. // Var & var (int lit) { return vtab [vidx (lit)]; } Watches & watches (int lit) { return wtab [vlit (lit)]; } // Watch literal 'lit' in clause with blocking literal 'blit'. // Inlined here, since it occurs in the tight inner loop of 'propagate'. // inline void watch_literal (int lit, int blit, Clause * c, int size) { Watches & ws = watches (lit); ws.push_back (Watch (blit, c, size)); LOG (c, "watch %d blit %d in", lit, blit); } // Managing clauses in 'clause.cpp'. Without explicit 'Clause' argument // these functions work on the global temporary 'clause'. // void watch_clause (Clause *); size_t bytes_clause (int size); Clause * new_clause (bool red, int glue = 0); void deallocate_clause (Clause *); void delete_clause (Clause *); bool tautological_clause (); void add_new_original_clause (); Clause * new_learned_clause (int glue); // Forward reasoning through propagation in 'propagate.cpp'. // void assign (int lit, Clause * reason = 0); bool propagate (); // Undo and restart in 'backtrack.cpp'. // void unassign (int lit); void backtrack (int target_level = 0); // Learning from conflicts in 'analyze.cc'. // void learn_empty_clause (); void learn_unit_clause (int lit); bool minimize_literal (int lit, int depth = 0); void minimize_clause (); void bump_variable (Var * v); void bump_variables (); void bump_resolved_clauses (); void resolve_clause (Clause *); void clear_seen (); void clear_levels (); bool analyze_literal (int); void analyze (); void iterate (); // for reporting learned unit clause // Restarting policy in 'restart.cc'. // bool restarting (); int reuse_trail (); void restart (); // Reducing means garbage collecting useless clauses in 'reduce.cpp'. // bool reducing (); void protect_reasons (); void unprotect_reasons (); int clause_contains_fixed_literal (Clause *); void flush_falsified_literals (Clause *); void mark_satisfied_clauses_as_garbage (); void mark_useless_redundant_clauses_as_garbage (); void move_clause (Clause *); void move_non_garbage_clauses (); void delete_garbage_clauses (); void flush_watches (); void setup_watches (); void garbage_collection (); void reduce (); // Part on picking the next decision in 'decide.cpp'. // bool satisfied () const { return trail.size () == (size_t) max_var; } int next_decision_variable (); void decide (); // Main search functions in 'internal.cpp'. // int search (); // CDCL loop void init_solving (); int solve (); // Built in profiling in 'profile.cpp'. // void start_profiling (Profile * p); void stop_profiling (Profile * p); void update_all_timers (double now); void print_profile (double now); // Checking solutions (see 'solution.cpp'). // int sol (int lit) const; void check_clause (); void check (int (Internal::*assignment) (int) const); Internal (); ~Internal (); // Get the value of a literal: -1 = false, 0 = unassigned, 1 = true. // int val (int lit) const { assert (lit), assert (abs (lit) <= max_var); return vals[lit]; } // Get and manipulate variable flags. // Flags & flags (int lit) { return ftab[vidx (lit)]; } const Flags & flags (int lit) const { return ftab[vidx (lit)]; } bool seen (int lit) const { return flags (lit).seen (); } // As 'val' but restricted to the root-level value of a literal. // int fixed (int lit) { int idx = vidx (lit), res = vals[idx]; if (res && vtab[idx].level) res = 0; if (lit < 0) res = -res; return res; } // Parsing functions (handed over to 'parse.cpp'). // const char * parse_dimacs (FILE *); const char * parse_dimacs (const char *); const char * parse_solution (const char *); // Enable and disable proof logging. void close_proof (); void new_proof (File *, bool owned = false); }; }; #endif <|endoftext|>
<commit_before><commit_msg>TEXT2BMP.C updated<commit_after><|endoftext|>
<commit_before>/* * Copyright (c) 2007-2009 Digital Bazaar, Inc. All rights reserved. */ #include "db/util/Date.h" #include "db/rt/System.h" #include "db/util/StringTools.h" #include <cstring> using namespace std; using namespace db::util; Date::Date() { // get the current time setSeconds(time(NULL)); } Date::Date(time_t seconds) { setSeconds(seconds); } Date::~Date() { } inline int Date::second() { return mBrokenDownTime.tm_sec; } inline int Date::minute() { return mBrokenDownTime.tm_min; } inline int Date::hour() { return mBrokenDownTime.tm_hour; } inline int Date::day() { return mBrokenDownTime.tm_mday; } inline int Date::month() { return mBrokenDownTime.tm_mon; } inline int Date::year() { return mBrokenDownTime.tm_year; } void Date::setDosTime(unsigned int dosTime) { // MS-DOS date & time bit-breakdown (4-bytes total): // [0-4][5-10][11-15][16-20][21-24][25-31] // sec min hour day month years // // sec is 0-59 / 2 (yes, divide by 2) // min is 0-59 // hour is 0-23 // day is 1-31 // month is 1-12 // years are from 1980 mBrokenDownTime.tm_sec = (dosTime & 0x1f) * 2; mBrokenDownTime.tm_min = (dosTime >> 5) & 0x3f; mBrokenDownTime.tm_hour = (dosTime >> 11) & 0x1f; mBrokenDownTime.tm_mday = (dosTime >> 16) & 0x1f; mBrokenDownTime.tm_mon = ((dosTime >> 21) & 0x0f) - 1; mBrokenDownTime.tm_year = ((dosTime >> 25) & 0x7f) + 80; } unsigned int Date::dosTime(bool local) { struct tm time; if(local) { // get local time localtime_r(&mSecondsSinceEpoch, &time); } else { // use broken down time time = mBrokenDownTime; } // MS-DOS date & time bit-breakdown (4-bytes total): // [0-4][5-10][11-15][16-20][21-24][25-31] // sec min hour day month years // // sec is 0-59 / 2 (yes, divide by 2) // min is 0-59 // hour is 0-23 // day is 1-31 // month is 1-12 // years are from 1980 return (time.tm_sec / 2) | time.tm_min << 5 | time.tm_hour << 11 | time.tm_mday << 16 | (time.tm_mon + 1) << 21 | (time.tm_year - 80) << 25; } void Date::addSeconds(time_t seconds) { setSeconds(mSecondsSinceEpoch + seconds); } void Date::setSeconds(time_t seconds) { mSecondsSinceEpoch = seconds; gmtime_r(&mSecondsSinceEpoch, &mBrokenDownTime); } time_t Date::getSeconds() { return mSecondsSinceEpoch; } string Date::getDateTime(TimeZone* tz) { // %F = YYYY-MM-DD // %T = HH:MM:SS string rval; #ifdef WIN32 // windows fails on %T specifier return format(rval, "%F %H:%M:%S", tz); #else return format(rval, "%F %T", tz); #endif } string Date::getUtcDateTime() { TimeZone tz = TimeZone::getTimeZone("UTC"); return getDateTime(&tz); } string& Date::format(string& str, const char* format, TimeZone* tz) { struct tm time; // apply time zone if(tz == NULL) { // get local time localtime_r(&mSecondsSinceEpoch, &time); } else if(tz->getMinutesWest() != 0) { // remove minutes west and get time time_t seconds = mSecondsSinceEpoch - tz->getMinutesWest() * 60UL; gmtime_r(&seconds, &time); } else { // use stored time time = mBrokenDownTime; } // print the time to a string unsigned int size = strlen(format) + 100; char out[size]; strftime(out, size, format, &time); str.assign(out); return str; } bool Date::parse(const char* str, const char* format, TimeZone* tz) { bool rval = false; if(strptime(str, format, &mBrokenDownTime) != NULL) { rval = true; if(tz == NULL) { // get local time mSecondsSinceEpoch = mktime(&mBrokenDownTime); } else { // get gmt time (applies no timezone) mSecondsSinceEpoch = timegm(&mBrokenDownTime); } // ensure broken down time is in GMT and totally filled out // (strptime may not populate all fields) gmtime_r(&mSecondsSinceEpoch, &mBrokenDownTime); } return rval; } string Date::toString(const char* format, TimeZone* tz) { string rval; return this->format(rval, format, tz); } <commit_msg>Used more compatible string format.<commit_after>/* * Copyright (c) 2007-2009 Digital Bazaar, Inc. All rights reserved. */ #include "db/util/Date.h" #include "db/rt/System.h" #include "db/util/StringTools.h" #include <cstring> using namespace std; using namespace db::util; Date::Date() { // get the current time setSeconds(time(NULL)); } Date::Date(time_t seconds) { setSeconds(seconds); } Date::~Date() { } inline int Date::second() { return mBrokenDownTime.tm_sec; } inline int Date::minute() { return mBrokenDownTime.tm_min; } inline int Date::hour() { return mBrokenDownTime.tm_hour; } inline int Date::day() { return mBrokenDownTime.tm_mday; } inline int Date::month() { return mBrokenDownTime.tm_mon; } inline int Date::year() { return mBrokenDownTime.tm_year; } void Date::setDosTime(unsigned int dosTime) { // MS-DOS date & time bit-breakdown (4-bytes total): // [0-4][5-10][11-15][16-20][21-24][25-31] // sec min hour day month years // // sec is 0-59 / 2 (yes, divide by 2) // min is 0-59 // hour is 0-23 // day is 1-31 // month is 1-12 // years are from 1980 mBrokenDownTime.tm_sec = (dosTime & 0x1f) * 2; mBrokenDownTime.tm_min = (dosTime >> 5) & 0x3f; mBrokenDownTime.tm_hour = (dosTime >> 11) & 0x1f; mBrokenDownTime.tm_mday = (dosTime >> 16) & 0x1f; mBrokenDownTime.tm_mon = ((dosTime >> 21) & 0x0f) - 1; mBrokenDownTime.tm_year = ((dosTime >> 25) & 0x7f) + 80; } unsigned int Date::dosTime(bool local) { struct tm time; if(local) { // get local time localtime_r(&mSecondsSinceEpoch, &time); } else { // use broken down time time = mBrokenDownTime; } // MS-DOS date & time bit-breakdown (4-bytes total): // [0-4][5-10][11-15][16-20][21-24][25-31] // sec min hour day month years // // sec is 0-59 / 2 (yes, divide by 2) // min is 0-59 // hour is 0-23 // day is 1-31 // month is 1-12 // years are from 1980 return (time.tm_sec / 2) | time.tm_min << 5 | time.tm_hour << 11 | time.tm_mday << 16 | (time.tm_mon + 1) << 21 | (time.tm_year - 80) << 25; } void Date::addSeconds(time_t seconds) { setSeconds(mSecondsSinceEpoch + seconds); } void Date::setSeconds(time_t seconds) { mSecondsSinceEpoch = seconds; gmtime_r(&mSecondsSinceEpoch, &mBrokenDownTime); } time_t Date::getSeconds() { return mSecondsSinceEpoch; } string Date::getDateTime(TimeZone* tz) { // %F = YYYY-MM-DD // %T = HH:MM:SS string rval; // Note: windows fails on %F and %T specifiers, so // we use the more compatible ones instead return format(rval, "%Y-%m-%d %H:%M:%S", tz); } string Date::getUtcDateTime() { TimeZone tz = TimeZone::getTimeZone("UTC"); return getDateTime(&tz); } string& Date::format(string& str, const char* format, TimeZone* tz) { struct tm time; // apply time zone if(tz == NULL) { // get local time localtime_r(&mSecondsSinceEpoch, &time); } else if(tz->getMinutesWest() != 0) { // remove minutes west and get time time_t seconds = mSecondsSinceEpoch - tz->getMinutesWest() * 60UL; gmtime_r(&seconds, &time); } else { // use stored time time = mBrokenDownTime; } // print the time to a string unsigned int size = strlen(format) + 100; char out[size]; strftime(out, size, format, &time); str.assign(out); return str; } bool Date::parse(const char* str, const char* format, TimeZone* tz) { bool rval = false; if(strptime(str, format, &mBrokenDownTime) != NULL) { rval = true; if(tz == NULL) { // get local time mSecondsSinceEpoch = mktime(&mBrokenDownTime); } else { // get gmt time (applies no timezone) mSecondsSinceEpoch = timegm(&mBrokenDownTime); } // ensure broken down time is in GMT and totally filled out // (strptime may not populate all fields) gmtime_r(&mSecondsSinceEpoch, &mBrokenDownTime); } return rval; } string Date::toString(const char* format, TimeZone* tz) { string rval; return this->format(rval, format, tz); } <|endoftext|>
<commit_before>/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Copyright 2015 Cloudius Systems * * Modified by Cloudius Systems */ #ifndef CQL3_OPERATION_HH #define CQL3_OPERATION_HH #include "core/shared_ptr.hh" #include "database.hh" #include <experimental/optional> namespace cql3 { #if 0 package org.apache.cassandra.cql3; import java.nio.ByteBuffer; import org.apache.cassandra.config.ColumnDefinition; import org.apache.cassandra.db.ColumnFamily; import org.apache.cassandra.db.composites.Composite; import org.apache.cassandra.db.marshal.*; import org.apache.cassandra.exceptions.InvalidRequestException; #endif /** * An UPDATE or DELETE operation. * * For UPDATE this includes: * - setting a constant * - counter operations * - collections operations * and for DELETE: * - deleting a column * - deleting an element of collection column * * Fine grained operation are obtained from their raw counterpart (Operation.Raw, which * correspond to a parsed, non-checked operation) by provided the receiver for the operation. */ class operation { public: // the column the operation applies to // We can hold a reference because all operations have life bound to their statements and // statements pin the schema. const column_definition& column; protected: // Term involved in the operation. In theory this should not be here since some operation // may require none of more than one term, but most need 1 so it simplify things a bit. const ::shared_ptr<term> _t; public: operation(column_definition& column_, ::shared_ptr<term> t) : column{column_} , _t{t} { } virtual bool uses_function(const sstring& ks_name, const sstring& function_name) const { return _t && _t->uses_function(ks_name, function_name); } /** * @return whether the operation requires a read of the previous value to be executed * (only lists setterByIdx, discard and discardByIdx requires that). */ virtual bool requires_read() { return false; } /** * Collects the column specification for the bind variables of this operation. * * @param bound_names the list of column specification where to collect the * bind variables of this term in. */ virtual void collect_marker_specification(::shared_ptr<variable_specifications> bound_names) { if (_t) { _t->collect_marker_specification(bound_names); } } /** * Execute the operation. */ virtual void execute(mutation& m, const clustering_prefix& row_key, const update_parameters& params) = 0; /** * A parsed raw UPDATE operation. * * This can be one of: * - Setting a value: c = v * - Setting an element of a collection: c[x] = v * - An addition/subtraction to a variable: c = c +/- v (where v can be a collection literal) * - An prepend operation: c = v + c */ class raw_update { public: virtual ~raw_update() {} /** * This method validates the operation (i.e. validate it is well typed) * based on the specification of the receiver of the operation. * * It returns an Operation which can be though as post-preparation well-typed * Operation. * * @param receiver the "column" this operation applies to. Note that * contrarly to the method of same name in Term.Raw, the receiver should always * be a true column. * @return the prepared update operation. */ virtual ::shared_ptr<operation> prepare(const sstring& keyspace, column_definition& receiver) = 0; /** * @return whether this operation can be applied alongside the {@code * other} update (in the same UPDATE statement for the same column). */ virtual bool is_compatible_with(::shared_ptr<raw_update> other) = 0; }; /** * A parsed raw DELETE operation. * * This can be one of: * - Deleting a column * - Deleting an element of a collection */ class raw_deletion { public: ~raw_deletion() {} /** * The name of the column affected by this delete operation. */ virtual ::shared_ptr<column_identifier::raw> affectedColumn() = 0; /** * This method validates the operation (i.e. validate it is well typed) * based on the specification of the column affected by the operation (i.e the * one returned by affectedColumn()). * * It returns an Operation which can be though as post-preparation well-typed * Operation. * * @param receiver the "column" this operation applies to. * @return the prepared delete operation. */ virtual ::shared_ptr<operation> prepare(const sstring& keyspace, column_definition& receiver) = 0; }; class set_value; #if 0 public static class SetElement implements RawUpdate { private final Term.Raw selector; private final Term.Raw value; public SetElement(Term.Raw selector, Term.Raw value) { this.selector = selector; this.value = value; } public Operation prepare(String keyspace, ColumnDefinition receiver) throws InvalidRequestException { if (!(receiver.type instanceof CollectionType)) throw new InvalidRequestException(String.format("Invalid operation (%s) for non collection column %s", toString(receiver), receiver.name)); else if (!(receiver.type.isMultiCell())) throw new InvalidRequestException(String.format("Invalid operation (%s) for frozen collection column %s", toString(receiver), receiver.name)); switch (((CollectionType)receiver.type).kind) { case LIST: Term idx = selector.prepare(keyspace, Lists.indexSpecOf(receiver)); Term lval = value.prepare(keyspace, Lists.valueSpecOf(receiver)); return new Lists.SetterByIndex(receiver, idx, lval); case SET: throw new InvalidRequestException(String.format("Invalid operation (%s) for set column %s", toString(receiver), receiver.name)); case MAP: Term key = selector.prepare(keyspace, Maps.keySpecOf(receiver)); Term mval = value.prepare(keyspace, Maps.valueSpecOf(receiver)); return new Maps.SetterByKey(receiver, key, mval); } throw new AssertionError(); } protected String toString(ColumnSpecification column) { return String.format("%s[%s] = %s", column.name, selector, value); } public boolean isCompatibleWith(RawUpdate other) { // TODO: we could check that the other operation is not setting the same element // too (but since the index/key set may be a bind variables we can't always do it at this point) return !(other instanceof SetValue); } } public static class Addition implements RawUpdate { private final Term.Raw value; public Addition(Term.Raw value) { this.value = value; } public Operation prepare(String keyspace, ColumnDefinition receiver) throws InvalidRequestException { Term v = value.prepare(keyspace, receiver); if (!(receiver.type instanceof CollectionType)) { if (!(receiver.type instanceof CounterColumnType)) throw new InvalidRequestException(String.format("Invalid operation (%s) for non counter column %s", toString(receiver), receiver.name)); return new Constants.Adder(receiver, v); } else if (!(receiver.type.isMultiCell())) throw new InvalidRequestException(String.format("Invalid operation (%s) for frozen collection column %s", toString(receiver), receiver.name)); switch (((CollectionType)receiver.type).kind) { case LIST: return new Lists.Appender(receiver, v); case SET: return new Sets.Adder(receiver, v); case MAP: return new Maps.Putter(receiver, v); } throw new AssertionError(); } protected String toString(ColumnSpecification column) { return String.format("%s = %s + %s", column.name, column.name, value); } public boolean isCompatibleWith(RawUpdate other) { return !(other instanceof SetValue); } } public static class Substraction implements RawUpdate { private final Term.Raw value; public Substraction(Term.Raw value) { this.value = value; } public Operation prepare(String keyspace, ColumnDefinition receiver) throws InvalidRequestException { if (!(receiver.type instanceof CollectionType)) { if (!(receiver.type instanceof CounterColumnType)) throw new InvalidRequestException(String.format("Invalid operation (%s) for non counter column %s", toString(receiver), receiver.name)); return new Constants.Substracter(receiver, value.prepare(keyspace, receiver)); } else if (!(receiver.type.isMultiCell())) throw new InvalidRequestException(String.format("Invalid operation (%s) for frozen collection column %s", toString(receiver), receiver.name)); switch (((CollectionType)receiver.type).kind) { case LIST: return new Lists.Discarder(receiver, value.prepare(keyspace, receiver)); case SET: return new Sets.Discarder(receiver, value.prepare(keyspace, receiver)); case MAP: // The value for a map subtraction is actually a set ColumnSpecification vr = new ColumnSpecification(receiver.ksName, receiver.cfName, receiver.name, SetType.getInstance(((MapType)receiver.type).getKeysType(), false)); return new Sets.Discarder(receiver, value.prepare(keyspace, vr)); } throw new AssertionError(); } protected String toString(ColumnSpecification column) { return String.format("%s = %s - %s", column.name, column.name, value); } public boolean isCompatibleWith(RawUpdate other) { return !(other instanceof SetValue); } } public static class Prepend implements RawUpdate { private final Term.Raw value; public Prepend(Term.Raw value) { this.value = value; } public Operation prepare(String keyspace, ColumnDefinition receiver) throws InvalidRequestException { Term v = value.prepare(keyspace, receiver); if (!(receiver.type instanceof ListType)) throw new InvalidRequestException(String.format("Invalid operation (%s) for non list column %s", toString(receiver), receiver.name)); else if (!(receiver.type.isMultiCell())) throw new InvalidRequestException(String.format("Invalid operation (%s) for frozen list column %s", toString(receiver), receiver.name)); return new Lists.Prepender(receiver, v); } protected String toString(ColumnSpecification column) { return String.format("%s = %s - %s", column.name, value, column.name); } public boolean isCompatibleWith(RawUpdate other) { return !(other instanceof SetValue); } } public static class ColumnDeletion implements RawDeletion { private final ColumnIdentifier.Raw id; public ColumnDeletion(ColumnIdentifier.Raw id) { this.id = id; } public ColumnIdentifier.Raw affectedColumn() { return id; } public Operation prepare(String keyspace, ColumnDefinition receiver) throws InvalidRequestException { // No validation, deleting a column is always "well typed" return new Constants.Deleter(receiver); } } public static class ElementDeletion implements RawDeletion { private final ColumnIdentifier.Raw id; private final Term.Raw element; public ElementDeletion(ColumnIdentifier.Raw id, Term.Raw element) { this.id = id; this.element = element; } public ColumnIdentifier.Raw affectedColumn() { return id; } public Operation prepare(String keyspace, ColumnDefinition receiver) throws InvalidRequestException { if (!(receiver.type.isCollection())) throw new InvalidRequestException(String.format("Invalid deletion operation for non collection column %s", receiver.name)); else if (!(receiver.type.isMultiCell())) throw new InvalidRequestException(String.format("Invalid deletion operation for frozen collection column %s", receiver.name)); switch (((CollectionType)receiver.type).kind) { case LIST: Term idx = element.prepare(keyspace, Lists.indexSpecOf(receiver)); return new Lists.DiscarderByIndex(receiver, idx); case SET: Term elt = element.prepare(keyspace, Sets.valueSpecOf(receiver)); return new Sets.Discarder(receiver, elt); case MAP: Term key = element.prepare(keyspace, Maps.keySpecOf(receiver)); return new Maps.DiscarderByKey(receiver, key); } throw new AssertionError(); } } #endif }; } #endif <commit_msg>cql3: add virtual destructor to class operation<commit_after>/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Copyright 2015 Cloudius Systems * * Modified by Cloudius Systems */ #ifndef CQL3_OPERATION_HH #define CQL3_OPERATION_HH #include "core/shared_ptr.hh" #include "database.hh" #include <experimental/optional> namespace cql3 { #if 0 package org.apache.cassandra.cql3; import java.nio.ByteBuffer; import org.apache.cassandra.config.ColumnDefinition; import org.apache.cassandra.db.ColumnFamily; import org.apache.cassandra.db.composites.Composite; import org.apache.cassandra.db.marshal.*; import org.apache.cassandra.exceptions.InvalidRequestException; #endif /** * An UPDATE or DELETE operation. * * For UPDATE this includes: * - setting a constant * - counter operations * - collections operations * and for DELETE: * - deleting a column * - deleting an element of collection column * * Fine grained operation are obtained from their raw counterpart (Operation.Raw, which * correspond to a parsed, non-checked operation) by provided the receiver for the operation. */ class operation { public: // the column the operation applies to // We can hold a reference because all operations have life bound to their statements and // statements pin the schema. const column_definition& column; protected: // Term involved in the operation. In theory this should not be here since some operation // may require none of more than one term, but most need 1 so it simplify things a bit. const ::shared_ptr<term> _t; public: operation(column_definition& column_, ::shared_ptr<term> t) : column{column_} , _t{t} { } virtual ~operation() {} virtual bool uses_function(const sstring& ks_name, const sstring& function_name) const { return _t && _t->uses_function(ks_name, function_name); } /** * @return whether the operation requires a read of the previous value to be executed * (only lists setterByIdx, discard and discardByIdx requires that). */ virtual bool requires_read() { return false; } /** * Collects the column specification for the bind variables of this operation. * * @param bound_names the list of column specification where to collect the * bind variables of this term in. */ virtual void collect_marker_specification(::shared_ptr<variable_specifications> bound_names) { if (_t) { _t->collect_marker_specification(bound_names); } } /** * Execute the operation. */ virtual void execute(mutation& m, const clustering_prefix& row_key, const update_parameters& params) = 0; /** * A parsed raw UPDATE operation. * * This can be one of: * - Setting a value: c = v * - Setting an element of a collection: c[x] = v * - An addition/subtraction to a variable: c = c +/- v (where v can be a collection literal) * - An prepend operation: c = v + c */ class raw_update { public: virtual ~raw_update() {} /** * This method validates the operation (i.e. validate it is well typed) * based on the specification of the receiver of the operation. * * It returns an Operation which can be though as post-preparation well-typed * Operation. * * @param receiver the "column" this operation applies to. Note that * contrarly to the method of same name in Term.Raw, the receiver should always * be a true column. * @return the prepared update operation. */ virtual ::shared_ptr<operation> prepare(const sstring& keyspace, column_definition& receiver) = 0; /** * @return whether this operation can be applied alongside the {@code * other} update (in the same UPDATE statement for the same column). */ virtual bool is_compatible_with(::shared_ptr<raw_update> other) = 0; }; /** * A parsed raw DELETE operation. * * This can be one of: * - Deleting a column * - Deleting an element of a collection */ class raw_deletion { public: ~raw_deletion() {} /** * The name of the column affected by this delete operation. */ virtual ::shared_ptr<column_identifier::raw> affectedColumn() = 0; /** * This method validates the operation (i.e. validate it is well typed) * based on the specification of the column affected by the operation (i.e the * one returned by affectedColumn()). * * It returns an Operation which can be though as post-preparation well-typed * Operation. * * @param receiver the "column" this operation applies to. * @return the prepared delete operation. */ virtual ::shared_ptr<operation> prepare(const sstring& keyspace, column_definition& receiver) = 0; }; class set_value; #if 0 public static class SetElement implements RawUpdate { private final Term.Raw selector; private final Term.Raw value; public SetElement(Term.Raw selector, Term.Raw value) { this.selector = selector; this.value = value; } public Operation prepare(String keyspace, ColumnDefinition receiver) throws InvalidRequestException { if (!(receiver.type instanceof CollectionType)) throw new InvalidRequestException(String.format("Invalid operation (%s) for non collection column %s", toString(receiver), receiver.name)); else if (!(receiver.type.isMultiCell())) throw new InvalidRequestException(String.format("Invalid operation (%s) for frozen collection column %s", toString(receiver), receiver.name)); switch (((CollectionType)receiver.type).kind) { case LIST: Term idx = selector.prepare(keyspace, Lists.indexSpecOf(receiver)); Term lval = value.prepare(keyspace, Lists.valueSpecOf(receiver)); return new Lists.SetterByIndex(receiver, idx, lval); case SET: throw new InvalidRequestException(String.format("Invalid operation (%s) for set column %s", toString(receiver), receiver.name)); case MAP: Term key = selector.prepare(keyspace, Maps.keySpecOf(receiver)); Term mval = value.prepare(keyspace, Maps.valueSpecOf(receiver)); return new Maps.SetterByKey(receiver, key, mval); } throw new AssertionError(); } protected String toString(ColumnSpecification column) { return String.format("%s[%s] = %s", column.name, selector, value); } public boolean isCompatibleWith(RawUpdate other) { // TODO: we could check that the other operation is not setting the same element // too (but since the index/key set may be a bind variables we can't always do it at this point) return !(other instanceof SetValue); } } public static class Addition implements RawUpdate { private final Term.Raw value; public Addition(Term.Raw value) { this.value = value; } public Operation prepare(String keyspace, ColumnDefinition receiver) throws InvalidRequestException { Term v = value.prepare(keyspace, receiver); if (!(receiver.type instanceof CollectionType)) { if (!(receiver.type instanceof CounterColumnType)) throw new InvalidRequestException(String.format("Invalid operation (%s) for non counter column %s", toString(receiver), receiver.name)); return new Constants.Adder(receiver, v); } else if (!(receiver.type.isMultiCell())) throw new InvalidRequestException(String.format("Invalid operation (%s) for frozen collection column %s", toString(receiver), receiver.name)); switch (((CollectionType)receiver.type).kind) { case LIST: return new Lists.Appender(receiver, v); case SET: return new Sets.Adder(receiver, v); case MAP: return new Maps.Putter(receiver, v); } throw new AssertionError(); } protected String toString(ColumnSpecification column) { return String.format("%s = %s + %s", column.name, column.name, value); } public boolean isCompatibleWith(RawUpdate other) { return !(other instanceof SetValue); } } public static class Substraction implements RawUpdate { private final Term.Raw value; public Substraction(Term.Raw value) { this.value = value; } public Operation prepare(String keyspace, ColumnDefinition receiver) throws InvalidRequestException { if (!(receiver.type instanceof CollectionType)) { if (!(receiver.type instanceof CounterColumnType)) throw new InvalidRequestException(String.format("Invalid operation (%s) for non counter column %s", toString(receiver), receiver.name)); return new Constants.Substracter(receiver, value.prepare(keyspace, receiver)); } else if (!(receiver.type.isMultiCell())) throw new InvalidRequestException(String.format("Invalid operation (%s) for frozen collection column %s", toString(receiver), receiver.name)); switch (((CollectionType)receiver.type).kind) { case LIST: return new Lists.Discarder(receiver, value.prepare(keyspace, receiver)); case SET: return new Sets.Discarder(receiver, value.prepare(keyspace, receiver)); case MAP: // The value for a map subtraction is actually a set ColumnSpecification vr = new ColumnSpecification(receiver.ksName, receiver.cfName, receiver.name, SetType.getInstance(((MapType)receiver.type).getKeysType(), false)); return new Sets.Discarder(receiver, value.prepare(keyspace, vr)); } throw new AssertionError(); } protected String toString(ColumnSpecification column) { return String.format("%s = %s - %s", column.name, column.name, value); } public boolean isCompatibleWith(RawUpdate other) { return !(other instanceof SetValue); } } public static class Prepend implements RawUpdate { private final Term.Raw value; public Prepend(Term.Raw value) { this.value = value; } public Operation prepare(String keyspace, ColumnDefinition receiver) throws InvalidRequestException { Term v = value.prepare(keyspace, receiver); if (!(receiver.type instanceof ListType)) throw new InvalidRequestException(String.format("Invalid operation (%s) for non list column %s", toString(receiver), receiver.name)); else if (!(receiver.type.isMultiCell())) throw new InvalidRequestException(String.format("Invalid operation (%s) for frozen list column %s", toString(receiver), receiver.name)); return new Lists.Prepender(receiver, v); } protected String toString(ColumnSpecification column) { return String.format("%s = %s - %s", column.name, value, column.name); } public boolean isCompatibleWith(RawUpdate other) { return !(other instanceof SetValue); } } public static class ColumnDeletion implements RawDeletion { private final ColumnIdentifier.Raw id; public ColumnDeletion(ColumnIdentifier.Raw id) { this.id = id; } public ColumnIdentifier.Raw affectedColumn() { return id; } public Operation prepare(String keyspace, ColumnDefinition receiver) throws InvalidRequestException { // No validation, deleting a column is always "well typed" return new Constants.Deleter(receiver); } } public static class ElementDeletion implements RawDeletion { private final ColumnIdentifier.Raw id; private final Term.Raw element; public ElementDeletion(ColumnIdentifier.Raw id, Term.Raw element) { this.id = id; this.element = element; } public ColumnIdentifier.Raw affectedColumn() { return id; } public Operation prepare(String keyspace, ColumnDefinition receiver) throws InvalidRequestException { if (!(receiver.type.isCollection())) throw new InvalidRequestException(String.format("Invalid deletion operation for non collection column %s", receiver.name)); else if (!(receiver.type.isMultiCell())) throw new InvalidRequestException(String.format("Invalid deletion operation for frozen collection column %s", receiver.name)); switch (((CollectionType)receiver.type).kind) { case LIST: Term idx = element.prepare(keyspace, Lists.indexSpecOf(receiver)); return new Lists.DiscarderByIndex(receiver, idx); case SET: Term elt = element.prepare(keyspace, Sets.valueSpecOf(receiver)); return new Sets.Discarder(receiver, elt); case MAP: Term key = element.prepare(keyspace, Maps.keySpecOf(receiver)); return new Maps.DiscarderByKey(receiver, key); } throw new AssertionError(); } } #endif }; } #endif <|endoftext|>
<commit_before>/* * Copyright 2015-2019 Arm Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef SPIRV_CROSS_ERROR_HANDLING #define SPIRV_CROSS_ERROR_HANDLING #include <stdexcept> #include <stdio.h> #include <stdlib.h> #include <string> #ifdef SPIRV_CROSS_NAMESPACE_OVERRIDE #define SPIRV_CROSS_NAMESPACE SPIRV_CROSS_NAMESPACE_OVERRIDE #else #define SPIRV_CROSS_NAMESPACE spirv_cross #endif namespace SPIRV_CROSS_NAMESPACE { #ifdef SPIRV_CROSS_EXCEPTIONS_TO_ASSERTIONS #if !defined(_MSC_VER) || defined(__clang__) [[noreturn]] #endif inline void report_and_abort(const std::string &msg) { #ifdef NDEBUG (void)msg; #else fprintf(stderr, "There was a compiler error: %s\n", msg.c_str()); #endif fflush(stderr); abort(); } #define SPIRV_CROSS_THROW(x) report_and_abort(x) #else class CompilerError : public std::runtime_error { public: explicit CompilerError(const std::string &str) : std::runtime_error(str) { } }; #define SPIRV_CROSS_THROW(x) throw CompilerError(x) #endif // MSVC 2013 does not have noexcept. We need this for Variant to get move constructor to work correctly // instead of copy constructor. // MSVC 2013 ignores that move constructors cannot throw in std::vector, so just don't define it. #if defined(_MSC_VER) && _MSC_VER < 1900 #define SPIRV_CROSS_NOEXCEPT #else #define SPIRV_CROSS_NOEXCEPT noexcept #endif #if __cplusplus >= 201402l #define SPIRV_CROSS_DEPRECATED(reason) [[deprecated(reason)]] #elif defined(__GNUC__) #define SPIRV_CROSS_DEPRECATED(reason) __attribute__((deprecated)) #elif defined(_MSC_VER) #define SPIRV_CROSS_DEPRECATED(reason) __declspec(deprecated(reason)) #else #define SPIRV_CROSS_DEPRECATED(reason) #endif } // namespace SPIRV_CROSS_NAMESPACE #endif <commit_msg>Avoid including stdexcept in no-exception environment<commit_after>/* * Copyright 2015-2019 Arm Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef SPIRV_CROSS_ERROR_HANDLING #define SPIRV_CROSS_ERROR_HANDLING #include <stdio.h> #include <stdlib.h> #include <string> #ifndef SPIRV_CROSS_EXCEPTIONS_TO_ASSERTIONS #include <stdexcept> #endif #ifdef SPIRV_CROSS_NAMESPACE_OVERRIDE #define SPIRV_CROSS_NAMESPACE SPIRV_CROSS_NAMESPACE_OVERRIDE #else #define SPIRV_CROSS_NAMESPACE spirv_cross #endif namespace SPIRV_CROSS_NAMESPACE { #ifdef SPIRV_CROSS_EXCEPTIONS_TO_ASSERTIONS #if !defined(_MSC_VER) || defined(__clang__) [[noreturn]] #endif inline void report_and_abort(const std::string &msg) { #ifdef NDEBUG (void)msg; #else fprintf(stderr, "There was a compiler error: %s\n", msg.c_str()); #endif fflush(stderr); abort(); } #define SPIRV_CROSS_THROW(x) report_and_abort(x) #else class CompilerError : public std::runtime_error { public: explicit CompilerError(const std::string &str) : std::runtime_error(str) { } }; #define SPIRV_CROSS_THROW(x) throw CompilerError(x) #endif // MSVC 2013 does not have noexcept. We need this for Variant to get move constructor to work correctly // instead of copy constructor. // MSVC 2013 ignores that move constructors cannot throw in std::vector, so just don't define it. #if defined(_MSC_VER) && _MSC_VER < 1900 #define SPIRV_CROSS_NOEXCEPT #else #define SPIRV_CROSS_NOEXCEPT noexcept #endif #if __cplusplus >= 201402l #define SPIRV_CROSS_DEPRECATED(reason) [[deprecated(reason)]] #elif defined(__GNUC__) #define SPIRV_CROSS_DEPRECATED(reason) __attribute__((deprecated)) #elif defined(_MSC_VER) #define SPIRV_CROSS_DEPRECATED(reason) __declspec(deprecated(reason)) #else #define SPIRV_CROSS_DEPRECATED(reason) #endif } // namespace SPIRV_CROSS_NAMESPACE #endif <|endoftext|>
<commit_before>//===-- PlatformAndroidRemoteGDBServer.cpp ----------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // Other libraries and framework includes #include "lldb/Core/Error.h" #include "lldb/Core/Log.h" #include "lldb/Host/ConnectionFileDescriptor.h" #include "llvm/ADT/StringRef.h" // Project includes #include "AdbClient.h" #include "PlatformAndroidRemoteGDBServer.h" #include "Utility/UriParser.h" using namespace lldb; using namespace lldb_private; static const lldb::pid_t g_remote_platform_pid = 0; // Alias for the process id of lldb-platform static Error ForwardPortWithAdb (uint16_t port, std::string& device_id) { Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PLATFORM)); // Fetch the device list from ADB and if only 1 device found then use that device // TODO: Handle the case when more device is available AdbClient adb; AdbClient::DeviceIDList connect_devices; auto error = adb.GetDevices (connect_devices); if (error.Fail ()) return error; if (connect_devices.size () != 1) return Error ("Expected a single connected device, got instead %" PRIu64, connect_devices.size ()); device_id = connect_devices.front (); if (log) log->Printf("Connected to Android device \"%s\"", device_id.c_str ()); adb.SetDeviceID (device_id); return adb.SetPortForwarding (port); } static Error DeleteForwardPortWithAdb (uint16_t port, const std::string& device_id) { AdbClient adb (device_id); return adb.DeletePortForwarding (port); } PlatformAndroidRemoteGDBServer::PlatformAndroidRemoteGDBServer () { } PlatformAndroidRemoteGDBServer::~PlatformAndroidRemoteGDBServer () { for (const auto& it : m_port_forwards) { DeleteForwardPortWithAdb (it.second.first, it.second.second); } } uint16_t PlatformAndroidRemoteGDBServer::LaunchGDBserverAndGetPort (lldb::pid_t &pid) { uint16_t port = m_gdb_client.LaunchGDBserverAndGetPort (pid, "127.0.0.1"); if (port == 0) return port; std::string device_id; Error error = ForwardPortWithAdb (port, device_id); if (error.Fail ()) return 0; m_port_forwards[pid] = std::make_pair (port, device_id); return port; } bool PlatformAndroidRemoteGDBServer::KillSpawnedProcess (lldb::pid_t pid) { auto it = m_port_forwards.find (pid); if (it != m_port_forwards.end ()) { DeleteForwardPortWithAdb (it->second.first, it->second.second); m_port_forwards.erase (it); } return m_gdb_client.KillSpawnedProcess (pid); } Error PlatformAndroidRemoteGDBServer::ConnectRemote (Args& args) { if (args.GetArgumentCount () != 1) return Error ("\"platform connect\" takes a single argument: <connect-url>"); int port; std::string scheme, host, path; const char *url = args.GetArgumentAtIndex (0); if (!UriParser::Parse (url, scheme, host, port, path)) return Error ("invalid uri"); std::string device_id; Error error = ForwardPortWithAdb (port, device_id); if (error.Fail ()) return error; m_port_forwards[g_remote_platform_pid] = std::make_pair (port, device_id); return PlatformRemoteGDBServer::ConnectRemote (args); } Error PlatformAndroidRemoteGDBServer::DisconnectRemote () { auto it = m_port_forwards.find (g_remote_platform_pid); if (it != m_port_forwards.end ()) { DeleteForwardPortWithAdb (it->second.first, it->second.second); m_port_forwards.erase (it); } return PlatformRemoteGDBServer::DisconnectRemote (); } <commit_msg>Fix format compilation warning in PlatformAndroidRemoteGDBServer.cpp.<commit_after>//===-- PlatformAndroidRemoteGDBServer.cpp ----------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // Other libraries and framework includes #include "lldb/Core/Error.h" #include "lldb/Core/Log.h" #include "lldb/Host/ConnectionFileDescriptor.h" #include "llvm/ADT/StringRef.h" // Project includes #include "AdbClient.h" #include "PlatformAndroidRemoteGDBServer.h" #include "Utility/UriParser.h" using namespace lldb; using namespace lldb_private; static const lldb::pid_t g_remote_platform_pid = 0; // Alias for the process id of lldb-platform static Error ForwardPortWithAdb (uint16_t port, std::string& device_id) { Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PLATFORM)); // Fetch the device list from ADB and if only 1 device found then use that device // TODO: Handle the case when more device is available AdbClient adb; AdbClient::DeviceIDList connect_devices; auto error = adb.GetDevices (connect_devices); if (error.Fail ()) return error; if (connect_devices.size () != 1) return Error ("Expected a single connected device, got instead %zu", connect_devices.size ()); device_id = connect_devices.front (); if (log) log->Printf("Connected to Android device \"%s\"", device_id.c_str ()); adb.SetDeviceID (device_id); return adb.SetPortForwarding (port); } static Error DeleteForwardPortWithAdb (uint16_t port, const std::string& device_id) { AdbClient adb (device_id); return adb.DeletePortForwarding (port); } PlatformAndroidRemoteGDBServer::PlatformAndroidRemoteGDBServer () { } PlatformAndroidRemoteGDBServer::~PlatformAndroidRemoteGDBServer () { for (const auto& it : m_port_forwards) { DeleteForwardPortWithAdb (it.second.first, it.second.second); } } uint16_t PlatformAndroidRemoteGDBServer::LaunchGDBserverAndGetPort (lldb::pid_t &pid) { uint16_t port = m_gdb_client.LaunchGDBserverAndGetPort (pid, "127.0.0.1"); if (port == 0) return port; std::string device_id; Error error = ForwardPortWithAdb (port, device_id); if (error.Fail ()) return 0; m_port_forwards[pid] = std::make_pair (port, device_id); return port; } bool PlatformAndroidRemoteGDBServer::KillSpawnedProcess (lldb::pid_t pid) { auto it = m_port_forwards.find (pid); if (it != m_port_forwards.end ()) { DeleteForwardPortWithAdb (it->second.first, it->second.second); m_port_forwards.erase (it); } return m_gdb_client.KillSpawnedProcess (pid); } Error PlatformAndroidRemoteGDBServer::ConnectRemote (Args& args) { if (args.GetArgumentCount () != 1) return Error ("\"platform connect\" takes a single argument: <connect-url>"); int port; std::string scheme, host, path; const char *url = args.GetArgumentAtIndex (0); if (!UriParser::Parse (url, scheme, host, port, path)) return Error ("invalid uri"); std::string device_id; Error error = ForwardPortWithAdb (port, device_id); if (error.Fail ()) return error; m_port_forwards[g_remote_platform_pid] = std::make_pair (port, device_id); return PlatformRemoteGDBServer::ConnectRemote (args); } Error PlatformAndroidRemoteGDBServer::DisconnectRemote () { auto it = m_port_forwards.find (g_remote_platform_pid); if (it != m_port_forwards.end ()) { DeleteForwardPortWithAdb (it->second.first, it->second.second); m_port_forwards.erase (it); } return PlatformRemoteGDBServer::DisconnectRemote (); } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: framelistanalyzer.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: kz $ $Date: 2004-02-25 17:44:02 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #include "classes/framelistanalyzer.hxx" //_______________________________________________ // my own includes #ifndef __FRAMEWORK_THREADHELP_WRITEGUARD_HXX_ #include <threadhelp/writeguard.hxx> #endif #ifndef __FRAMEWORK_THREADHELP_READGUARD_HXX_ #include <threadhelp/readguard.hxx> #endif #ifndef __FRAMEWORK_TARGETS_H_ #include <targets.h> #endif #ifndef __FRAMEWORK_PROPERTIES_H_ #include <properties.h> #endif #ifndef __FRAMEWORK_SERVICES_H_ #include <services.h> #endif //_______________________________________________ // interface includes #ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_ #include <com/sun/star/beans/XPropertySet.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_ #include <com/sun/star/lang/XMultiServiceFactory.hpp> #endif #ifndef _DRAFTS_COM_SUN_STAR_FRAME_XMODULEMANAGER_HPP_ #include <drafts/com/sun/star/frame/XModuleManager.hpp> #endif //_______________________________________________ // includes of other projects #ifndef _UNOTOOLS_PROCESSFACTORY_HXX_ #include <unotools/processfactory.hxx> #endif #ifndef _SV_SVAPP_HXX #include <vcl/svapp.hxx> #endif //_______________________________________________ // namespace namespace framework{ //_______________________________________________ // non exported const //_______________________________________________ // non exported definitions //_______________________________________________ // declarations //_______________________________________________ /** */ FrameListAnalyzer::FrameListAnalyzer( const css::uno::Reference< css::frame::XFramesSupplier >& xSupplier , const css::uno::Reference< css::frame::XFrame >& xReferenceFrame , sal_uInt32 eDetectMode ) : m_xSupplier (xSupplier ) , m_xReferenceFrame(xReferenceFrame) , m_eDetectMode (eDetectMode ) { impl_analyze(); } //_______________________________________________ /** */ FrameListAnalyzer::~FrameListAnalyzer() { } //_______________________________________________ /** returns an analyzed list of all currently opened (top!) frames inside the desktop tree. We try to get a snapshot of all opened frames, which are part of the desktop frame container. Of course we can't access frames, which stands outside of this tree. But it's neccessary to collect top frames here only. Otherwhise we interpret closing of last frame wrong. Further we analyze this list and split into different parts. E.g. for "CloseDoc" we must know, which frames of the given list referr to the same model. These frames must be closed then. But all other frames must be untouched. In case the request was "CloseWin" these splitted lists can be used too, to decide if the last window or document was closed. Then we have to initialize the backing window ... Last but not least we must know something about our special help frame. It must be handled seperatly. And last but not least - the backing component frame must be detected too. */ void FrameListAnalyzer::impl_analyze() { // reset all members to get a consistent state m_bReferenceIsHidden = sal_False; m_bReferenceIsHelp = sal_False; m_bReferenceIsBacking = sal_False; m_xHelp = css::uno::Reference< css::frame::XFrame >(); m_xBackingComponent = css::uno::Reference< css::frame::XFrame >(); // try to get the task container by using the given supplier css::uno::Reference< css::container::XIndexAccess > xFrameContainer(m_xSupplier->getFrames(), css::uno::UNO_QUERY); // All return list get an initial size to include all possible frames. // They will be packed at the end of this method ... using the actual step positions then. sal_Int32 nVisibleStep = 0; sal_Int32 nHiddenStep = 0; sal_Int32 nModelStep = 0; sal_Int32 nCount = xFrameContainer->getCount(); m_lOtherVisibleFrames.realloc(nCount); m_lOtherHiddenFrames.realloc(nCount); m_lModelFrames.realloc(nCount); // ask for the model of the given reference frame. // It must be compared with the model of every frame of the container // to sort it into the list of frames with the same model. // Supress this step, if right detect mode isn't set. css::uno::Reference< css::frame::XModel > xReferenceModel; if ((m_eDetectMode & E_MODEL) == E_MODEL ) { css::uno::Reference< css::frame::XController > xReferenceController = m_xReferenceFrame->getController(); if (xReferenceController.is()) xReferenceModel = xReferenceController->getModel(); } // check, if the reference frame is in hidden mode. // But look, if this analyze step is realy needed. css::uno::Reference< css::beans::XPropertySet > xSet(m_xReferenceFrame, css::uno::UNO_QUERY); if ( ((m_eDetectMode & E_HIDDEN) == E_HIDDEN) && (xSet.is() ) ) { css::uno::Any aValue = xSet->getPropertyValue(FRAME_PROPNAME_ISHIDDEN); aValue >>= m_bReferenceIsHidden; } // check, if the reference frame includes the backing component. // But look, if this analyze step is realy needed. if ((m_eDetectMode & E_BACKINGCOMPONENT) == E_BACKINGCOMPONENT) { try { css::uno::Reference< css::lang::XMultiServiceFactory > xSMGR = ::utl::getProcessServiceFactory(); css::uno::Reference< dcss::frame::XModuleManager > xModuleMgr(xSMGR->createInstance(SERVICENAME_MODULEMANAGER), css::uno::UNO_QUERY); ::rtl::OUString sModule = xModuleMgr->identify(m_xReferenceFrame); m_bReferenceIsBacking = (sModule.equals(SERVICENAME_STARTMODULE)); } catch(const css::uno::Exception&) {} } // check, if the reference frame includes the help module. // But look, if this analyze step is realy needed. if ( ((m_eDetectMode & E_HELP) == E_HELP ) && (m_xReferenceFrame.is() ) && (m_xReferenceFrame->getName() == SPECIALTARGET_HELPTASK) ) { m_bReferenceIsHelp = sal_True; } try { // Step over all frames of the desktop frame container and analyze it. for (sal_Int32 i=0; i<nCount; ++i) { // Ignore invalid items ... and of course the reference frame. // It will be a member of the given frame list too - but it was already // analyzed before! css::uno::Reference< css::frame::XFrame > xFrame; if ( !(xFrameContainer->getByIndex(i) >>= xFrame) || !(xFrame.is() ) || (xFrame==m_xReferenceFrame ) ) continue; #ifdef ENABLE_WARNINGS if ( ((m_eDetectMode & E_ZOMBIE) == E_ZOMBIE) && ( (!xFrame->getContainerWindow().is()) || (!xFrame->getComponentWindow().is()) ) ) { LOG_WARNING("FrameListAnalyzer::impl_analyze()", "ZOMBIE!") } #endif // ------------------------------------------------- // a) Is it the special help task? // Return it seperated from any return list. if ( ((m_eDetectMode & E_HELP) == E_HELP ) && (xFrame->getName()==SPECIALTARGET_HELPTASK) ) { m_xHelp = xFrame; continue; } // ------------------------------------------------- // b) Or is includes this task the special backing component? // Return it seperated from any return list. // But check if the reference task itself is the backing frame. // Our user mst know it to decide right. if ((m_eDetectMode & E_BACKINGCOMPONENT) == E_BACKINGCOMPONENT) { try { css::uno::Reference< css::lang::XMultiServiceFactory > xSMGR = ::utl::getProcessServiceFactory(); css::uno::Reference< dcss::frame::XModuleManager > xModuleMgr(xSMGR->createInstance(SERVICENAME_MODULEMANAGER), css::uno::UNO_QUERY); ::rtl::OUString sModule = xModuleMgr->identify(xFrame); if (sModule.equals(SERVICENAME_STARTMODULE)) { m_xBackingComponent = xFrame; continue; } } catch(const css::uno::Exception&) {} } // ------------------------------------------------- // c) Or is it the a task, which uses the specified model? // Add it to the list of "model frames". if ((m_eDetectMode & E_MODEL) == E_MODEL) { css::uno::Reference< css::frame::XController > xController = xFrame->getController(); css::uno::Reference< css::frame::XModel > xModel ; if (xController.is()) xModel = xController->getModel(); if (xModel==xReferenceModel) { m_lModelFrames[nModelStep] = xFrame; ++nModelStep; continue; } } // ------------------------------------------------- // d) Or is it the a task, which use another or no model at all? // Add it to the list of "other frames". But look for it's // visible state ... if it's allowed to do so. // ------------------------------------------------- sal_Bool bHidden = sal_False; if ((m_eDetectMode & E_HIDDEN) == E_HIDDEN ) { xSet = css::uno::Reference< css::beans::XPropertySet >(xFrame, css::uno::UNO_QUERY); if (xSet.is()) { css::uno::Any aValue = xSet->getPropertyValue(FRAME_PROPNAME_ISHIDDEN); aValue >>= bHidden; } } if (bHidden) { m_lOtherHiddenFrames[nHiddenStep] = xFrame; ++nHiddenStep; } else { m_lOtherVisibleFrames[nVisibleStep] = xFrame; ++nVisibleStep; } } } catch(css::lang::IndexOutOfBoundsException) { // stop copying if index seams to be wrong. // This interface can't realy guarantee its count for multithreaded // environments. So it can occure! } // Pack both lists by using the actual step positions. // All empty or ignorable items should exist at the end of these lists // behind the position pointers. So they will be removed by a reallocation. m_lOtherVisibleFrames.realloc(nVisibleStep); m_lOtherHiddenFrames.realloc(nHiddenStep); m_lModelFrames.realloc(nModelStep); } } // namespace framework <commit_msg>INTEGRATION: CWS removedrafts (1.4.204); FILE MERGED 2005/02/17 12:47:38 cd 1.4.204.1: #i42557# move UNOIDL types from drafts to com<commit_after>/************************************************************************* * * $RCSfile: framelistanalyzer.cxx,v $ * * $Revision: 1.5 $ * * last change: $Author: kz $ $Date: 2005-03-01 19:35:00 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #include "classes/framelistanalyzer.hxx" //_______________________________________________ // my own includes #ifndef __FRAMEWORK_THREADHELP_WRITEGUARD_HXX_ #include <threadhelp/writeguard.hxx> #endif #ifndef __FRAMEWORK_THREADHELP_READGUARD_HXX_ #include <threadhelp/readguard.hxx> #endif #ifndef __FRAMEWORK_TARGETS_H_ #include <targets.h> #endif #ifndef __FRAMEWORK_PROPERTIES_H_ #include <properties.h> #endif #ifndef __FRAMEWORK_SERVICES_H_ #include <services.h> #endif //_______________________________________________ // interface includes #ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_ #include <com/sun/star/beans/XPropertySet.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_ #include <com/sun/star/lang/XMultiServiceFactory.hpp> #endif #ifndef _COM_SUN_STAR_FRAME_XMODULEMANAGER_HPP_ #include <com/sun/star/frame/XModuleManager.hpp> #endif //_______________________________________________ // includes of other projects #ifndef _UNOTOOLS_PROCESSFACTORY_HXX_ #include <unotools/processfactory.hxx> #endif #ifndef _SV_SVAPP_HXX #include <vcl/svapp.hxx> #endif //_______________________________________________ // namespace namespace framework{ //_______________________________________________ // non exported const //_______________________________________________ // non exported definitions //_______________________________________________ // declarations //_______________________________________________ /** */ FrameListAnalyzer::FrameListAnalyzer( const css::uno::Reference< css::frame::XFramesSupplier >& xSupplier , const css::uno::Reference< css::frame::XFrame >& xReferenceFrame , sal_uInt32 eDetectMode ) : m_xSupplier (xSupplier ) , m_xReferenceFrame(xReferenceFrame) , m_eDetectMode (eDetectMode ) { impl_analyze(); } //_______________________________________________ /** */ FrameListAnalyzer::~FrameListAnalyzer() { } //_______________________________________________ /** returns an analyzed list of all currently opened (top!) frames inside the desktop tree. We try to get a snapshot of all opened frames, which are part of the desktop frame container. Of course we can't access frames, which stands outside of this tree. But it's neccessary to collect top frames here only. Otherwhise we interpret closing of last frame wrong. Further we analyze this list and split into different parts. E.g. for "CloseDoc" we must know, which frames of the given list referr to the same model. These frames must be closed then. But all other frames must be untouched. In case the request was "CloseWin" these splitted lists can be used too, to decide if the last window or document was closed. Then we have to initialize the backing window ... Last but not least we must know something about our special help frame. It must be handled seperatly. And last but not least - the backing component frame must be detected too. */ void FrameListAnalyzer::impl_analyze() { // reset all members to get a consistent state m_bReferenceIsHidden = sal_False; m_bReferenceIsHelp = sal_False; m_bReferenceIsBacking = sal_False; m_xHelp = css::uno::Reference< css::frame::XFrame >(); m_xBackingComponent = css::uno::Reference< css::frame::XFrame >(); // try to get the task container by using the given supplier css::uno::Reference< css::container::XIndexAccess > xFrameContainer(m_xSupplier->getFrames(), css::uno::UNO_QUERY); // All return list get an initial size to include all possible frames. // They will be packed at the end of this method ... using the actual step positions then. sal_Int32 nVisibleStep = 0; sal_Int32 nHiddenStep = 0; sal_Int32 nModelStep = 0; sal_Int32 nCount = xFrameContainer->getCount(); m_lOtherVisibleFrames.realloc(nCount); m_lOtherHiddenFrames.realloc(nCount); m_lModelFrames.realloc(nCount); // ask for the model of the given reference frame. // It must be compared with the model of every frame of the container // to sort it into the list of frames with the same model. // Supress this step, if right detect mode isn't set. css::uno::Reference< css::frame::XModel > xReferenceModel; if ((m_eDetectMode & E_MODEL) == E_MODEL ) { css::uno::Reference< css::frame::XController > xReferenceController = m_xReferenceFrame->getController(); if (xReferenceController.is()) xReferenceModel = xReferenceController->getModel(); } // check, if the reference frame is in hidden mode. // But look, if this analyze step is realy needed. css::uno::Reference< css::beans::XPropertySet > xSet(m_xReferenceFrame, css::uno::UNO_QUERY); if ( ((m_eDetectMode & E_HIDDEN) == E_HIDDEN) && (xSet.is() ) ) { css::uno::Any aValue = xSet->getPropertyValue(FRAME_PROPNAME_ISHIDDEN); aValue >>= m_bReferenceIsHidden; } // check, if the reference frame includes the backing component. // But look, if this analyze step is realy needed. if ((m_eDetectMode & E_BACKINGCOMPONENT) == E_BACKINGCOMPONENT) { try { css::uno::Reference< css::lang::XMultiServiceFactory > xSMGR = ::utl::getProcessServiceFactory(); css::uno::Reference< css::frame::XModuleManager > xModuleMgr(xSMGR->createInstance(SERVICENAME_MODULEMANAGER), css::uno::UNO_QUERY); ::rtl::OUString sModule = xModuleMgr->identify(m_xReferenceFrame); m_bReferenceIsBacking = (sModule.equals(SERVICENAME_STARTMODULE)); } catch(const css::uno::Exception&) {} } // check, if the reference frame includes the help module. // But look, if this analyze step is realy needed. if ( ((m_eDetectMode & E_HELP) == E_HELP ) && (m_xReferenceFrame.is() ) && (m_xReferenceFrame->getName() == SPECIALTARGET_HELPTASK) ) { m_bReferenceIsHelp = sal_True; } try { // Step over all frames of the desktop frame container and analyze it. for (sal_Int32 i=0; i<nCount; ++i) { // Ignore invalid items ... and of course the reference frame. // It will be a member of the given frame list too - but it was already // analyzed before! css::uno::Reference< css::frame::XFrame > xFrame; if ( !(xFrameContainer->getByIndex(i) >>= xFrame) || !(xFrame.is() ) || (xFrame==m_xReferenceFrame ) ) continue; #ifdef ENABLE_WARNINGS if ( ((m_eDetectMode & E_ZOMBIE) == E_ZOMBIE) && ( (!xFrame->getContainerWindow().is()) || (!xFrame->getComponentWindow().is()) ) ) { LOG_WARNING("FrameListAnalyzer::impl_analyze()", "ZOMBIE!") } #endif // ------------------------------------------------- // a) Is it the special help task? // Return it seperated from any return list. if ( ((m_eDetectMode & E_HELP) == E_HELP ) && (xFrame->getName()==SPECIALTARGET_HELPTASK) ) { m_xHelp = xFrame; continue; } // ------------------------------------------------- // b) Or is includes this task the special backing component? // Return it seperated from any return list. // But check if the reference task itself is the backing frame. // Our user mst know it to decide right. if ((m_eDetectMode & E_BACKINGCOMPONENT) == E_BACKINGCOMPONENT) { try { css::uno::Reference< css::lang::XMultiServiceFactory > xSMGR = ::utl::getProcessServiceFactory(); css::uno::Reference< css::frame::XModuleManager > xModuleMgr(xSMGR->createInstance(SERVICENAME_MODULEMANAGER), css::uno::UNO_QUERY); ::rtl::OUString sModule = xModuleMgr->identify(xFrame); if (sModule.equals(SERVICENAME_STARTMODULE)) { m_xBackingComponent = xFrame; continue; } } catch(const css::uno::Exception&) {} } // ------------------------------------------------- // c) Or is it the a task, which uses the specified model? // Add it to the list of "model frames". if ((m_eDetectMode & E_MODEL) == E_MODEL) { css::uno::Reference< css::frame::XController > xController = xFrame->getController(); css::uno::Reference< css::frame::XModel > xModel ; if (xController.is()) xModel = xController->getModel(); if (xModel==xReferenceModel) { m_lModelFrames[nModelStep] = xFrame; ++nModelStep; continue; } } // ------------------------------------------------- // d) Or is it the a task, which use another or no model at all? // Add it to the list of "other frames". But look for it's // visible state ... if it's allowed to do so. // ------------------------------------------------- sal_Bool bHidden = sal_False; if ((m_eDetectMode & E_HIDDEN) == E_HIDDEN ) { xSet = css::uno::Reference< css::beans::XPropertySet >(xFrame, css::uno::UNO_QUERY); if (xSet.is()) { css::uno::Any aValue = xSet->getPropertyValue(FRAME_PROPNAME_ISHIDDEN); aValue >>= bHidden; } } if (bHidden) { m_lOtherHiddenFrames[nHiddenStep] = xFrame; ++nHiddenStep; } else { m_lOtherVisibleFrames[nVisibleStep] = xFrame; ++nVisibleStep; } } } catch(css::lang::IndexOutOfBoundsException) { // stop copying if index seams to be wrong. // This interface can't realy guarantee its count for multithreaded // environments. So it can occure! } // Pack both lists by using the actual step positions. // All empty or ignorable items should exist at the end of these lists // behind the position pointers. So they will be removed by a reallocation. m_lOtherVisibleFrames.realloc(nVisibleStep); m_lOtherHiddenFrames.realloc(nHiddenStep); m_lModelFrames.realloc(nModelStep); } } // namespace framework <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: propertysethelper.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: kz $ $Date: 2005-11-04 15:42:05 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ //_________________________________________________________________________________________________________________ // my own includes #include <classes/propertysethelper.hxx> #include <threadhelp/transactionguard.hxx> #include <threadhelp/readguard.hxx> #include <threadhelp/writeguard.hxx> //_________________________________________________________________________________________________________________ // interface includes //_________________________________________________________________________________________________________________ // other includes //_________________________________________________________________________________________________________________ // namespace namespace framework{ //_________________________________________________________________________________________________________________ // non exported definitions //----------------------------------------------------------------------------- PropertySetHelper::PropertySetHelper(const css::uno::Reference< css::lang::XMultiServiceFactory >& xSMGR , ::vos::IMutex* pSolarMutex , sal_Bool bReleaseLockOnCall) : ThreadHelpBase (pSolarMutex ) , TransactionBase ( ) , m_xSMGR (xSMGR ) , m_lSimpleChangeListener(m_aLock.getShareableOslMutex()) , m_lVetoChangeListener (m_aLock.getShareableOslMutex()) , m_bReleaseLockOnCall (bReleaseLockOnCall ) { } //----------------------------------------------------------------------------- PropertySetHelper::~PropertySetHelper() { } //----------------------------------------------------------------------------- void PropertySetHelper::impl_setPropertyChangeBroadcaster(const css::uno::Reference< css::uno::XInterface >& xBroadcaster) { TransactionGuard aTransaction(m_aTransactionManager, E_SOFTEXCEPTIONS); // SAFE -> WriteGuard aWriteLock(m_aLock); m_xBroadcaster = xBroadcaster; aWriteLock.unlock(); // <- SAFE } //----------------------------------------------------------------------------- void SAL_CALL PropertySetHelper::impl_addPropertyInfo(const css::beans::Property& aProperty) throw(css::beans::PropertyExistException, css::uno::Exception ) { TransactionGuard aTransaction(m_aTransactionManager, E_SOFTEXCEPTIONS); // SAFE -> WriteGuard aWriteLock(m_aLock); PropertySetHelper::TPropInfoHash::const_iterator pIt = m_lProps.find(aProperty.Name); if (pIt != m_lProps.end()) throw css::beans::PropertyExistException(); m_lProps[aProperty.Name] = aProperty; // <- SAFE } //----------------------------------------------------------------------------- void SAL_CALL PropertySetHelper::impl_removePropertyInfo(const ::rtl::OUString& sProperty) throw(css::beans::UnknownPropertyException, css::uno::Exception ) { TransactionGuard aTransaction(m_aTransactionManager, E_SOFTEXCEPTIONS); // SAFE -> WriteGuard aWriteLock(m_aLock); PropertySetHelper::TPropInfoHash::iterator pIt = m_lProps.find(sProperty); if (pIt == m_lProps.end()) throw css::beans::UnknownPropertyException(); m_lProps.erase(pIt); // <- SAFE } //----------------------------------------------------------------------------- void SAL_CALL PropertySetHelper::impl_enablePropertySet() { } //----------------------------------------------------------------------------- void SAL_CALL PropertySetHelper::impl_disablePropertySet() { TransactionGuard aTransaction(m_aTransactionManager, E_SOFTEXCEPTIONS); // SAFE -> WriteGuard aWriteLock(m_aLock); css::uno::Reference< css::uno::XInterface > xThis(static_cast< css::beans::XPropertySet* >(this), css::uno::UNO_QUERY); css::lang::EventObject aEvent(xThis); m_lSimpleChangeListener.disposeAndClear(aEvent); m_lVetoChangeListener.disposeAndClear(aEvent); m_lProps.free(); aWriteLock.unlock(); // <- SAFE } //----------------------------------------------------------------------------- sal_Bool PropertySetHelper::impl_existsVeto(const css::beans::PropertyChangeEvent& aEvent) { /* Dont use the lock here! The used helper is threadsafe and it lives for the whole lifetime of our own object. */ ::cppu::OInterfaceContainerHelper* pVetoListener = m_lVetoChangeListener.getContainer(aEvent.PropertyName); if (! pVetoListener) return sal_False; ::cppu::OInterfaceIteratorHelper pListener(*pVetoListener); while (pListener.hasMoreElements()) { try { css::uno::Reference< css::beans::XVetoableChangeListener > xListener( ((css::beans::XVetoableChangeListener*)pListener.next()), css::uno::UNO_QUERY_THROW); xListener->vetoableChange(aEvent); } catch(const css::uno::RuntimeException&) { pListener.remove(); } catch(const css::beans::PropertyVetoException&) { return sal_True; } } return sal_False; } //----------------------------------------------------------------------------- void PropertySetHelper::impl_notifyChangeListener(const css::beans::PropertyChangeEvent& aEvent) { /* Dont use the lock here! The used helper is threadsafe and it lives for the whole lifetime of our own object. */ ::cppu::OInterfaceContainerHelper* pSimpleListener = m_lSimpleChangeListener.getContainer(aEvent.PropertyName); if (! pSimpleListener) return; ::cppu::OInterfaceIteratorHelper pListener(*pSimpleListener); while (pListener.hasMoreElements()) { try { css::uno::Reference< css::beans::XPropertyChangeListener > xListener( ((css::beans::XVetoableChangeListener*)pListener.next()), css::uno::UNO_QUERY_THROW); xListener->propertyChange(aEvent); } catch(const css::uno::RuntimeException&) { pListener.remove(); } } } //----------------------------------------------------------------------------- css::uno::Reference< css::beans::XPropertySetInfo > SAL_CALL PropertySetHelper::getPropertySetInfo() throw(css::uno::RuntimeException) { TransactionGuard aTransaction(m_aTransactionManager, E_HARDEXCEPTIONS); css::uno::Reference< css::beans::XPropertySetInfo > xInfo(static_cast< css::beans::XPropertySetInfo* >(this), css::uno::UNO_QUERY_THROW); return xInfo; } //----------------------------------------------------------------------------- void SAL_CALL PropertySetHelper::setPropertyValue(const ::rtl::OUString& sProperty, const css::uno::Any& aValue ) throw(css::beans::UnknownPropertyException, css::beans::PropertyVetoException , css::lang::IllegalArgumentException , css::lang::WrappedTargetException , css::uno::RuntimeException ) { // TODO look for e.g. readonly props and reject setProp() call! TransactionGuard aTransaction(m_aTransactionManager, E_HARDEXCEPTIONS); // SAFE -> WriteGuard aWriteLock(m_aLock); PropertySetHelper::TPropInfoHash::const_iterator pIt = m_lProps.find(sProperty); if (pIt == m_lProps.end()) throw css::beans::UnknownPropertyException(); css::beans::Property aPropInfo = pIt->second; sal_Bool bLocked = sal_True; if (m_bReleaseLockOnCall) { aWriteLock.unlock(); bLocked = sal_False; // <- SAFE } css::uno::Any aCurrentValue = impl_getPropertyValue(aPropInfo.Name, aPropInfo.Handle); if (! bLocked) { // SAFE -> aWriteLock.lock(); bLocked = sal_True; } sal_Bool bWillBeChanged = (aCurrentValue != aValue); if (! bWillBeChanged) return; css::beans::PropertyChangeEvent aEvent; aEvent.PropertyName = aPropInfo.Name; aEvent.Further = sal_False; aEvent.PropertyHandle = aPropInfo.Handle; aEvent.OldValue = aCurrentValue; aEvent.NewValue = aValue; aEvent.Source = css::uno::Reference< css::uno::XInterface >(m_xBroadcaster.get(), css::uno::UNO_QUERY); if (m_bReleaseLockOnCall) { aWriteLock.unlock(); bLocked = sal_False; // <- SAFE } if (impl_existsVeto(aEvent)) throw css::beans::PropertyVetoException(); impl_setPropertyValue(aPropInfo.Name, aPropInfo.Handle, aValue); impl_notifyChangeListener(aEvent); } //----------------------------------------------------------------------------- css::uno::Any SAL_CALL PropertySetHelper::getPropertyValue(const ::rtl::OUString& sProperty) throw(css::beans::UnknownPropertyException, css::lang::WrappedTargetException , css::uno::RuntimeException ) { TransactionGuard aTransaction(m_aTransactionManager, E_HARDEXCEPTIONS); // SAFE -> ReadGuard aReadLock(m_aLock); PropertySetHelper::TPropInfoHash::const_iterator pIt = m_lProps.find(sProperty); if (pIt == m_lProps.end()) throw css::beans::UnknownPropertyException(); css::beans::Property aPropInfo = pIt->second; sal_Bool bLocked = sal_True; if (m_bReleaseLockOnCall) { aReadLock.unlock(); bLocked = sal_False; // <- SAFE } css::uno::Any aValue = impl_getPropertyValue(aPropInfo.Name, aPropInfo.Handle); return aValue; } //----------------------------------------------------------------------------- void SAL_CALL PropertySetHelper::addPropertyChangeListener(const ::rtl::OUString& sProperty, const css::uno::Reference< css::beans::XPropertyChangeListener >& xListener) throw(css::beans::UnknownPropertyException, css::lang::WrappedTargetException , css::uno::RuntimeException ) { TransactionGuard aTransaction(m_aTransactionManager, E_HARDEXCEPTIONS); // SAFE -> ReadGuard aReadLock(m_aLock); PropertySetHelper::TPropInfoHash::const_iterator pIt = m_lProps.find(sProperty); if (pIt == m_lProps.end()) throw css::beans::UnknownPropertyException(); aReadLock.unlock(); // <- SAFE m_lSimpleChangeListener.addInterface(sProperty, xListener); } //----------------------------------------------------------------------------- void SAL_CALL PropertySetHelper::removePropertyChangeListener(const ::rtl::OUString& sProperty, const css::uno::Reference< css::beans::XPropertyChangeListener >& xListener) throw(css::beans::UnknownPropertyException, css::lang::WrappedTargetException , css::uno::RuntimeException ) { TransactionGuard aTransaction(m_aTransactionManager, E_SOFTEXCEPTIONS); // SAFE -> ReadGuard aReadLock(m_aLock); PropertySetHelper::TPropInfoHash::const_iterator pIt = m_lProps.find(sProperty); if (pIt == m_lProps.end()) throw css::beans::UnknownPropertyException(); aReadLock.unlock(); // <- SAFE m_lSimpleChangeListener.removeInterface(sProperty, xListener); } //----------------------------------------------------------------------------- void SAL_CALL PropertySetHelper::addVetoableChangeListener(const ::rtl::OUString& sProperty, const css::uno::Reference< css::beans::XVetoableChangeListener >& xListener) throw(css::beans::UnknownPropertyException, css::lang::WrappedTargetException , css::uno::RuntimeException ) { TransactionGuard aTransaction(m_aTransactionManager, E_HARDEXCEPTIONS); // SAFE -> ReadGuard aReadLock(m_aLock); PropertySetHelper::TPropInfoHash::const_iterator pIt = m_lProps.find(sProperty); if (pIt == m_lProps.end()) throw css::beans::UnknownPropertyException(); aReadLock.unlock(); // <- SAFE m_lVetoChangeListener.addInterface(sProperty, xListener); } //----------------------------------------------------------------------------- void SAL_CALL PropertySetHelper::removeVetoableChangeListener(const ::rtl::OUString& sProperty, const css::uno::Reference< css::beans::XVetoableChangeListener >& xListener) throw(css::beans::UnknownPropertyException, css::lang::WrappedTargetException , css::uno::RuntimeException ) { TransactionGuard aTransaction(m_aTransactionManager, E_SOFTEXCEPTIONS); // SAFE -> ReadGuard aReadLock(m_aLock); PropertySetHelper::TPropInfoHash::const_iterator pIt = m_lProps.find(sProperty); if (pIt == m_lProps.end()) throw css::beans::UnknownPropertyException(); aReadLock.unlock(); // <- SAFE m_lVetoChangeListener.removeInterface(sProperty, xListener); } //----------------------------------------------------------------------------- css::uno::Sequence< css::beans::Property > SAL_CALL PropertySetHelper::getProperties() throw(css::uno::RuntimeException) { TransactionGuard aTransaction(m_aTransactionManager, E_HARDEXCEPTIONS); // SAFE -> ReadGuard aReadLock(m_aLock); sal_Int32 c = (sal_Int32)m_lProps.size(); css::uno::Sequence< css::beans::Property > lProps(c); PropertySetHelper::TPropInfoHash::const_iterator pIt ; for ( pIt = m_lProps.begin(); pIt != m_lProps.end() ; ++pIt ) { lProps[--c] = pIt->second; } return lProps; // <- SAFE } //----------------------------------------------------------------------------- css::beans::Property SAL_CALL PropertySetHelper::getPropertyByName(const ::rtl::OUString& sName) throw(css::beans::UnknownPropertyException, css::uno::RuntimeException ) { TransactionGuard aTransaction(m_aTransactionManager, E_HARDEXCEPTIONS); // SAFE -> ReadGuard aReadLock(m_aLock); PropertySetHelper::TPropInfoHash::const_iterator pIt = m_lProps.find(sName); if (pIt == m_lProps.end()) throw css::beans::UnknownPropertyException(); return pIt->second; // <- SAFE } //----------------------------------------------------------------------------- sal_Bool SAL_CALL PropertySetHelper::hasPropertyByName(const ::rtl::OUString& sName) throw(css::uno::RuntimeException) { TransactionGuard aTransaction(m_aTransactionManager, E_HARDEXCEPTIONS); // SAFE -> ReadGuard aReadLock(m_aLock); PropertySetHelper::TPropInfoHash::iterator pIt = m_lProps.find(sName); sal_Bool bExist = (pIt != m_lProps.end()); return bExist; // <- SAFE } } // namespace framework <commit_msg>INTEGRATION: CWS fwk29 (1.4.24); FILE MERGED 2005/12/12 09:41:59 as 1.4.24.1: #120310# use right TransactionManager instance ... and use it right<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: propertysethelper.cxx,v $ * * $Revision: 1.5 $ * * last change: $Author: rt $ $Date: 2006-02-07 10:23:55 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ //_________________________________________________________________________________________________________________ // my own includes #include <classes/propertysethelper.hxx> #include <threadhelp/transactionguard.hxx> #include <threadhelp/readguard.hxx> #include <threadhelp/writeguard.hxx> //_________________________________________________________________________________________________________________ // interface includes //_________________________________________________________________________________________________________________ // other includes //_________________________________________________________________________________________________________________ // namespace namespace framework{ //_________________________________________________________________________________________________________________ // non exported definitions //----------------------------------------------------------------------------- PropertySetHelper::PropertySetHelper(const css::uno::Reference< css::lang::XMultiServiceFactory >& xSMGR , LockHelper* pExternalLock , TransactionManager* pExternalTransactionManager , sal_Bool bReleaseLockOnCall ) : m_xSMGR (xSMGR ) , m_lSimpleChangeListener(pExternalLock->getShareableOslMutex()) , m_lVetoChangeListener (pExternalLock->getShareableOslMutex()) , m_bReleaseLockOnCall (bReleaseLockOnCall ) , m_rLock (*pExternalLock ) , m_rTransactionManager (*pExternalTransactionManager ) { } //----------------------------------------------------------------------------- PropertySetHelper::~PropertySetHelper() { } //----------------------------------------------------------------------------- void PropertySetHelper::impl_setPropertyChangeBroadcaster(const css::uno::Reference< css::uno::XInterface >& xBroadcaster) { TransactionGuard aTransaction(m_rTransactionManager, E_SOFTEXCEPTIONS); // SAFE -> WriteGuard aWriteLock(m_rLock); m_xBroadcaster = xBroadcaster; aWriteLock.unlock(); // <- SAFE } //----------------------------------------------------------------------------- void SAL_CALL PropertySetHelper::impl_addPropertyInfo(const css::beans::Property& aProperty) throw(css::beans::PropertyExistException, css::uno::Exception ) { TransactionGuard aTransaction(m_rTransactionManager, E_SOFTEXCEPTIONS); // SAFE -> WriteGuard aWriteLock(m_rLock); PropertySetHelper::TPropInfoHash::const_iterator pIt = m_lProps.find(aProperty.Name); if (pIt != m_lProps.end()) throw css::beans::PropertyExistException(); m_lProps[aProperty.Name] = aProperty; // <- SAFE } //----------------------------------------------------------------------------- void SAL_CALL PropertySetHelper::impl_removePropertyInfo(const ::rtl::OUString& sProperty) throw(css::beans::UnknownPropertyException, css::uno::Exception ) { TransactionGuard aTransaction(m_rTransactionManager, E_SOFTEXCEPTIONS); // SAFE -> WriteGuard aWriteLock(m_rLock); PropertySetHelper::TPropInfoHash::iterator pIt = m_lProps.find(sProperty); if (pIt == m_lProps.end()) throw css::beans::UnknownPropertyException(); m_lProps.erase(pIt); // <- SAFE } //----------------------------------------------------------------------------- void SAL_CALL PropertySetHelper::impl_enablePropertySet() { } //----------------------------------------------------------------------------- void SAL_CALL PropertySetHelper::impl_disablePropertySet() { TransactionGuard aTransaction(m_rTransactionManager, E_SOFTEXCEPTIONS); // SAFE -> WriteGuard aWriteLock(m_rLock); css::uno::Reference< css::uno::XInterface > xThis(static_cast< css::beans::XPropertySet* >(this), css::uno::UNO_QUERY); css::lang::EventObject aEvent(xThis); m_lSimpleChangeListener.disposeAndClear(aEvent); m_lVetoChangeListener.disposeAndClear(aEvent); m_lProps.free(); aWriteLock.unlock(); // <- SAFE } //----------------------------------------------------------------------------- sal_Bool PropertySetHelper::impl_existsVeto(const css::beans::PropertyChangeEvent& aEvent) { /* Dont use the lock here! The used helper is threadsafe and it lives for the whole lifetime of our own object. */ ::cppu::OInterfaceContainerHelper* pVetoListener = m_lVetoChangeListener.getContainer(aEvent.PropertyName); if (! pVetoListener) return sal_False; ::cppu::OInterfaceIteratorHelper pListener(*pVetoListener); while (pListener.hasMoreElements()) { try { css::uno::Reference< css::beans::XVetoableChangeListener > xListener( ((css::beans::XVetoableChangeListener*)pListener.next()), css::uno::UNO_QUERY_THROW); xListener->vetoableChange(aEvent); } catch(const css::uno::RuntimeException&) { pListener.remove(); } catch(const css::beans::PropertyVetoException&) { return sal_True; } } return sal_False; } //----------------------------------------------------------------------------- void PropertySetHelper::impl_notifyChangeListener(const css::beans::PropertyChangeEvent& aEvent) { /* Dont use the lock here! The used helper is threadsafe and it lives for the whole lifetime of our own object. */ ::cppu::OInterfaceContainerHelper* pSimpleListener = m_lSimpleChangeListener.getContainer(aEvent.PropertyName); if (! pSimpleListener) return; ::cppu::OInterfaceIteratorHelper pListener(*pSimpleListener); while (pListener.hasMoreElements()) { try { css::uno::Reference< css::beans::XPropertyChangeListener > xListener( ((css::beans::XVetoableChangeListener*)pListener.next()), css::uno::UNO_QUERY_THROW); xListener->propertyChange(aEvent); } catch(const css::uno::RuntimeException&) { pListener.remove(); } } } //----------------------------------------------------------------------------- css::uno::Reference< css::beans::XPropertySetInfo > SAL_CALL PropertySetHelper::getPropertySetInfo() throw(css::uno::RuntimeException) { TransactionGuard aTransaction(m_rTransactionManager, E_HARDEXCEPTIONS); css::uno::Reference< css::beans::XPropertySetInfo > xInfo(static_cast< css::beans::XPropertySetInfo* >(this), css::uno::UNO_QUERY_THROW); return xInfo; } //----------------------------------------------------------------------------- void SAL_CALL PropertySetHelper::setPropertyValue(const ::rtl::OUString& sProperty, const css::uno::Any& aValue ) throw(css::beans::UnknownPropertyException, css::beans::PropertyVetoException , css::lang::IllegalArgumentException , css::lang::WrappedTargetException , css::uno::RuntimeException ) { // TODO look for e.g. readonly props and reject setProp() call! TransactionGuard aTransaction(m_rTransactionManager, E_HARDEXCEPTIONS); // SAFE -> WriteGuard aWriteLock(m_rLock); PropertySetHelper::TPropInfoHash::const_iterator pIt = m_lProps.find(sProperty); if (pIt == m_lProps.end()) throw css::beans::UnknownPropertyException(); css::beans::Property aPropInfo = pIt->second; sal_Bool bLocked = sal_True; if (m_bReleaseLockOnCall) { aWriteLock.unlock(); bLocked = sal_False; // <- SAFE } css::uno::Any aCurrentValue = impl_getPropertyValue(aPropInfo.Name, aPropInfo.Handle); if (! bLocked) { // SAFE -> aWriteLock.lock(); bLocked = sal_True; } sal_Bool bWillBeChanged = (aCurrentValue != aValue); if (! bWillBeChanged) return; css::beans::PropertyChangeEvent aEvent; aEvent.PropertyName = aPropInfo.Name; aEvent.Further = sal_False; aEvent.PropertyHandle = aPropInfo.Handle; aEvent.OldValue = aCurrentValue; aEvent.NewValue = aValue; aEvent.Source = css::uno::Reference< css::uno::XInterface >(m_xBroadcaster.get(), css::uno::UNO_QUERY); if (m_bReleaseLockOnCall) { aWriteLock.unlock(); bLocked = sal_False; // <- SAFE } if (impl_existsVeto(aEvent)) throw css::beans::PropertyVetoException(); impl_setPropertyValue(aPropInfo.Name, aPropInfo.Handle, aValue); impl_notifyChangeListener(aEvent); } //----------------------------------------------------------------------------- css::uno::Any SAL_CALL PropertySetHelper::getPropertyValue(const ::rtl::OUString& sProperty) throw(css::beans::UnknownPropertyException, css::lang::WrappedTargetException , css::uno::RuntimeException ) { TransactionGuard aTransaction(m_rTransactionManager, E_HARDEXCEPTIONS); // SAFE -> ReadGuard aReadLock(m_rLock); PropertySetHelper::TPropInfoHash::const_iterator pIt = m_lProps.find(sProperty); if (pIt == m_lProps.end()) throw css::beans::UnknownPropertyException(); css::beans::Property aPropInfo = pIt->second; sal_Bool bLocked = sal_True; if (m_bReleaseLockOnCall) { aReadLock.unlock(); bLocked = sal_False; // <- SAFE } css::uno::Any aValue = impl_getPropertyValue(aPropInfo.Name, aPropInfo.Handle); return aValue; } //----------------------------------------------------------------------------- void SAL_CALL PropertySetHelper::addPropertyChangeListener(const ::rtl::OUString& sProperty, const css::uno::Reference< css::beans::XPropertyChangeListener >& xListener) throw(css::beans::UnknownPropertyException, css::lang::WrappedTargetException , css::uno::RuntimeException ) { TransactionGuard aTransaction(m_rTransactionManager, E_HARDEXCEPTIONS); // SAFE -> ReadGuard aReadLock(m_rLock); PropertySetHelper::TPropInfoHash::const_iterator pIt = m_lProps.find(sProperty); if (pIt == m_lProps.end()) throw css::beans::UnknownPropertyException(); aReadLock.unlock(); // <- SAFE m_lSimpleChangeListener.addInterface(sProperty, xListener); } //----------------------------------------------------------------------------- void SAL_CALL PropertySetHelper::removePropertyChangeListener(const ::rtl::OUString& sProperty, const css::uno::Reference< css::beans::XPropertyChangeListener >& xListener) throw(css::beans::UnknownPropertyException, css::lang::WrappedTargetException , css::uno::RuntimeException ) { TransactionGuard aTransaction(m_rTransactionManager, E_SOFTEXCEPTIONS); // SAFE -> ReadGuard aReadLock(m_rLock); PropertySetHelper::TPropInfoHash::const_iterator pIt = m_lProps.find(sProperty); if (pIt == m_lProps.end()) throw css::beans::UnknownPropertyException(); aReadLock.unlock(); // <- SAFE m_lSimpleChangeListener.removeInterface(sProperty, xListener); } //----------------------------------------------------------------------------- void SAL_CALL PropertySetHelper::addVetoableChangeListener(const ::rtl::OUString& sProperty, const css::uno::Reference< css::beans::XVetoableChangeListener >& xListener) throw(css::beans::UnknownPropertyException, css::lang::WrappedTargetException , css::uno::RuntimeException ) { TransactionGuard aTransaction(m_rTransactionManager, E_HARDEXCEPTIONS); // SAFE -> ReadGuard aReadLock(m_rLock); PropertySetHelper::TPropInfoHash::const_iterator pIt = m_lProps.find(sProperty); if (pIt == m_lProps.end()) throw css::beans::UnknownPropertyException(); aReadLock.unlock(); // <- SAFE m_lVetoChangeListener.addInterface(sProperty, xListener); } //----------------------------------------------------------------------------- void SAL_CALL PropertySetHelper::removeVetoableChangeListener(const ::rtl::OUString& sProperty, const css::uno::Reference< css::beans::XVetoableChangeListener >& xListener) throw(css::beans::UnknownPropertyException, css::lang::WrappedTargetException , css::uno::RuntimeException ) { TransactionGuard aTransaction(m_rTransactionManager, E_SOFTEXCEPTIONS); // SAFE -> ReadGuard aReadLock(m_rLock); PropertySetHelper::TPropInfoHash::const_iterator pIt = m_lProps.find(sProperty); if (pIt == m_lProps.end()) throw css::beans::UnknownPropertyException(); aReadLock.unlock(); // <- SAFE m_lVetoChangeListener.removeInterface(sProperty, xListener); } //----------------------------------------------------------------------------- css::uno::Sequence< css::beans::Property > SAL_CALL PropertySetHelper::getProperties() throw(css::uno::RuntimeException) { TransactionGuard aTransaction(m_rTransactionManager, E_HARDEXCEPTIONS); // SAFE -> ReadGuard aReadLock(m_rLock); sal_Int32 c = (sal_Int32)m_lProps.size(); css::uno::Sequence< css::beans::Property > lProps(c); PropertySetHelper::TPropInfoHash::const_iterator pIt ; for ( pIt = m_lProps.begin(); pIt != m_lProps.end() ; ++pIt ) { lProps[--c] = pIt->second; } return lProps; // <- SAFE } //----------------------------------------------------------------------------- css::beans::Property SAL_CALL PropertySetHelper::getPropertyByName(const ::rtl::OUString& sName) throw(css::beans::UnknownPropertyException, css::uno::RuntimeException ) { TransactionGuard aTransaction(m_rTransactionManager, E_HARDEXCEPTIONS); // SAFE -> ReadGuard aReadLock(m_rLock); PropertySetHelper::TPropInfoHash::const_iterator pIt = m_lProps.find(sName); if (pIt == m_lProps.end()) throw css::beans::UnknownPropertyException(); return pIt->second; // <- SAFE } //----------------------------------------------------------------------------- sal_Bool SAL_CALL PropertySetHelper::hasPropertyByName(const ::rtl::OUString& sName) throw(css::uno::RuntimeException) { TransactionGuard aTransaction(m_rTransactionManager, E_HARDEXCEPTIONS); // SAFE -> ReadGuard aReadLock(m_rLock); PropertySetHelper::TPropInfoHash::iterator pIt = m_lProps.find(sName); sal_Bool bExist = (pIt != m_lProps.end()); return bExist; // <- SAFE } } // namespace framework <|endoftext|>
<commit_before>// Copyright 2010-2012 RethinkDB, all rights reserved. #include <string.h> #include <algorithm> #include "rdb_protocol/exceptions.hpp" #include "rdb_protocol/rdb_protocol_json.hpp" #include "utils.hpp" write_message_t &operator<<(write_message_t &msg, const boost::shared_ptr<scoped_cJSON_t> &cjson) { rassert(NULL != cjson.get() && NULL != cjson->get()); msg << *cjson->get(); return msg; } MUST_USE archive_result_t deserialize(read_stream_t *s, boost::shared_ptr<scoped_cJSON_t> *cjson) { cJSON *data = cJSON_CreateBlank(); archive_result_t res = deserialize(s, data); if (res) { return res; } *cjson = boost::shared_ptr<scoped_cJSON_t>(new scoped_cJSON_t(data)); return ARCHIVE_SUCCESS; } namespace query_language { /* In a less ridiculous world, the C++ standard wouldn't have dropped designated initializers for arrays, and this namespace wouldn't be necessary. */ namespace cJSON_type_ordering { struct rank_wrapper { std::map<int, int> rank; rank_wrapper() { rank[cJSON_Array] = 0; rank[cJSON_False] = 1; rank[cJSON_True] = 2; rank[cJSON_NULL] = 3; rank[cJSON_Number] = 4; rank[cJSON_Object] = 5; rank[cJSON_String] = 6; } }; rank_wrapper wrapper; int cmp(int t1, int t2) { return wrapper.rank[t1] - wrapper.rank[t2]; } } class char_star_cmp_functor { public: bool operator()(const char *x, const char *y) { return strcmp(x, y) < 0; } }; class compare_functor { public: bool operator()(const std::pair<std::string, cJSON *> &l, const std::pair<std::string, cJSON *> &r) { if (l.first != r.first) { return l.first < r.first; } else { return json_cmp(l.second, r.second); } } }; int json_cmp(cJSON *l, cJSON *r) { if (l->type != r->type) { return cJSON_type_ordering::cmp(l->type, r->type); } switch (l->type) { case cJSON_False: if (r->type == cJSON_True) { return -1; } else if (r->type == cJSON_False) { return 0; } break; case cJSON_True: if (r->type == cJSON_True) { return 0; } else if (r->type == cJSON_False) { return 1; } break; case cJSON_NULL: return 0; break; case cJSON_Number: if (l->valuedouble < r->valuedouble) { return -1; } else if (l->valuedouble > r->valuedouble) { return 1; } else { return 0; // TODO: Handle NaN? } break; case cJSON_String: return strcmp(l->valuestring, r->valuestring); break; case cJSON_Array: { int lsize = cJSON_GetArraySize(l), rsize = cJSON_GetArraySize(r); for (int i = 0; i < lsize; ++i) { if (i >= rsize) { return 1; // e.g. cmp([0, 1], [0]) } int cmp = json_cmp(cJSON_GetArrayItem(l, i), cJSON_GetArrayItem(r, i)); if (cmp) { return cmp; } } if (rsize > lsize) return -1; // e.g. cmp([0], [0, 1]); return 0; } break; case cJSON_Object: { std::map<char *, cJSON *, char_star_cmp_functor> lvalues, rvalues; json_iterator_t l_json_it(l); while (cJSON *cur = l_json_it.next()) { //guarantee makes sure there are no duplicates guarantee(lvalues.insert(std::make_pair(cur->string, cur)).second); } json_iterator_t r_json_it(r); while (cJSON *cur = r_json_it.next()) { //guarantee makes sure there are no duplicates guarantee(rvalues.insert(std::make_pair(cur->string, cur)).second); } if (lexicographical_compare(lvalues.begin(), lvalues.end(), rvalues.begin(), rvalues.end(), compare_functor())) { return -1; } else if (lexicographical_compare(rvalues.begin(), rvalues.end(), lvalues.begin(), lvalues.end(), compare_functor())) { return 1; } else { return 0; } } break; default: unreachable(); break; } unreachable(); } void require_type(const cJSON *json, int type, const backtrace_t &b) { if (json->type != type) { throw runtime_exc_t(strprintf("Required type: %s but found %s.", cJSON_type_to_string(type).c_str(), cJSON_type_to_string(json->type).c_str()), b); } } } // namespace query_language <commit_msg>Fixes an issue that would have caused us to segfault.<commit_after>// Copyright 2010-2012 RethinkDB, all rights reserved. #include <string.h> #include <algorithm> #include "rdb_protocol/exceptions.hpp" #include "rdb_protocol/rdb_protocol_json.hpp" #include "utils.hpp" write_message_t &operator<<(write_message_t &msg, const boost::shared_ptr<scoped_cJSON_t> &cjson) { rassert(NULL != cjson.get() && NULL != cjson->get()); msg << *cjson->get(); return msg; } MUST_USE archive_result_t deserialize(read_stream_t *s, boost::shared_ptr<scoped_cJSON_t> *cjson) { cJSON *data = cJSON_CreateBlank(); archive_result_t res = deserialize(s, data); if (res) { return res; } *cjson = boost::shared_ptr<scoped_cJSON_t>(new scoped_cJSON_t(data)); return ARCHIVE_SUCCESS; } namespace query_language { /* In a less ridiculous world, the C++ standard wouldn't have dropped designated initializers for arrays, and this namespace wouldn't be necessary. */ namespace cJSON_type_ordering { struct rank_wrapper { std::map<int, int> rank; rank_wrapper() { rank[cJSON_Array] = 0; rank[cJSON_False] = 1; rank[cJSON_True] = 2; rank[cJSON_NULL] = 3; rank[cJSON_Number] = 4; rank[cJSON_Object] = 5; rank[cJSON_String] = 6; } }; rank_wrapper wrapper; int cmp(int t1, int t2) { return wrapper.rank[t1] - wrapper.rank[t2]; } } class char_star_cmp_functor { public: bool operator()(const char *x, const char *y) { return strcmp(x, y) < 0; } }; class compare_functor { public: bool operator()(const std::pair<std::string, cJSON *> &l, const std::pair<std::string, cJSON *> &r) { if (l.first != r.first) { return l.first < r.first; } else { return json_cmp(l.second, r.second); } } }; int json_cmp(cJSON *l, cJSON *r) { if (l->type != r->type) { return cJSON_type_ordering::cmp(l->type, r->type); } switch (l->type) { case cJSON_False: if (r->type == cJSON_True) { return -1; } else if (r->type == cJSON_False) { return 0; } break; case cJSON_True: if (r->type == cJSON_True) { return 0; } else if (r->type == cJSON_False) { return 1; } break; case cJSON_NULL: return 0; break; case cJSON_Number: if (l->valuedouble < r->valuedouble) { return -1; } else if (l->valuedouble > r->valuedouble) { return 1; } else { return 0; // TODO: Handle NaN? } break; case cJSON_String: return strcmp(l->valuestring, r->valuestring); break; case cJSON_Array: { int lsize = cJSON_GetArraySize(l), rsize = cJSON_GetArraySize(r); for (int i = 0; i < lsize; ++i) { if (i >= rsize) { return 1; // e.g. cmp([0, 1], [0]) } int cmp = json_cmp(cJSON_GetArrayItem(l, i), cJSON_GetArrayItem(r, i)); if (cmp != 0) { return cmp; } } if (rsize > lsize) return -1; // e.g. cmp([0], [0, 1]); return 0; } break; case cJSON_Object: { std::map<char *, cJSON *, char_star_cmp_functor> lvalues, rvalues; json_iterator_t l_json_it(l); while (cJSON *cur = l_json_it.next()) { //If this guarantee trips we would have segfaulted on insertion guarantee(cur->string != NULL, "cJSON object is in a map but has no key set... something has gone wrong with cJSON."); //guarantee makes sure there are no duplicates guarantee(lvalues.insert(std::make_pair(cur->string, cur)).second); } json_iterator_t r_json_it(r); while (cJSON *cur = r_json_it.next()) { //If this guarantee trips we would have segfaulted on insertion guarantee(cur->string != NULL, "cJSON object is in a map but has no key set... something has gone wrong with cJSON."); //guarantee makes sure there are no duplicates guarantee(rvalues.insert(std::make_pair(cur->string, cur)).second); } if (lexicographical_compare(lvalues.begin(), lvalues.end(), rvalues.begin(), rvalues.end(), compare_functor())) { return -1; } else if (lexicographical_compare(rvalues.begin(), rvalues.end(), lvalues.begin(), lvalues.end(), compare_functor())) { return 1; } else { return 0; } } break; default: unreachable(); break; } unreachable(); } void require_type(const cJSON *json, int type, const backtrace_t &b) { if (json->type != type) { throw runtime_exc_t(strprintf("Required type: %s but found %s.", cJSON_type_to_string(type).c_str(), cJSON_type_to_string(json->type).c_str()), b); } } } // namespace query_language <|endoftext|>
<commit_before>#include "MaterialEditorScene.hh" #include <imgui/imgui.h> #include <Utils/OpenGL.hh> #include <Convertor/MaterialConvertor.hpp> #include <Utils/Directory.hpp> #include <Utils/Path.hpp> #include <Utils/FileSystemHelpers.hpp> #include <EditorConfiguration.hpp> #include <glm/glm.hpp> #include <glm/gtc/type_ptr.hpp> namespace AGE { static const char const *_nameTexture[ModeTexture::size] = { "ambient texture", "diffuse texture", "emissive texture", "reflective texture", "specular texture", "normal texture", "bump texture" }; const std::string MaterialEditorScene::Name = "MaterialEditor"; MaterialEditorScene::MaterialEditorScene(AGE::Engine *engine) : AScene(engine), _mode(ModeMaterialEditor::selectMaterial), _indexMaterial(-1) { _resetEdition(); } MaterialEditorScene::~MaterialEditorScene(void) { } bool MaterialEditorScene::_userStart() { return true; } void MaterialEditorScene::_resetEdition() { _editModeName = false; _indexSubMaterial = -1; memset(_bufferName, 0, NAME_LENGTH); for (auto index = 0; index < ModeTexture::size; ++index) { memset(_bufferTexture[index], 0, TEXTURE_LENGTH); } for (auto index = 0; index < ModeTexture::size; ++index) { _editModeTexture[index] = false; } } void MaterialEditorScene::_selectMaterial() { const std::string currentDir = Directory::GetCurrentDirectory(); const std::string absPath = Path::AbsoluteName(currentDir.c_str(), WE::EditorConfiguration::GetCookedDirectory().c_str()); std::vector<std::string> materialGettable; std::vector<std::string> materialFullPath; Directory dir; const bool succeed = dir.open(absPath.c_str()); AGE_ASSERT(succeed && "Impossible to open directory"); for (auto it = dir.recursive_begin(); it != dir.recursive_end(); ++it) { if (Directory::IsFile(*it) && AGE::FileSystemHelpers::GetExtension(*it) == "mage") { materialGettable.push_back(std::string(Path::RelativeName(absPath.c_str(), *it))); materialFullPath.push_back(*it); } } dir.close(); char const **matListBox = new char const *[materialGettable.size()]; for (auto index = 0; index < materialFullPath.size(); ++index) { matListBox[index] = materialGettable[index].c_str(); } ImGui::ListBox("List of material existing", &_indexMaterial, matListBox, materialFullPath.size()); delete[] matListBox; if (_indexMaterial != -1 && ImGui::Button("open a material")) { _resetEdition(); std::shared_ptr<MaterialDataSet> material_data_set = std::make_shared<MaterialDataSet>(); std::ifstream ifs(materialFullPath[_indexMaterial]); cereal::PortableBinaryInputArchive ar(ifs); ar(*material_data_set.get()); _current = *material_data_set; if (_current.name == "") { std::string fileName = std::string(materialGettable[_indexMaterial]); _current.name = fileName.substr(0, fileName.find('.')); } _mode = ModeMaterialEditor::selectSubMaterial; } if (_indexMaterial == -1) { ImGui::Text("Please select one material for edition"); } } void MaterialEditorScene::_editTexture(ModeTexture mode, std::string &current) { if (!_editModeTexture[mode]) { if (current.empty()) ImGui::Text(std::string("No " + std::string(_nameTexture[mode]) + "...").c_str()); else ImGui::Text(current.c_str()); ImGui::SameLine(); if (ImGui::Button("Edit texture")) _editModeTexture[mode] = true; } else { ImGui::InputText(_nameTexture[mode], _bufferTexture[mode], NAME_LENGTH); ImGui::SameLine(); if (ImGui::Button("valid new texture")) { current = std::string(_bufferName); _editModeTexture[mode] = false; } } } void MaterialEditorScene::_editName() { if (!_editModeName) { if (_current.name.empty()) ImGui::Text("No name..."); else ImGui::Text(_current.name.c_str()); ImGui::SameLine(); if (ImGui::Button("Edit name")) _editModeName = true; } else { ImGui::InputText("", _bufferName, NAME_LENGTH); ImGui::SameLine(); if (ImGui::Button("valid new name")) { _current.name = std::string(_bufferName); _editModeName = false; } } } void MaterialEditorScene::_selectSubMaterial() { if (ImGui::Button("precedent")) _mode = ModeMaterialEditor::selectMaterial; ImGui::Separator(); ImGui::Spacing(); _editName(); std::vector<std::string> subMaterials; for (auto index = 0; index < _current.collection.size(); ++index) subMaterials.emplace_back(std::string("sub material: ") + std::to_string(index)); char const **matListBox = new char const *[_current.collection.size()]; for (auto index = 0; index < _current.collection.size(); ++index) matListBox[index] = subMaterials[index].c_str(); ImGui::ListBox("List of sub material", &_indexSubMaterial, matListBox, _current.collection.size()); delete[] matListBox; if (_indexSubMaterial != -1 && ImGui::Button("open a sub material")) _mode = ModeMaterialEditor::edit; if (_indexSubMaterial == -1) ImGui::Text("Please select one sub material for edition"); _saveEdit(); } void MaterialEditorScene::_saveEdit() { if (ImGui::Button("Save Edition")) { const std::string currentDir = Directory::GetCurrentDirectory(); const std::string absPath = Path::AbsoluteName(currentDir.c_str(), WE::EditorConfiguration::GetCookedDirectory().c_str()); std::ofstream file(absPath + _current.name + ".mage"); cereal::PortableBinaryOutputArchive ar(file); ar(_current); } } void MaterialEditorScene::_editData() { if (ImGui::Button("precedent")) _mode = ModeMaterialEditor::selectSubMaterial; MaterialData &mat = _current.collection[_indexSubMaterial]; ImGui::InputFloat3("ambient", glm::value_ptr(mat.ambient)); ImGui::InputFloat3("diffuse", glm::value_ptr(mat.diffuse)); ImGui::InputFloat3("emissive", glm::value_ptr(mat.emissive)); ImGui::InputFloat3("reflective", glm::value_ptr(mat.reflective)); ImGui::InputFloat3("specular", glm::value_ptr(mat.specular)); _editTexture(ModeTexture::diffuse, mat.diffuseTexPath); _editTexture(ModeTexture::specular, mat.specularTexPath); _editTexture(ModeTexture::ambient, mat.ambientTexPath); _editTexture(ModeTexture::reflective, mat.reflectiveTexPath); _editTexture(ModeTexture::emissive, mat.emissiveTexPath); _editTexture(ModeTexture::normal, mat.reflectiveTexPath); _editTexture(ModeTexture::bump, mat.bumpTexPath); _saveEdit(); } bool MaterialEditorScene::_userUpdateBegin(float time) { glClear(GL_COLOR_BUFFER_BIT); ImGui::BeginChild("Material editor", ImVec2(0, 0), true); switch (_mode) { case ModeMaterialEditor::selectMaterial: _selectMaterial(); break; case ModeMaterialEditor::selectSubMaterial: _selectSubMaterial(); break; case ModeMaterialEditor::edit: _editData(); break; } return true; } bool MaterialEditorScene::_userUpdateEnd(float time) { ImGui::EndChild(); ImGui::End(); return true; } }<commit_msg>Crash fix when loading materials<commit_after>#include "MaterialEditorScene.hh" #include <imgui/imgui.h> #include <Utils/OpenGL.hh> #include <Convertor/MaterialConvertor.hpp> #include <Utils/Directory.hpp> #include <Utils/Path.hpp> #include <Utils/FileSystemHelpers.hpp> #include <EditorConfiguration.hpp> #include <glm/glm.hpp> #include <glm/gtc/type_ptr.hpp> namespace AGE { static const char const *_nameTexture[ModeTexture::size] = { "ambient texture", "diffuse texture", "emissive texture", "reflective texture", "specular texture", "normal texture", "bump texture" }; const std::string MaterialEditorScene::Name = "MaterialEditor"; MaterialEditorScene::MaterialEditorScene(AGE::Engine *engine) : AScene(engine), _mode(ModeMaterialEditor::selectMaterial), _indexMaterial(-1) { _resetEdition(); } MaterialEditorScene::~MaterialEditorScene(void) { } bool MaterialEditorScene::_userStart() { return true; } void MaterialEditorScene::_resetEdition() { _editModeName = false; _indexSubMaterial = -1; memset(_bufferName, 0, NAME_LENGTH); for (auto index = 0; index < ModeTexture::size; ++index) { memset(_bufferTexture[index], 0, TEXTURE_LENGTH); } for (auto index = 0; index < ModeTexture::size; ++index) { _editModeTexture[index] = false; } } void MaterialEditorScene::_selectMaterial() { const std::string currentDir = Directory::GetCurrentDirectory(); const std::string absPath = Path::AbsoluteName(currentDir.c_str(), WE::EditorConfiguration::GetCookedDirectory().c_str()); std::vector<std::string> materialGettable; std::vector<std::string> materialFullPath; Directory dir; const bool succeed = dir.open(absPath.c_str()); AGE_ASSERT(succeed && "Impossible to open directory"); for (auto it = dir.recursive_begin(); it != dir.recursive_end(); ++it) { if (Directory::IsFile(*it) && AGE::FileSystemHelpers::GetExtension(*it) == "mage") { materialGettable.push_back(std::string(Path::RelativeName(absPath.c_str(), *it))); materialFullPath.push_back(*it); } } dir.close(); char const **matListBox = new char const *[materialGettable.size()]; for (auto index = 0; index < materialFullPath.size(); ++index) { matListBox[index] = materialGettable[index].c_str(); } ImGui::ListBox("List of material existing", &_indexMaterial, matListBox, materialFullPath.size()); delete[] matListBox; if (_indexMaterial != -1 && ImGui::Button("open a material")) { _resetEdition(); //std::shared_ptr<MaterialDataSet> material_data_set = std::make_shared<MaterialDataSet>(); //std::ifstream ifs(filePath.getFullName(), std::ios::binary); //cereal::PortableBinaryInputArchive ar(ifs); //ar(*material_data_set.get()); //material->name = material_data_set->name; //material->path = _filePath.getFullName(); //getInstance<AssetsManager>()->loadMaterial() std::shared_ptr<MaterialDataSet> material_data_set = std::make_shared<MaterialDataSet>(); std::ifstream ifs(materialFullPath[_indexMaterial], std::ios::binary); cereal::PortableBinaryInputArchive ar(ifs); ar(*material_data_set.get()); _current = *material_data_set; if (_current.name == "") { std::string fileName = std::string(materialGettable[_indexMaterial]); _current.name = fileName.substr(0, fileName.find('.')); } _mode = ModeMaterialEditor::selectSubMaterial; } if (_indexMaterial == -1) { ImGui::Text("Please select one material for edition"); } } void MaterialEditorScene::_editTexture(ModeTexture mode, std::string &current) { if (!_editModeTexture[mode]) { if (current.empty()) ImGui::Text(std::string("No " + std::string(_nameTexture[mode]) + "...").c_str()); else ImGui::Text(current.c_str()); ImGui::SameLine(); if (ImGui::Button("Edit texture")) _editModeTexture[mode] = true; } else { ImGui::InputText(_nameTexture[mode], _bufferTexture[mode], NAME_LENGTH); ImGui::SameLine(); if (ImGui::Button("valid new texture")) { current = std::string(_bufferName); _editModeTexture[mode] = false; } } } void MaterialEditorScene::_editName() { if (!_editModeName) { if (_current.name.empty()) ImGui::Text("No name..."); else ImGui::Text(_current.name.c_str()); ImGui::SameLine(); if (ImGui::Button("Edit name")) _editModeName = true; } else { ImGui::InputText("", _bufferName, NAME_LENGTH); ImGui::SameLine(); if (ImGui::Button("valid new name")) { _current.name = std::string(_bufferName); _editModeName = false; } } } void MaterialEditorScene::_selectSubMaterial() { if (ImGui::Button("precedent")) _mode = ModeMaterialEditor::selectMaterial; ImGui::Separator(); ImGui::Spacing(); _editName(); std::vector<std::string> subMaterials; for (auto index = 0; index < _current.collection.size(); ++index) subMaterials.emplace_back(std::string("sub material: ") + std::to_string(index)); char const **matListBox = new char const *[_current.collection.size()]; for (auto index = 0; index < _current.collection.size(); ++index) matListBox[index] = subMaterials[index].c_str(); ImGui::ListBox("List of sub material", &_indexSubMaterial, matListBox, _current.collection.size()); delete[] matListBox; if (_indexSubMaterial != -1 && ImGui::Button("open a sub material")) _mode = ModeMaterialEditor::edit; if (_indexSubMaterial == -1) ImGui::Text("Please select one sub material for edition"); _saveEdit(); } void MaterialEditorScene::_saveEdit() { if (ImGui::Button("Save Edition")) { const std::string currentDir = Directory::GetCurrentDirectory(); const std::string absPath = Path::AbsoluteName(currentDir.c_str(), WE::EditorConfiguration::GetCookedDirectory().c_str()); std::ofstream file(absPath + _current.name + ".mage"); cereal::PortableBinaryOutputArchive ar(file); ar(_current); } } void MaterialEditorScene::_editData() { if (ImGui::Button("precedent")) _mode = ModeMaterialEditor::selectSubMaterial; MaterialData &mat = _current.collection[_indexSubMaterial]; ImGui::InputFloat3("ambient", glm::value_ptr(mat.ambient)); ImGui::InputFloat3("diffuse", glm::value_ptr(mat.diffuse)); ImGui::InputFloat3("emissive", glm::value_ptr(mat.emissive)); ImGui::InputFloat3("reflective", glm::value_ptr(mat.reflective)); ImGui::InputFloat3("specular", glm::value_ptr(mat.specular)); _editTexture(ModeTexture::diffuse, mat.diffuseTexPath); _editTexture(ModeTexture::specular, mat.specularTexPath); _editTexture(ModeTexture::ambient, mat.ambientTexPath); _editTexture(ModeTexture::reflective, mat.reflectiveTexPath); _editTexture(ModeTexture::emissive, mat.emissiveTexPath); _editTexture(ModeTexture::normal, mat.reflectiveTexPath); _editTexture(ModeTexture::bump, mat.bumpTexPath); _saveEdit(); } bool MaterialEditorScene::_userUpdateBegin(float time) { glClear(GL_COLOR_BUFFER_BIT); ImGui::BeginChild("Material editor", ImVec2(0, 0), true); switch (_mode) { case ModeMaterialEditor::selectMaterial: _selectMaterial(); break; case ModeMaterialEditor::selectSubMaterial: _selectSubMaterial(); break; case ModeMaterialEditor::edit: _editData(); break; } return true; } bool MaterialEditorScene::_userUpdateEnd(float time) { ImGui::EndChild(); ImGui::End(); return true; } }<|endoftext|>
<commit_before>#include "AsyncLogger.h" #include "thread/Thread.h" #include "thread/Mutex.h" #include "thread/Condition.h" #include "thread/CountDownLatch.h" #include "base/Logger.h" #include "base/LogFile.h" NAMESPACE_ZL_BASE_START AsyncLogger::AsyncLogger(int flushInterval/* = 3*/) : isRunning_(false), mutex_(new thread::Mutex), condition_(new thread::Condition(*mutex_)), latch_(new thread::CountDownLatch(1)), thread_(new thread::Thread(std::bind(&AsyncLogger::logThread, this), "AsyncLogger")), flushInterval_(flushInterval), currentBuffer_(new Buffer), remainBuffer_(new Buffer) { //latch_->wait(); } AsyncLogger::~AsyncLogger() { if (isRunning_) { stop(); } thread_->join(); delete mutex_; delete condition_; delete latch_; delete thread_; } void AsyncLogger::start() { latch_->wait(); } void AsyncLogger::stop() { isRunning_ = false; condition_->notify_all(); } void AsyncLogger::output(const char* data, size_t len) { thread::LockGuard<thread::Mutex> lock(*mutex_); if (currentBuffer_->avail() > len) { currentBuffer_->append(data, len); } else { buffers_.push_back(std::move(currentBuffer_)); if (remainBuffer_) { currentBuffer_ = std::move(remainBuffer_); } else { currentBuffer_.reset(new Buffer); } currentBuffer_->append(data, len); condition_->notify_all(); } } void AsyncLogger::logThread() { isRunning_ = true; LogFile logfile(NULL, NULL, false, 3); std::vector<BufferPtr> writeBuffers; latch_->countDown(); while(isRunning_) { //printf("111111111111\n"); { thread::LockGuard<thread::Mutex> lock(*mutex_); if (buffers_.empty()) { condition_->timed_wait(flushInterval_ * 1000); } //if (!isRunning_) //{ // break; //} buffers_.push_back(std::move(currentBuffer_)); if (remainBuffer_) { currentBuffer_ = std::move(remainBuffer_); } else { currentBuffer_.reset(new Buffer); } writeBuffers.swap(buffers_); } assert(!writeBuffers.empty()); for (size_t i = 0; i < writeBuffers.size(); ++i) { logfile.dumpLog(writeBuffers[i]->data(), writeBuffers[i]->size()); } { thread::LockGuard<thread::Mutex> lock(*mutex_); if (!remainBuffer_) { remainBuffer_ = std::move(writeBuffers[0]); remainBuffer_.reset(); } } writeBuffers.clear(); logfile.flush(); } logfile.flush(); } NAMESPACE_ZL_BASE_END <commit_msg>update<commit_after>#include "AsyncLogger.h" #include "thread/Thread.h" #include "thread/Mutex.h" #include "thread/Condition.h" #include "thread/CountDownLatch.h" #include "base/Logger.h" #include "base/LogFile.h" NAMESPACE_ZL_BASE_START AsyncLogger::AsyncLogger(int flushInterval/* = 3*/) : isRunning_(false), mutex_(new thread::Mutex), condition_(new thread::Condition(*mutex_)), latch_(new thread::CountDownLatch(1)), thread_(new thread::Thread(std::bind(&AsyncLogger::logThread, this), "AsyncLogger")), flushInterval_(flushInterval), currentBuffer_(new Buffer), remainBuffer_(new Buffer) { //latch_->wait(); } AsyncLogger::~AsyncLogger() { if (isRunning_) { stop(); } thread_->join(); delete mutex_; delete condition_; delete latch_; delete thread_; } void AsyncLogger::start() { LOG_SET_LOGHANDLER(std::bind(&AsyncLogger::output, &logger, std::placeholders::_1, std::placeholders::_2)); latch_->wait(); } void AsyncLogger::stop() { isRunning_ = false; condition_->notify_all(); } void AsyncLogger::output(const char* data, size_t len) { thread::LockGuard<thread::Mutex> lock(*mutex_); if (currentBuffer_->avail() > len) { currentBuffer_->append(data, len); } else { buffers_.push_back(std::move(currentBuffer_)); if (remainBuffer_) { currentBuffer_ = std::move(remainBuffer_); } else { currentBuffer_.reset(new Buffer); } currentBuffer_->append(data, len); condition_->notify_all(); } } void AsyncLogger::logThread() { isRunning_ = true; LogFile logfile(NULL, NULL, false, 3); std::vector<BufferPtr> writeBuffers; latch_->countDown(); while(isRunning_) { { thread::LockGuard<thread::Mutex> lock(*mutex_); if (buffers_.empty()) { condition_->timed_wait(flushInterval_ * 1000); } //if (!isRunning_) //{ // break; //} buffers_.push_back(std::move(currentBuffer_)); if (remainBuffer_) { currentBuffer_ = std::move(remainBuffer_); } else { currentBuffer_.reset(new Buffer); } writeBuffers.swap(buffers_); } assert(!writeBuffers.empty()); for (size_t i = 0; i < writeBuffers.size(); ++i) { logfile.dumpLog(writeBuffers[i]->data(), writeBuffers[i]->size()); } { thread::LockGuard<thread::Mutex> lock(*mutex_); if (!remainBuffer_) { remainBuffer_ = std::move(writeBuffers[0]); remainBuffer_.reset(); } } writeBuffers.clear(); logfile.flush(); } logfile.flush(); } NAMESPACE_ZL_BASE_END <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2015 The Qt Company Ltd. ** Contact: http://www.qt.io/licensing ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms and ** conditions see http://www.qt.io/terms-conditions. For further information ** use the contact form at http://www.qt.io/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 or version 3 as published by the Free ** Software Foundation and appearing in the file LICENSE.LGPLv21 and ** LICENSE.LGPLv3 included in the packaging of this file. Please review the ** following information to ensure the GNU Lesser General Public License ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, The Qt Company gives you certain additional ** rights. These rights are described in The Qt Company LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "cppeditordocument.h" #include "cppeditorconstants.h" #include "cpphighlighter.h" #include <cpptools/baseeditordocumentparser.h> #include <cpptools/builtineditordocumentprocessor.h> #include <cpptools/cppcodeformatter.h> #include <cpptools/cppcodemodelsettings.h> #include <cpptools/cppmodelmanager.h> #include <cpptools/cppqtstyleindenter.h> #include <cpptools/cpptoolsconstants.h> #include <cpptools/cpptoolsplugin.h> #include <projectexplorer/session.h> #include <coreplugin/editormanager/editormanager.h> #include <utils/mimetypes/mimedatabase.h> #include <utils/qtcassert.h> #include <utils/runextensions.h> #include <QTextDocument> namespace { CppTools::CppModelManager *mm() { return CppTools::CppModelManager::instance(); } } // anonymous namespace namespace CppEditor { namespace Internal { enum { processDocumentIntervalInMs = 150 }; class CppEditorDocumentHandleImpl : public CppTools::CppEditorDocumentHandle { public: CppEditorDocumentHandleImpl(CppEditorDocument *cppEditorDocument) : m_cppEditorDocument(cppEditorDocument) , m_registrationFilePath(cppEditorDocument->filePath().toString()) { mm()->registerCppEditorDocument(this); } ~CppEditorDocumentHandleImpl() { mm()->unregisterCppEditorDocument(m_registrationFilePath); } QString filePath() const override { return m_cppEditorDocument->filePath().toString(); } QByteArray contents() const override { return m_cppEditorDocument->contentsText(); } unsigned revision() const override { return m_cppEditorDocument->contentsRevision(); } CppTools::BaseEditorDocumentProcessor *processor() const override { return m_cppEditorDocument->processor(); } void resetProcessor() { m_cppEditorDocument->resetProcessor(); } private: CppEditor::Internal::CppEditorDocument * const m_cppEditorDocument; // The file path of the editor document can change (e.g. by "Save As..."), so make sure // that un-registration happens with the path the document was registered. const QString m_registrationFilePath; }; CppEditorDocument::CppEditorDocument() : m_fileIsBeingReloaded(false) , m_isObjCEnabled(false) , m_cachedContentsRevision(-1) , m_processorRevision(0) , m_completionAssistProvider(0) { setId(CppEditor::Constants::CPPEDITOR_ID); setSyntaxHighlighter(new CppHighlighter); setIndenter(new CppTools::CppQtStyleIndenter); connect(this, SIGNAL(tabSettingsChanged()), this, SLOT(invalidateFormatterCache())); connect(this, SIGNAL(mimeTypeChanged()), this, SLOT(onMimeTypeChanged())); connect(this, SIGNAL(aboutToReload()), this, SLOT(onAboutToReload())); connect(this, SIGNAL(reloadFinished(bool)), this, SLOT(onReloadFinished())); connect(this, &IDocument::filePathChanged, this, &CppEditorDocument::onFilePathChanged); m_processorTimer.setSingleShot(true); m_processorTimer.setInterval(processDocumentIntervalInMs); connect(&m_processorTimer, SIGNAL(timeout()), this, SLOT(processDocument())); // See also onFilePathChanged() for more initialization } bool CppEditorDocument::isObjCEnabled() const { return m_isObjCEnabled; } TextEditor::CompletionAssistProvider *CppEditorDocument::completionAssistProvider() const { return m_completionAssistProvider; } void CppEditorDocument::recalculateSemanticInfoDetached() { CppTools::BaseEditorDocumentProcessor *p = processor(); QTC_ASSERT(p, return); p->recalculateSemanticInfoDetached(true); } CppTools::SemanticInfo CppEditorDocument::recalculateSemanticInfo() { CppTools::BaseEditorDocumentProcessor *p = processor(); QTC_ASSERT(p, CppTools::SemanticInfo()); return p->recalculateSemanticInfo(); } QByteArray CppEditorDocument::contentsText() const { QMutexLocker locker(&m_cachedContentsLock); const int currentRevision = document()->revision(); if (m_cachedContentsRevision != currentRevision && !m_fileIsBeingReloaded) { m_cachedContentsRevision = currentRevision; m_cachedContents = plainText().toUtf8(); } return m_cachedContents; } void CppEditorDocument::applyFontSettings() { if (TextEditor::SyntaxHighlighter *highlighter = syntaxHighlighter()) { // Clear all additional formats since they may have changed QTextBlock b = document()->firstBlock(); while (b.isValid()) { QList<QTextLayout::FormatRange> noFormats; highlighter->setExtraAdditionalFormats(b, noFormats); b = b.next(); } } TextDocument::applyFontSettings(); // rehighlights and updates additional formats m_processor->semanticRehighlight(); } void CppEditorDocument::invalidateFormatterCache() { CppTools::QtStyleCodeFormatter formatter; formatter.invalidateCache(document()); } void CppEditorDocument::onMimeTypeChanged() { const QString &mt = mimeType(); m_isObjCEnabled = (mt == QLatin1String(CppTools::Constants::OBJECTIVE_C_SOURCE_MIMETYPE) || mt == QLatin1String(CppTools::Constants::OBJECTIVE_CPP_SOURCE_MIMETYPE)); m_completionAssistProvider = mm()->completionAssistProvider(mt); } void CppEditorDocument::onAboutToReload() { QTC_CHECK(!m_fileIsBeingReloaded); m_fileIsBeingReloaded = true; } void CppEditorDocument::onReloadFinished() { QTC_CHECK(m_fileIsBeingReloaded); m_fileIsBeingReloaded = false; } void CppEditorDocument::onFilePathChanged(const Utils::FileName &oldPath, const Utils::FileName &newPath) { Q_UNUSED(oldPath); if (!newPath.isEmpty()) { Utils::MimeDatabase mdb; setMimeType(mdb.mimeTypeForFile(newPath.toFileInfo()).name()); disconnect(this, SIGNAL(contentsChanged()), this, SLOT(scheduleProcessDocument())); connect(this, SIGNAL(contentsChanged()), this, SLOT(scheduleProcessDocument())); // Un-Register/Register in ModelManager m_editorDocumentHandle.reset(); m_editorDocumentHandle.reset(new CppEditorDocumentHandleImpl(this)); resetProcessor(); updatePreprocessorSettings(); m_processorRevision = document()->revision(); processDocument(); } } void CppEditorDocument::scheduleProcessDocument() { m_processorRevision = document()->revision(); m_processorTimer.start(processDocumentIntervalInMs); } void CppEditorDocument::processDocument() { if (processor()->isParserRunning() || m_processorRevision != contentsRevision()) { m_processorTimer.start(); return; } m_processorTimer.stop(); if (m_fileIsBeingReloaded || filePath().isEmpty()) return; processor()->run(); } void CppEditorDocument::resetProcessor() { releaseResources(); processor(); // creates a new processor } void CppEditorDocument::updatePreprocessorSettings() { if (filePath().isEmpty()) return; const QString prefix = QLatin1String(Constants::CPP_PREPROCESSOR_PROJECT_PREFIX); const QString &projectFile = ProjectExplorer::SessionManager::value( prefix + filePath().toString()).toString(); const QString directivesKey = projectFile + QLatin1Char(',') + filePath().toString(); const QByteArray additionalDirectives = ProjectExplorer::SessionManager::value( directivesKey).toString().toUtf8(); setPreprocessorSettings(mm()->projectPartForProjectFile(projectFile), additionalDirectives); } void CppEditorDocument::setPreprocessorSettings(const CppTools::ProjectPart::Ptr &projectPart, const QByteArray &defines) { CppTools::BaseEditorDocumentParser *parser = processor()->parser(); QTC_ASSERT(parser, return); if (parser->projectPart() != projectPart || parser->editorDefines() != defines) { parser->setProjectPart(projectPart); parser->setEditorDefines(defines); emit preprocessorSettingsChanged(!defines.trimmed().isEmpty()); } } unsigned CppEditorDocument::contentsRevision() const { return document()->revision(); } void CppEditorDocument::releaseResources() { if (m_processor) disconnect(m_processor.data(), 0, this, 0); m_processor.reset(); } CppTools::BaseEditorDocumentProcessor *CppEditorDocument::processor() { if (!m_processor) { m_processor.reset(mm()->editorDocumentProcessor(this)); connect(m_processor.data(), &CppTools::BaseEditorDocumentProcessor::codeWarningsUpdated, this, &CppEditorDocument::codeWarningsUpdated); connect(m_processor.data(), &CppTools::BaseEditorDocumentProcessor::ifdefedOutBlocksUpdated, this, &CppEditorDocument::ifdefedOutBlocksUpdated); connect(m_processor.data(), &CppTools::BaseEditorDocumentProcessor::cppDocumentUpdated, this, &CppEditorDocument::cppDocumentUpdated); connect(m_processor.data(), &CppTools::BaseEditorDocumentProcessor::semanticInfoUpdated, this, &CppEditorDocument::semanticInfoUpdated); } return m_processor.data(); } } // namespace Internal } // namespace CppEditor <commit_msg>CppEditor: Fix accessing null pointer...<commit_after>/**************************************************************************** ** ** Copyright (C) 2015 The Qt Company Ltd. ** Contact: http://www.qt.io/licensing ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms and ** conditions see http://www.qt.io/terms-conditions. For further information ** use the contact form at http://www.qt.io/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 or version 3 as published by the Free ** Software Foundation and appearing in the file LICENSE.LGPLv21 and ** LICENSE.LGPLv3 included in the packaging of this file. Please review the ** following information to ensure the GNU Lesser General Public License ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, The Qt Company gives you certain additional ** rights. These rights are described in The Qt Company LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "cppeditordocument.h" #include "cppeditorconstants.h" #include "cpphighlighter.h" #include <cpptools/baseeditordocumentparser.h> #include <cpptools/builtineditordocumentprocessor.h> #include <cpptools/cppcodeformatter.h> #include <cpptools/cppcodemodelsettings.h> #include <cpptools/cppmodelmanager.h> #include <cpptools/cppqtstyleindenter.h> #include <cpptools/cpptoolsconstants.h> #include <cpptools/cpptoolsplugin.h> #include <projectexplorer/session.h> #include <coreplugin/editormanager/editormanager.h> #include <utils/mimetypes/mimedatabase.h> #include <utils/qtcassert.h> #include <utils/runextensions.h> #include <QTextDocument> namespace { CppTools::CppModelManager *mm() { return CppTools::CppModelManager::instance(); } } // anonymous namespace namespace CppEditor { namespace Internal { enum { processDocumentIntervalInMs = 150 }; class CppEditorDocumentHandleImpl : public CppTools::CppEditorDocumentHandle { public: CppEditorDocumentHandleImpl(CppEditorDocument *cppEditorDocument) : m_cppEditorDocument(cppEditorDocument) , m_registrationFilePath(cppEditorDocument->filePath().toString()) { mm()->registerCppEditorDocument(this); } ~CppEditorDocumentHandleImpl() { mm()->unregisterCppEditorDocument(m_registrationFilePath); } QString filePath() const override { return m_cppEditorDocument->filePath().toString(); } QByteArray contents() const override { return m_cppEditorDocument->contentsText(); } unsigned revision() const override { return m_cppEditorDocument->contentsRevision(); } CppTools::BaseEditorDocumentProcessor *processor() const override { return m_cppEditorDocument->processor(); } void resetProcessor() { m_cppEditorDocument->resetProcessor(); } private: CppEditor::Internal::CppEditorDocument * const m_cppEditorDocument; // The file path of the editor document can change (e.g. by "Save As..."), so make sure // that un-registration happens with the path the document was registered. const QString m_registrationFilePath; }; CppEditorDocument::CppEditorDocument() : m_fileIsBeingReloaded(false) , m_isObjCEnabled(false) , m_cachedContentsRevision(-1) , m_processorRevision(0) , m_completionAssistProvider(0) { setId(CppEditor::Constants::CPPEDITOR_ID); setSyntaxHighlighter(new CppHighlighter); setIndenter(new CppTools::CppQtStyleIndenter); connect(this, SIGNAL(tabSettingsChanged()), this, SLOT(invalidateFormatterCache())); connect(this, SIGNAL(mimeTypeChanged()), this, SLOT(onMimeTypeChanged())); connect(this, SIGNAL(aboutToReload()), this, SLOT(onAboutToReload())); connect(this, SIGNAL(reloadFinished(bool)), this, SLOT(onReloadFinished())); connect(this, &IDocument::filePathChanged, this, &CppEditorDocument::onFilePathChanged); m_processorTimer.setSingleShot(true); m_processorTimer.setInterval(processDocumentIntervalInMs); connect(&m_processorTimer, SIGNAL(timeout()), this, SLOT(processDocument())); // See also onFilePathChanged() for more initialization } bool CppEditorDocument::isObjCEnabled() const { return m_isObjCEnabled; } TextEditor::CompletionAssistProvider *CppEditorDocument::completionAssistProvider() const { return m_completionAssistProvider; } void CppEditorDocument::recalculateSemanticInfoDetached() { CppTools::BaseEditorDocumentProcessor *p = processor(); QTC_ASSERT(p, return); p->recalculateSemanticInfoDetached(true); } CppTools::SemanticInfo CppEditorDocument::recalculateSemanticInfo() { CppTools::BaseEditorDocumentProcessor *p = processor(); QTC_ASSERT(p, CppTools::SemanticInfo()); return p->recalculateSemanticInfo(); } QByteArray CppEditorDocument::contentsText() const { QMutexLocker locker(&m_cachedContentsLock); const int currentRevision = document()->revision(); if (m_cachedContentsRevision != currentRevision && !m_fileIsBeingReloaded) { m_cachedContentsRevision = currentRevision; m_cachedContents = plainText().toUtf8(); } return m_cachedContents; } void CppEditorDocument::applyFontSettings() { if (TextEditor::SyntaxHighlighter *highlighter = syntaxHighlighter()) { // Clear all additional formats since they may have changed QTextBlock b = document()->firstBlock(); while (b.isValid()) { QList<QTextLayout::FormatRange> noFormats; highlighter->setExtraAdditionalFormats(b, noFormats); b = b.next(); } } TextDocument::applyFontSettings(); // rehighlights and updates additional formats if (m_processor) m_processor->semanticRehighlight(); } void CppEditorDocument::invalidateFormatterCache() { CppTools::QtStyleCodeFormatter formatter; formatter.invalidateCache(document()); } void CppEditorDocument::onMimeTypeChanged() { const QString &mt = mimeType(); m_isObjCEnabled = (mt == QLatin1String(CppTools::Constants::OBJECTIVE_C_SOURCE_MIMETYPE) || mt == QLatin1String(CppTools::Constants::OBJECTIVE_CPP_SOURCE_MIMETYPE)); m_completionAssistProvider = mm()->completionAssistProvider(mt); } void CppEditorDocument::onAboutToReload() { QTC_CHECK(!m_fileIsBeingReloaded); m_fileIsBeingReloaded = true; } void CppEditorDocument::onReloadFinished() { QTC_CHECK(m_fileIsBeingReloaded); m_fileIsBeingReloaded = false; } void CppEditorDocument::onFilePathChanged(const Utils::FileName &oldPath, const Utils::FileName &newPath) { Q_UNUSED(oldPath); if (!newPath.isEmpty()) { Utils::MimeDatabase mdb; setMimeType(mdb.mimeTypeForFile(newPath.toFileInfo()).name()); disconnect(this, SIGNAL(contentsChanged()), this, SLOT(scheduleProcessDocument())); connect(this, SIGNAL(contentsChanged()), this, SLOT(scheduleProcessDocument())); // Un-Register/Register in ModelManager m_editorDocumentHandle.reset(); m_editorDocumentHandle.reset(new CppEditorDocumentHandleImpl(this)); resetProcessor(); updatePreprocessorSettings(); m_processorRevision = document()->revision(); processDocument(); } } void CppEditorDocument::scheduleProcessDocument() { m_processorRevision = document()->revision(); m_processorTimer.start(processDocumentIntervalInMs); } void CppEditorDocument::processDocument() { if (processor()->isParserRunning() || m_processorRevision != contentsRevision()) { m_processorTimer.start(); return; } m_processorTimer.stop(); if (m_fileIsBeingReloaded || filePath().isEmpty()) return; processor()->run(); } void CppEditorDocument::resetProcessor() { releaseResources(); processor(); // creates a new processor } void CppEditorDocument::updatePreprocessorSettings() { if (filePath().isEmpty()) return; const QString prefix = QLatin1String(Constants::CPP_PREPROCESSOR_PROJECT_PREFIX); const QString &projectFile = ProjectExplorer::SessionManager::value( prefix + filePath().toString()).toString(); const QString directivesKey = projectFile + QLatin1Char(',') + filePath().toString(); const QByteArray additionalDirectives = ProjectExplorer::SessionManager::value( directivesKey).toString().toUtf8(); setPreprocessorSettings(mm()->projectPartForProjectFile(projectFile), additionalDirectives); } void CppEditorDocument::setPreprocessorSettings(const CppTools::ProjectPart::Ptr &projectPart, const QByteArray &defines) { CppTools::BaseEditorDocumentParser *parser = processor()->parser(); QTC_ASSERT(parser, return); if (parser->projectPart() != projectPart || parser->editorDefines() != defines) { parser->setProjectPart(projectPart); parser->setEditorDefines(defines); emit preprocessorSettingsChanged(!defines.trimmed().isEmpty()); } } unsigned CppEditorDocument::contentsRevision() const { return document()->revision(); } void CppEditorDocument::releaseResources() { if (m_processor) disconnect(m_processor.data(), 0, this, 0); m_processor.reset(); } CppTools::BaseEditorDocumentProcessor *CppEditorDocument::processor() { if (!m_processor) { m_processor.reset(mm()->editorDocumentProcessor(this)); connect(m_processor.data(), &CppTools::BaseEditorDocumentProcessor::codeWarningsUpdated, this, &CppEditorDocument::codeWarningsUpdated); connect(m_processor.data(), &CppTools::BaseEditorDocumentProcessor::ifdefedOutBlocksUpdated, this, &CppEditorDocument::ifdefedOutBlocksUpdated); connect(m_processor.data(), &CppTools::BaseEditorDocumentProcessor::cppDocumentUpdated, this, &CppEditorDocument::cppDocumentUpdated); connect(m_processor.data(), &CppTools::BaseEditorDocumentProcessor::semanticInfoUpdated, this, &CppEditorDocument::semanticInfoUpdated); } return m_processor.data(); } } // namespace Internal } // namespace CppEditor <|endoftext|>
<commit_before>/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** Commercial Usage ** ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Commercial License Agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Nokia. ** ** GNU Lesser General Public License Usage ** ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at http://qt.nokia.com/contact. ** **************************************************************************/ #include "qmakestep.h" #include "qt4project.h" #include "qt4projectmanagerconstants.h" #include "qt4projectmanager.h" #include "makestep.h" #include "qtversionmanager.h" #include <coreplugin/icore.h> #include <utils/qtcassert.h> #include <QFileDialog> #include <QDir> #include <QFile> #include <QCoreApplication> using namespace Qt4ProjectManager; using namespace Qt4ProjectManager::Internal; using namespace ProjectExplorer; QMakeStep::QMakeStep(Qt4Project *project) : AbstractProcessStep(project), m_pro(project), m_forced(false) { } QMakeStep::~QMakeStep() { } QStringList QMakeStep::arguments(const QString &buildConfiguration) { QStringList additonalArguments = value(buildConfiguration, "qmakeArgs").toStringList(); ProjectExplorer::BuildConfiguration *bc = m_pro->buildConfiguration(buildConfiguration); QStringList arguments; arguments << project()->file()->fileName(); arguments << "-r"; if (!arguments.contains("-spec")) arguments << "-spec" << "default"; #ifdef Q_OS_WIN ToolChain::ToolChainType type = m_pro->toolChainType(bc); if (type == ToolChain::GCC_MAEMO) arguments << QLatin1String("-unix"); #endif if (bc->value("buildConfiguration").isValid()) { QStringList configarguments; QtVersion::QmakeBuildConfig defaultBuildConfiguration = m_pro->qtVersion(bc)->defaultBuildConfig(); QtVersion::QmakeBuildConfig projectBuildConfiguration = QtVersion::QmakeBuildConfig(bc->value("buildConfiguration").toInt()); if ((defaultBuildConfiguration & QtVersion::BuildAll) && !(projectBuildConfiguration & QtVersion::BuildAll)) configarguments << "CONFIG-=debug_and_release"; if (!(defaultBuildConfiguration & QtVersion::BuildAll) && (projectBuildConfiguration & QtVersion::BuildAll)) configarguments << "CONFIG+=debug_and_release"; if ((defaultBuildConfiguration & QtVersion::DebugBuild) && !(projectBuildConfiguration & QtVersion::DebugBuild)) configarguments << "CONFIG+=release"; if (!(defaultBuildConfiguration & QtVersion::DebugBuild) && (projectBuildConfiguration & QtVersion::DebugBuild)) configarguments << "CONFIG+=debug"; if (!configarguments.isEmpty()) arguments << configarguments; } else { qWarning()<< "The project should always have a qmake build configuration set"; } if (!additonalArguments.isEmpty()) arguments << additonalArguments; return arguments; } bool QMakeStep::init(const QString &name) { m_buildConfiguration = name; ProjectExplorer::BuildConfiguration *bc = m_pro->buildConfiguration(name); const QtVersion *qtVersion = m_pro->qtVersion(bc); if (!qtVersion->isValid()) { #if defined(Q_WS_MAC) emit addToOutputWindow(tr("\n<font color=\"#ff0000\"><b>No valid Qt version set. Set one in Preferences </b></font>\n")); #else emit addToOutputWindow(tr("\n<font color=\"#ff0000\"><b>No valid Qt version set. Set one in Tools/Options </b></font>\n")); #endif return false; } QStringList args = arguments(name); QString workingDirectory = m_pro->buildDirectory(bc); QString program = qtVersion->qmakeCommand(); // Check wheter we need to run qmake bool needToRunQMake = true; if (QDir(workingDirectory).exists(QLatin1String("Makefile"))) { QString qmakePath = QtVersionManager::findQMakeBinaryFromMakefile(workingDirectory); if (qtVersion->qmakeCommand() == qmakePath) { needToRunQMake = !m_pro->compareBuildConfigurationToImportFrom(bc, workingDirectory); } } if (m_forced) { m_forced = false; needToRunQMake = true; } setEnabled(name, needToRunQMake); setWorkingDirectory(name, workingDirectory); setCommand(name, program); setArguments(name, args); setEnvironment(name, m_pro->environment(bc)); return AbstractProcessStep::init(name); } void QMakeStep::run(QFutureInterface<bool> &fi) { if (qobject_cast<Qt4Project *>(project())->rootProjectNode()->projectType() == ScriptTemplate) { fi.reportResult(true); return; } if (!enabled(m_buildConfiguration)) { emit addToOutputWindow(tr("<font color=\"#0000ff\">Configuration unchanged, skipping QMake step.</font>")); fi.reportResult(true); return; } AbstractProcessStep::run(fi); } QString QMakeStep::name() { return Constants::QMAKESTEP; } QString QMakeStep::displayName() { return "QMake"; } void QMakeStep::setForced(bool b) { m_forced = b; } bool QMakeStep::forced() { return m_forced; } ProjectExplorer::BuildStepConfigWidget *QMakeStep::createConfigWidget() { return new QMakeStepConfigWidget(this); } bool QMakeStep::immutable() const { return false; } void QMakeStep::processStartupFailed() { m_forced = true; AbstractProcessStep::processStartupFailed(); } bool QMakeStep::processFinished(int exitCode, QProcess::ExitStatus status) { bool result = AbstractProcessStep::processFinished(exitCode, status); if (!result) m_forced = true; return result; } void QMakeStep::setQMakeArguments(const QString &buildConfiguration, const QStringList &arguments) { setValue(buildConfiguration, "qmakeArgs", arguments); emit changed(); } QMakeStepConfigWidget::QMakeStepConfigWidget(QMakeStep *step) : BuildStepConfigWidget(), m_step(step) { m_ui.setupUi(this); connect(m_ui.qmakeAdditonalArgumentsLineEdit, SIGNAL(textEdited(const QString&)), this, SLOT(qmakeArgumentsLineEditTextEdited())); connect(m_ui.buildConfigurationComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(buildConfigurationChanged())); connect(step, SIGNAL(changed()), this, SLOT(update())); connect(step->project(), SIGNAL(qtVersionChanged(ProjectExplorer::BuildConfiguration *)), this, SLOT(qtVersionChanged(ProjectExplorer::BuildConfiguration *))); } QString QMakeStepConfigWidget::summaryText() const { return m_summaryText; } void QMakeStepConfigWidget::qtVersionChanged(ProjectExplorer::BuildConfiguration *bc) { if (bc && bc->name() == m_buildConfiguration) { updateTitleLabel(); updateEffectiveQMakeCall(); } } void QMakeStepConfigWidget::updateTitleLabel() { Qt4Project *qt4project = qobject_cast<Qt4Project *>(m_step->project()); const QtVersion *qtVersion = qt4project->qtVersion(qt4project->buildConfiguration(m_buildConfiguration)); if (!qtVersion) { m_summaryText = tr("<b>QMake:</b> No Qt version set. QMake can not be run."); emit updateSummary(); return; } QStringList args = m_step->arguments(m_buildConfiguration); // We don't want the full path to the .pro file int index = args.indexOf(m_step->project()->file()->fileName()); if (index != -1) args[index] = QFileInfo(m_step->project()->file()->fileName()).fileName(); // And we only use the .pro filename not the full path QString program = QFileInfo(qtVersion->qmakeCommand()).fileName(); m_summaryText = tr("<b>QMake:</b> %1 %2").arg(program, args.join(QString(QLatin1Char(' ')))); emit updateSummary(); } void QMakeStepConfigWidget::qmakeArgumentsLineEditTextEdited() { Q_ASSERT(!m_buildConfiguration.isNull()); m_step->setValue(m_buildConfiguration, "qmakeArgs", ProjectExplorer::Environment::parseCombinedArgString(m_ui.qmakeAdditonalArgumentsLineEdit->text())); static_cast<Qt4Project *>(m_step->project())->invalidateCachedTargetInformation(); updateTitleLabel(); updateEffectiveQMakeCall(); } void QMakeStepConfigWidget::buildConfigurationChanged() { ProjectExplorer::BuildConfiguration *bc = m_step->project()->buildConfiguration(m_buildConfiguration); QtVersion::QmakeBuildConfig buildConfiguration = QtVersion::QmakeBuildConfig(bc->value("buildConfiguration").toInt()); if (m_ui.buildConfigurationComboBox->currentIndex() == 0) { // debug buildConfiguration = QtVersion::QmakeBuildConfig(buildConfiguration | QtVersion::DebugBuild); } else { buildConfiguration = QtVersion::QmakeBuildConfig(buildConfiguration & ~QtVersion::DebugBuild); } bc->setValue("buildConfiguration", int(buildConfiguration)); static_cast<Qt4Project *>(m_step->project())->invalidateCachedTargetInformation(); updateTitleLabel(); updateEffectiveQMakeCall(); // TODO if exact parsing is the default, we need to update the code model // and all the Qt4ProFileNodes //static_cast<Qt4Project *>(m_step->project())->update(); } QString QMakeStepConfigWidget::displayName() const { return m_step->displayName(); } void QMakeStepConfigWidget::update() { init(m_buildConfiguration); } void QMakeStepConfigWidget::init(const QString &buildConfiguration) { m_buildConfiguration = buildConfiguration; QString qmakeArgs = ProjectExplorer::Environment::joinArgumentList(m_step->value(buildConfiguration, "qmakeArgs").toStringList()); m_ui.qmakeAdditonalArgumentsLineEdit->setText(qmakeArgs); ProjectExplorer::BuildConfiguration *bc = m_step->project()->buildConfiguration(buildConfiguration); bool debug = QtVersion::QmakeBuildConfig(bc->value("buildConfiguration").toInt()) & QtVersion::DebugBuild; m_ui.buildConfigurationComboBox->setCurrentIndex(debug? 0 : 1); updateTitleLabel(); updateEffectiveQMakeCall(); } void QMakeStepConfigWidget::updateEffectiveQMakeCall() { Qt4Project *qt4project = qobject_cast<Qt4Project *>(m_step->project()); const QtVersion *qtVersion = qt4project->qtVersion(qt4project->buildConfiguration(m_buildConfiguration)); if (qtVersion) { QString program = QFileInfo(qtVersion->qmakeCommand()).fileName(); m_ui.qmakeArgumentsEdit->setPlainText(program + QLatin1Char(' ') + ProjectExplorer::Environment::joinArgumentList(m_step->arguments(m_buildConfiguration))); } else { m_ui.qmakeArgumentsEdit->setPlainText(tr("No valid Qt version set.")); } } //// // QMakeStepFactory //// QMakeStepFactory::QMakeStepFactory() { } QMakeStepFactory::~QMakeStepFactory() { } bool QMakeStepFactory::canCreate(const QString & name) const { return (name == Constants::QMAKESTEP); } ProjectExplorer::BuildStep * QMakeStepFactory::create(ProjectExplorer::Project * pro, const QString & name) const { Q_UNUSED(name) return new QMakeStep(static_cast<Qt4Project *>(pro)); } QStringList QMakeStepFactory::canCreateForProject(ProjectExplorer::Project *pro) const { Qt4Project *project = qobject_cast<Qt4Project *>(pro); if (project && !project->qmakeStep()) return QStringList() << Constants::QMAKESTEP; return QStringList(); } QString QMakeStepFactory::displayNameForName(const QString &name) const { Q_UNUSED(name); return tr("QMake"); } <commit_msg>Fixed the check for whether there already is a -spec parameter<commit_after>/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** Commercial Usage ** ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Commercial License Agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Nokia. ** ** GNU Lesser General Public License Usage ** ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at http://qt.nokia.com/contact. ** **************************************************************************/ #include "qmakestep.h" #include "qt4project.h" #include "qt4projectmanagerconstants.h" #include "qt4projectmanager.h" #include "makestep.h" #include "qtversionmanager.h" #include <coreplugin/icore.h> #include <utils/qtcassert.h> #include <QFileDialog> #include <QDir> #include <QFile> #include <QCoreApplication> using namespace Qt4ProjectManager; using namespace Qt4ProjectManager::Internal; using namespace ProjectExplorer; QMakeStep::QMakeStep(Qt4Project *project) : AbstractProcessStep(project), m_pro(project), m_forced(false) { } QMakeStep::~QMakeStep() { } QStringList QMakeStep::arguments(const QString &buildConfiguration) { QStringList additonalArguments = value(buildConfiguration, "qmakeArgs").toStringList(); ProjectExplorer::BuildConfiguration *bc = m_pro->buildConfiguration(buildConfiguration); QStringList arguments; arguments << project()->file()->fileName(); arguments << "-r"; if (!additonalArguments.contains("-spec")) arguments << "-spec" << "default"; #ifdef Q_OS_WIN ToolChain::ToolChainType type = m_pro->toolChainType(bc); if (type == ToolChain::GCC_MAEMO) arguments << QLatin1String("-unix"); #endif if (bc->value("buildConfiguration").isValid()) { QStringList configarguments; QtVersion::QmakeBuildConfig defaultBuildConfiguration = m_pro->qtVersion(bc)->defaultBuildConfig(); QtVersion::QmakeBuildConfig projectBuildConfiguration = QtVersion::QmakeBuildConfig(bc->value("buildConfiguration").toInt()); if ((defaultBuildConfiguration & QtVersion::BuildAll) && !(projectBuildConfiguration & QtVersion::BuildAll)) configarguments << "CONFIG-=debug_and_release"; if (!(defaultBuildConfiguration & QtVersion::BuildAll) && (projectBuildConfiguration & QtVersion::BuildAll)) configarguments << "CONFIG+=debug_and_release"; if ((defaultBuildConfiguration & QtVersion::DebugBuild) && !(projectBuildConfiguration & QtVersion::DebugBuild)) configarguments << "CONFIG+=release"; if (!(defaultBuildConfiguration & QtVersion::DebugBuild) && (projectBuildConfiguration & QtVersion::DebugBuild)) configarguments << "CONFIG+=debug"; if (!configarguments.isEmpty()) arguments << configarguments; } else { qWarning()<< "The project should always have a qmake build configuration set"; } if (!additonalArguments.isEmpty()) arguments << additonalArguments; return arguments; } bool QMakeStep::init(const QString &name) { m_buildConfiguration = name; ProjectExplorer::BuildConfiguration *bc = m_pro->buildConfiguration(name); const QtVersion *qtVersion = m_pro->qtVersion(bc); if (!qtVersion->isValid()) { #if defined(Q_WS_MAC) emit addToOutputWindow(tr("\n<font color=\"#ff0000\"><b>No valid Qt version set. Set one in Preferences </b></font>\n")); #else emit addToOutputWindow(tr("\n<font color=\"#ff0000\"><b>No valid Qt version set. Set one in Tools/Options </b></font>\n")); #endif return false; } QStringList args = arguments(name); QString workingDirectory = m_pro->buildDirectory(bc); QString program = qtVersion->qmakeCommand(); // Check wheter we need to run qmake bool needToRunQMake = true; if (QDir(workingDirectory).exists(QLatin1String("Makefile"))) { QString qmakePath = QtVersionManager::findQMakeBinaryFromMakefile(workingDirectory); if (qtVersion->qmakeCommand() == qmakePath) { needToRunQMake = !m_pro->compareBuildConfigurationToImportFrom(bc, workingDirectory); } } if (m_forced) { m_forced = false; needToRunQMake = true; } setEnabled(name, needToRunQMake); setWorkingDirectory(name, workingDirectory); setCommand(name, program); setArguments(name, args); setEnvironment(name, m_pro->environment(bc)); return AbstractProcessStep::init(name); } void QMakeStep::run(QFutureInterface<bool> &fi) { if (qobject_cast<Qt4Project *>(project())->rootProjectNode()->projectType() == ScriptTemplate) { fi.reportResult(true); return; } if (!enabled(m_buildConfiguration)) { emit addToOutputWindow(tr("<font color=\"#0000ff\">Configuration unchanged, skipping QMake step.</font>")); fi.reportResult(true); return; } AbstractProcessStep::run(fi); } QString QMakeStep::name() { return Constants::QMAKESTEP; } QString QMakeStep::displayName() { return "QMake"; } void QMakeStep::setForced(bool b) { m_forced = b; } bool QMakeStep::forced() { return m_forced; } ProjectExplorer::BuildStepConfigWidget *QMakeStep::createConfigWidget() { return new QMakeStepConfigWidget(this); } bool QMakeStep::immutable() const { return false; } void QMakeStep::processStartupFailed() { m_forced = true; AbstractProcessStep::processStartupFailed(); } bool QMakeStep::processFinished(int exitCode, QProcess::ExitStatus status) { bool result = AbstractProcessStep::processFinished(exitCode, status); if (!result) m_forced = true; return result; } void QMakeStep::setQMakeArguments(const QString &buildConfiguration, const QStringList &arguments) { setValue(buildConfiguration, "qmakeArgs", arguments); emit changed(); } QMakeStepConfigWidget::QMakeStepConfigWidget(QMakeStep *step) : BuildStepConfigWidget(), m_step(step) { m_ui.setupUi(this); connect(m_ui.qmakeAdditonalArgumentsLineEdit, SIGNAL(textEdited(const QString&)), this, SLOT(qmakeArgumentsLineEditTextEdited())); connect(m_ui.buildConfigurationComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(buildConfigurationChanged())); connect(step, SIGNAL(changed()), this, SLOT(update())); connect(step->project(), SIGNAL(qtVersionChanged(ProjectExplorer::BuildConfiguration *)), this, SLOT(qtVersionChanged(ProjectExplorer::BuildConfiguration *))); } QString QMakeStepConfigWidget::summaryText() const { return m_summaryText; } void QMakeStepConfigWidget::qtVersionChanged(ProjectExplorer::BuildConfiguration *bc) { if (bc && bc->name() == m_buildConfiguration) { updateTitleLabel(); updateEffectiveQMakeCall(); } } void QMakeStepConfigWidget::updateTitleLabel() { Qt4Project *qt4project = qobject_cast<Qt4Project *>(m_step->project()); const QtVersion *qtVersion = qt4project->qtVersion(qt4project->buildConfiguration(m_buildConfiguration)); if (!qtVersion) { m_summaryText = tr("<b>QMake:</b> No Qt version set. QMake can not be run."); emit updateSummary(); return; } QStringList args = m_step->arguments(m_buildConfiguration); // We don't want the full path to the .pro file int index = args.indexOf(m_step->project()->file()->fileName()); if (index != -1) args[index] = QFileInfo(m_step->project()->file()->fileName()).fileName(); // And we only use the .pro filename not the full path QString program = QFileInfo(qtVersion->qmakeCommand()).fileName(); m_summaryText = tr("<b>QMake:</b> %1 %2").arg(program, args.join(QString(QLatin1Char(' ')))); emit updateSummary(); } void QMakeStepConfigWidget::qmakeArgumentsLineEditTextEdited() { Q_ASSERT(!m_buildConfiguration.isNull()); m_step->setValue(m_buildConfiguration, "qmakeArgs", ProjectExplorer::Environment::parseCombinedArgString(m_ui.qmakeAdditonalArgumentsLineEdit->text())); static_cast<Qt4Project *>(m_step->project())->invalidateCachedTargetInformation(); updateTitleLabel(); updateEffectiveQMakeCall(); } void QMakeStepConfigWidget::buildConfigurationChanged() { ProjectExplorer::BuildConfiguration *bc = m_step->project()->buildConfiguration(m_buildConfiguration); QtVersion::QmakeBuildConfig buildConfiguration = QtVersion::QmakeBuildConfig(bc->value("buildConfiguration").toInt()); if (m_ui.buildConfigurationComboBox->currentIndex() == 0) { // debug buildConfiguration = QtVersion::QmakeBuildConfig(buildConfiguration | QtVersion::DebugBuild); } else { buildConfiguration = QtVersion::QmakeBuildConfig(buildConfiguration & ~QtVersion::DebugBuild); } bc->setValue("buildConfiguration", int(buildConfiguration)); static_cast<Qt4Project *>(m_step->project())->invalidateCachedTargetInformation(); updateTitleLabel(); updateEffectiveQMakeCall(); // TODO if exact parsing is the default, we need to update the code model // and all the Qt4ProFileNodes //static_cast<Qt4Project *>(m_step->project())->update(); } QString QMakeStepConfigWidget::displayName() const { return m_step->displayName(); } void QMakeStepConfigWidget::update() { init(m_buildConfiguration); } void QMakeStepConfigWidget::init(const QString &buildConfiguration) { m_buildConfiguration = buildConfiguration; QString qmakeArgs = ProjectExplorer::Environment::joinArgumentList(m_step->value(buildConfiguration, "qmakeArgs").toStringList()); m_ui.qmakeAdditonalArgumentsLineEdit->setText(qmakeArgs); ProjectExplorer::BuildConfiguration *bc = m_step->project()->buildConfiguration(buildConfiguration); bool debug = QtVersion::QmakeBuildConfig(bc->value("buildConfiguration").toInt()) & QtVersion::DebugBuild; m_ui.buildConfigurationComboBox->setCurrentIndex(debug? 0 : 1); updateTitleLabel(); updateEffectiveQMakeCall(); } void QMakeStepConfigWidget::updateEffectiveQMakeCall() { Qt4Project *qt4project = qobject_cast<Qt4Project *>(m_step->project()); const QtVersion *qtVersion = qt4project->qtVersion(qt4project->buildConfiguration(m_buildConfiguration)); if (qtVersion) { QString program = QFileInfo(qtVersion->qmakeCommand()).fileName(); m_ui.qmakeArgumentsEdit->setPlainText(program + QLatin1Char(' ') + ProjectExplorer::Environment::joinArgumentList(m_step->arguments(m_buildConfiguration))); } else { m_ui.qmakeArgumentsEdit->setPlainText(tr("No valid Qt version set.")); } } //// // QMakeStepFactory //// QMakeStepFactory::QMakeStepFactory() { } QMakeStepFactory::~QMakeStepFactory() { } bool QMakeStepFactory::canCreate(const QString & name) const { return (name == Constants::QMAKESTEP); } ProjectExplorer::BuildStep * QMakeStepFactory::create(ProjectExplorer::Project * pro, const QString & name) const { Q_UNUSED(name) return new QMakeStep(static_cast<Qt4Project *>(pro)); } QStringList QMakeStepFactory::canCreateForProject(ProjectExplorer::Project *pro) const { Qt4Project *project = qobject_cast<Qt4Project *>(pro); if (project && !project->qmakeStep()) return QStringList() << Constants::QMAKESTEP; return QStringList(); } QString QMakeStepFactory::displayNameForName(const QString &name) const { Q_UNUSED(name); return tr("QMake"); } <|endoftext|>
<commit_before>/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation (info@qt.nokia.com) ** ** ** GNU Lesser General Public License Usage ** ** This file may be used under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation and ** appearing in the file LICENSE.LGPL included in the packaging of this file. ** Please review the following information to ensure the GNU Lesser General ** Public License version 2.1 requirements will be met: ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** Other Usage ** ** Alternatively, this file may be used in accordance with the terms and ** conditions contained in a signed written agreement between you and Nokia. ** ** If you have questions regarding the use of this file, please contact ** Nokia at info@qt.nokia.com. ** **************************************************************************/ #include "updateinfoplugin.h" #include "updateinfobutton.h" #include <coreplugin/actionmanager/actionmanager.h> #include <coreplugin/actionmanager/actioncontainer.h> #include <coreplugin/coreconstants.h> #include <coreplugin/icore.h> #include <coreplugin/modemanager.h> #include <coreplugin/progressmanager/progressmanager.h> #include <coreplugin/progressmanager/futureprogress.h> #include <qtconcurrentrun.h> #include <QtCore/QtPlugin> #include <QtCore/QProcess> #include <QtCore/QTimer> #include <QtCore/QTimerEvent> #include <QtCore/QDebug> #include <QtCore/QFile> #include <QtCore/QThread> #include <QtCore/QCoreApplication> #include <QtCore/QProcess> #include <QtXml/QDomDocument> #include <QtGui/QMessageBox> #include <QtGui/QMenu> #include <QtCore/QFutureWatcher> namespace { static const quint32 OneMinute = 60000; } namespace UpdateInfo { namespace Internal { class UpdateInfoPluginPrivate { public: UpdateInfoPluginPrivate() : startUpdaterAction(0), currentTimerId(0), progressUpdateInfoButton(0), checkUpdateInfoWatcher(0) {} ~UpdateInfoPluginPrivate() { } QAction *startUpdaterAction; QString updaterProgram; QString updaterCheckOnlyArgument; QString updaterRunUiArgument; int currentTimerId; QFuture<QDomDocument> lastCheckUpdateInfoTask; QPointer<Core::FutureProgress> updateInfoProgress; UpdateInfoButton *progressUpdateInfoButton; QFutureWatcher<QDomDocument> *checkUpdateInfoWatcher; }; UpdateInfoPlugin::UpdateInfoPlugin() : d(new UpdateInfoPluginPrivate) { } UpdateInfoPlugin::~UpdateInfoPlugin() { delete d; } void UpdateInfoPlugin::startCheckTimer(uint milliseconds) { if (d->currentTimerId != 0) { stopCurrentCheckTimer(); } d->currentTimerId = startTimer(milliseconds); } void UpdateInfoPlugin::stopCurrentCheckTimer() { killTimer(d->currentTimerId); } /*! Initializes the plugin. Returns true on success. Plugins want to register objects with the plugin manager here. \a errorMessage can be used to pass an error message to the plugin system, if there was any. */ bool UpdateInfoPlugin::initialize(const QStringList & /* arguments */, QString * /* errorMessage */) { d->checkUpdateInfoWatcher = new QFutureWatcher<QDomDocument>(this); connect(d->checkUpdateInfoWatcher, SIGNAL(finished()), this, SLOT(reactOnUpdaterOutput())); QSettings *settings = Core::ICore::instance()->settings(); d->updaterProgram = settings->value(QLatin1String("Updater/Application")).toString(); d->updaterCheckOnlyArgument = settings->value(QLatin1String("Updater/CheckOnlyArgument")).toString(); d->updaterRunUiArgument = settings->value(QLatin1String("Updater/RunUiArgument")).toString(); Core::ICore* const core = Core::ICore::instance(); Core::ActionManager* const actionManager = core->actionManager(); Core::ActionContainer* const helpActionContainer = actionManager->actionContainer(Core::Constants::M_HELP); helpActionContainer->menu()->addAction(tr("Start Updater"), this, SLOT(startUpdaterUiApplication())); //wait some time before we want to have the first check if (!d->updaterProgram.isEmpty() && QFile::exists(d->updaterProgram)) { startCheckTimer(OneMinute / 10); } return true; } QDomDocument UpdateInfoPlugin::checkForUpdates() { if (QThread::currentThread() == QCoreApplication::instance()->thread()) { qWarning() << Q_FUNC_INFO << " Was not designed to run in main/gui thread -> it is using updaterProcess.waitForFinished()"; } //starting QProcess updaterProcess; updaterProcess.start(d->updaterProgram, QStringList() << d->updaterCheckOnlyArgument); updaterProcess.waitForFinished(); //process return value if (updaterProcess.exitStatus() == QProcess::CrashExit) { qWarning() << "Get update info application crashed."; //return; //maybe there is some output } QString updaterOutput = updaterProcess.readAllStandardOutput(); QDomDocument updatesDomDocument; updatesDomDocument.setContent(updaterOutput); return updatesDomDocument; } void UpdateInfoPlugin::reactOnUpdaterOutput() { QDomDocument updatesDomDocument = d->checkUpdateInfoWatcher->result(); if (updatesDomDocument.isNull() || !updatesDomDocument.firstChildElement().hasChildNodes()) { // no updates are available startCheckTimer(60 * OneMinute); } else { //added the current almost finished task to the progressmanager d->updateInfoProgress = Core::ICore::instance()->progressManager()->addTask( d->lastCheckUpdateInfoTask, tr("Update"), QLatin1String("Update.GetInfo"), Core::ProgressManager::KeepOnFinish); d->updateInfoProgress->setKeepOnFinish(Core::FutureProgress::KeepOnFinish); d->progressUpdateInfoButton = new UpdateInfoButton(); //the old widget is deleted inside this function //and the current widget becomes a child of updateInfoProgress d->updateInfoProgress->setWidget(d->progressUpdateInfoButton); //d->progressUpdateInfoButton->setText(tr("Update")); //we have this information over the progressbar connect(d->progressUpdateInfoButton, SIGNAL(released()), this, SLOT(startUpdaterUiApplication())); } } void UpdateInfoPlugin::startUpdaterUiApplication() { QProcess::startDetached(d->updaterProgram, QStringList() << d->updaterRunUiArgument); if (!d->updateInfoProgress.isNull()) { d->updateInfoProgress->setKeepOnFinish(Core::FutureProgress::HideOnFinish); //this is fading out the last updateinfo } startCheckTimer(OneMinute); } void UpdateInfoPlugin::timerEvent(QTimerEvent *event) { if (event->timerId() == d->currentTimerId && !d->lastCheckUpdateInfoTask.isRunning()) { stopCurrentCheckTimer(); d->lastCheckUpdateInfoTask = QtConcurrent::run(this, &UpdateInfoPlugin::checkForUpdates); d->checkUpdateInfoWatcher->setFuture(d->lastCheckUpdateInfoTask); } } void UpdateInfoPlugin::extensionsInitialized() { } } //namespace Internal } //namespace UpdateInfo Q_EXPORT_PLUGIN(UpdateInfo::Internal::UpdateInfoPlugin) <commit_msg>Warn if the update info plugin is useless.<commit_after>/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation (info@qt.nokia.com) ** ** ** GNU Lesser General Public License Usage ** ** This file may be used under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation and ** appearing in the file LICENSE.LGPL included in the packaging of this file. ** Please review the following information to ensure the GNU Lesser General ** Public License version 2.1 requirements will be met: ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** Other Usage ** ** Alternatively, this file may be used in accordance with the terms and ** conditions contained in a signed written agreement between you and Nokia. ** ** If you have questions regarding the use of this file, please contact ** Nokia at info@qt.nokia.com. ** **************************************************************************/ #include "updateinfoplugin.h" #include "updateinfobutton.h" #include <coreplugin/actionmanager/actionmanager.h> #include <coreplugin/actionmanager/actioncontainer.h> #include <coreplugin/coreconstants.h> #include <coreplugin/icore.h> #include <coreplugin/modemanager.h> #include <coreplugin/progressmanager/progressmanager.h> #include <coreplugin/progressmanager/futureprogress.h> #include <qtconcurrentrun.h> #include <QtCore/QtPlugin> #include <QtCore/QProcess> #include <QtCore/QTimer> #include <QtCore/QTimerEvent> #include <QtCore/QDebug> #include <QtCore/QFile> #include <QtCore/QThread> #include <QtCore/QCoreApplication> #include <QtCore/QProcess> #include <QtXml/QDomDocument> #include <QtGui/QMessageBox> #include <QtGui/QMenu> #include <QtCore/QFutureWatcher> namespace { static const quint32 OneMinute = 60000; } namespace UpdateInfo { namespace Internal { class UpdateInfoPluginPrivate { public: UpdateInfoPluginPrivate() : startUpdaterAction(0), currentTimerId(0), progressUpdateInfoButton(0), checkUpdateInfoWatcher(0) {} ~UpdateInfoPluginPrivate() { } QAction *startUpdaterAction; QString updaterProgram; QString updaterCheckOnlyArgument; QString updaterRunUiArgument; int currentTimerId; QFuture<QDomDocument> lastCheckUpdateInfoTask; QPointer<Core::FutureProgress> updateInfoProgress; UpdateInfoButton *progressUpdateInfoButton; QFutureWatcher<QDomDocument> *checkUpdateInfoWatcher; }; UpdateInfoPlugin::UpdateInfoPlugin() : d(new UpdateInfoPluginPrivate) { } UpdateInfoPlugin::~UpdateInfoPlugin() { delete d; } void UpdateInfoPlugin::startCheckTimer(uint milliseconds) { if (d->currentTimerId != 0) { stopCurrentCheckTimer(); } d->currentTimerId = startTimer(milliseconds); } void UpdateInfoPlugin::stopCurrentCheckTimer() { killTimer(d->currentTimerId); } /*! Initializes the plugin. Returns true on success. Plugins want to register objects with the plugin manager here. \a errorMessage can be used to pass an error message to the plugin system, if there was any. */ bool UpdateInfoPlugin::initialize(const QStringList & /* arguments */, QString *errorMessage) { d->checkUpdateInfoWatcher = new QFutureWatcher<QDomDocument>(this); connect(d->checkUpdateInfoWatcher, SIGNAL(finished()), this, SLOT(reactOnUpdaterOutput())); QSettings *settings = Core::ICore::instance()->settings(); d->updaterProgram = settings->value(QLatin1String("Updater/Application")).toString(); d->updaterCheckOnlyArgument = settings->value(QLatin1String("Updater/CheckOnlyArgument")).toString(); d->updaterRunUiArgument = settings->value(QLatin1String("Updater/RunUiArgument")).toString(); if (d->updaterProgram.isEmpty()) { *errorMessage = tr("Could not determine location of maintenance tool. Please check " "your installation if you did not enable this plugin manually."); return false; } if (!QFile::exists(d->updaterProgram)) { *errorMessage = tr("Could not find maintenance tool at '%1'. Check your installation.") .arg(d->updaterProgram); return false; } Core::ICore* const core = Core::ICore::instance(); Core::ActionManager* const actionManager = core->actionManager(); Core::ActionContainer* const helpActionContainer = actionManager->actionContainer(Core::Constants::M_HELP); helpActionContainer->menu()->addAction(tr("Start Updater"), this, SLOT(startUpdaterUiApplication())); //wait some time before we want to have the first check startCheckTimer(OneMinute / 10); return true; } QDomDocument UpdateInfoPlugin::checkForUpdates() { if (QThread::currentThread() == QCoreApplication::instance()->thread()) { qWarning() << Q_FUNC_INFO << " Was not designed to run in main/gui thread -> it is using updaterProcess.waitForFinished()"; } //starting QProcess updaterProcess; updaterProcess.start(d->updaterProgram, QStringList() << d->updaterCheckOnlyArgument); updaterProcess.waitForFinished(); //process return value if (updaterProcess.exitStatus() == QProcess::CrashExit) { qWarning() << "Get update info application crashed."; //return; //maybe there is some output } QString updaterOutput = updaterProcess.readAllStandardOutput(); QDomDocument updatesDomDocument; updatesDomDocument.setContent(updaterOutput); return updatesDomDocument; } void UpdateInfoPlugin::reactOnUpdaterOutput() { QDomDocument updatesDomDocument = d->checkUpdateInfoWatcher->result(); if (updatesDomDocument.isNull() || !updatesDomDocument.firstChildElement().hasChildNodes()) { // no updates are available startCheckTimer(60 * OneMinute); } else { //added the current almost finished task to the progressmanager d->updateInfoProgress = Core::ICore::instance()->progressManager()->addTask( d->lastCheckUpdateInfoTask, tr("Update"), QLatin1String("Update.GetInfo"), Core::ProgressManager::KeepOnFinish); d->updateInfoProgress->setKeepOnFinish(Core::FutureProgress::KeepOnFinish); d->progressUpdateInfoButton = new UpdateInfoButton(); //the old widget is deleted inside this function //and the current widget becomes a child of updateInfoProgress d->updateInfoProgress->setWidget(d->progressUpdateInfoButton); //d->progressUpdateInfoButton->setText(tr("Update")); //we have this information over the progressbar connect(d->progressUpdateInfoButton, SIGNAL(released()), this, SLOT(startUpdaterUiApplication())); } } void UpdateInfoPlugin::startUpdaterUiApplication() { QProcess::startDetached(d->updaterProgram, QStringList() << d->updaterRunUiArgument); if (!d->updateInfoProgress.isNull()) { d->updateInfoProgress->setKeepOnFinish(Core::FutureProgress::HideOnFinish); //this is fading out the last updateinfo } startCheckTimer(OneMinute); } void UpdateInfoPlugin::timerEvent(QTimerEvent *event) { if (event->timerId() == d->currentTimerId && !d->lastCheckUpdateInfoTask.isRunning()) { stopCurrentCheckTimer(); d->lastCheckUpdateInfoTask = QtConcurrent::run(this, &UpdateInfoPlugin::checkForUpdates); d->checkUpdateInfoWatcher->setFuture(d->lastCheckUpdateInfoTask); } } void UpdateInfoPlugin::extensionsInitialized() { } } //namespace Internal } //namespace UpdateInfo Q_EXPORT_PLUGIN(UpdateInfo::Internal::UpdateInfoPlugin) <|endoftext|>
<commit_before>/* * File: AlarmClockTest.cpp * Author: Craig Cogdill * Created: October 15, 2015 10:45am * Modifier: Amanda Carbonari * Modified Date: January 5, 2015 3:45pm */ #include "AlarmClockTest.h" #include "AlarmClock.h" #include "StopWatch.h" #include <chrono> #include <iostream> #include <thread> std::atomic<unsigned int> AlarmClockTest::mFakeSleepUs(0); namespace { typedef std::chrono::microseconds microseconds; typedef std::chrono::milliseconds milliseconds; typedef std::chrono::seconds seconds; unsigned int kFakeSleepLeeway = 100; template<typename T> void WaitForAlarmClockToExpire(AlarmClock<T>& alerter) { while (!alerter.Expired()); } template<typename Duration> unsigned int ConvertToMicroSeconds(Duration t) { return std::chrono::duration_cast<microseconds>(t).count(); } template<typename Duration> unsigned int ConvertToMilliSeconds(Duration t) { return std::chrono::duration_cast<milliseconds>(t).count(); } unsigned int FakeSleep(unsigned int usToSleep) { AlarmClockTest::mFakeSleepUs.store(usToSleep); std::this_thread::sleep_for(microseconds(100)); return 0; } } TEST_F(AlarmClockTest, GetUsSleepTimeInUs) { int us = 123456; AlarmClock<microseconds> alerter(us); EXPECT_EQ(us, alerter.SleepTimeUs()); } TEST_F(AlarmClockTest, GetUsSleepTimeInMs) { int us = 123456; AlarmClock<microseconds> alerter(us); EXPECT_EQ(ConvertToMilliSeconds(microseconds(us)), alerter.SleepTimeMs()); } TEST_F(AlarmClockTest, GetMsSleepTimeInMs) { int ms = 123456; AlarmClock<milliseconds> alerter(ms); EXPECT_EQ(ms, alerter.SleepTimeMs()); } TEST_F(AlarmClockTest, GetMsSleepTimeInUs) { int ms = 123456; AlarmClock<milliseconds> alerter(ms); EXPECT_EQ(ConvertToMicroSeconds(milliseconds(ms)), alerter.SleepTimeUs()); } TEST_F(AlarmClockTest, GetSecSleepTimeInUs) { int sec = 1; AlarmClock<seconds> alerter(sec); EXPECT_EQ(ConvertToMicroSeconds(seconds(sec)), alerter.SleepTimeUs()); } TEST_F(AlarmClockTest, GetSecSleepTimeInMs) { int sec = 1; AlarmClock<seconds> alerter(sec); EXPECT_EQ(ConvertToMilliSeconds(seconds(sec)), alerter.SleepTimeMs()); } TEST_F(AlarmClockTest, microsecondsLessThan500ms) { int us = 900; AlarmClock<microseconds> alerter(us, FakeSleep); EXPECT_FALSE(alerter.Expired()); WaitForAlarmClockToExpire(alerter); EXPECT_TRUE(alerter.Expired()); EXPECT_GE(AlarmClockTest::mFakeSleepUs, us-kFakeSleepLeeway); EXPECT_LE(AlarmClockTest::mFakeSleepUs, us); } TEST_F(AlarmClockTest, microsecondsGreaterThan500ms) { int us = 600000; AlarmClock<microseconds> alerter(us, FakeSleep); EXPECT_FALSE(alerter.Expired()); WaitForAlarmClockToExpire(alerter); EXPECT_TRUE(alerter.Expired()); EXPECT_GE(AlarmClockTest::mFakeSleepUs, us-kFakeSleepLeeway); EXPECT_LE(AlarmClockTest::mFakeSleepUs, us); } TEST_F(AlarmClockTest, weirdNumberOfMicroseconds) { int us = 724509; StopWatch sw; AlarmClock<microseconds> alerter(us, FakeSleep); EXPECT_FALSE(alerter.Expired()); WaitForAlarmClockToExpire(alerter); EXPECT_TRUE(alerter.Expired()); EXPECT_GE(AlarmClockTest::mFakeSleepUs, us-kFakeSleepLeeway); EXPECT_LE(AlarmClockTest::mFakeSleepUs, us); } TEST_F(AlarmClockTest, millisecondsLessThan500) { unsigned int ms = 100; AlarmClock<milliseconds> alerter(ms, FakeSleep); EXPECT_FALSE(alerter.Expired()); WaitForAlarmClockToExpire(alerter); EXPECT_TRUE(alerter.Expired()); EXPECT_GE(AlarmClockTest::mFakeSleepUs, alerter.SleepTimeUs()-kFakeSleepLeeway); EXPECT_LE(AlarmClockTest::mFakeSleepUs, alerter.SleepTimeUs()); } TEST_F(AlarmClockTest, oneSecondInMilliseconds) { unsigned int ms = 1000; AlarmClock<milliseconds> alerter(ms, FakeSleep); EXPECT_FALSE(alerter.Expired()); WaitForAlarmClockToExpire(alerter); EXPECT_TRUE(alerter.Expired()); EXPECT_GE(AlarmClockTest::mFakeSleepUs, alerter.SleepTimeUs()-kFakeSleepLeeway); EXPECT_LE(AlarmClockTest::mFakeSleepUs, alerter.SleepTimeUs()); } TEST_F(AlarmClockTest, millisecondsNotDivisibleBy500) { unsigned int ms = 1000; AlarmClock<milliseconds> alerter(ms, FakeSleep); EXPECT_FALSE(alerter.Expired()); WaitForAlarmClockToExpire(alerter); EXPECT_TRUE(alerter.Expired()); EXPECT_GE(AlarmClockTest::mFakeSleepUs, alerter.SleepTimeUs()-kFakeSleepLeeway); EXPECT_LE(AlarmClockTest::mFakeSleepUs, alerter.SleepTimeUs()); } TEST_F(AlarmClockTest, secondsSimple) { unsigned int sec = 1; AlarmClock<seconds> alerter(sec, FakeSleep); EXPECT_FALSE(alerter.Expired()); WaitForAlarmClockToExpire(alerter); EXPECT_TRUE(alerter.Expired()); EXPECT_GE(AlarmClockTest::mFakeSleepUs, alerter.SleepTimeUs()-kFakeSleepLeeway); EXPECT_LE(AlarmClockTest::mFakeSleepUs, alerter.SleepTimeUs()); } // Not working, not sure what it's supposed to be testing? TEST_F(AlarmClockTest, LongTimeout_ImmediatelyDestructed) { unsigned int sec = 1000; StopWatch sw; // cout << "TEST: Creating pointer" << endl; std::unique_ptr<AlarmClock<seconds>> acPtr(new AlarmClock<seconds>(sec, FakeSleep)); // cout << "TEST: expecting false for expired" << endl; EXPECT_FALSE(acPtr->Expired()); this_thread::sleep_for(microseconds(10)); // cout << "TEST: resetting pointer" << endl; acPtr.reset(); // cout << "TEST: expecting true for elapsed seconds" << endl; EXPECT_TRUE(sw.ElapsedSec() < 2); // cout << "TEST: calling destructor" << endl; } TEST_F(AlarmClockTest, milliseconds_ResetAfterExpired) { // First run int ms = 750; // cout << "TEST: creating alarm clock" << endl; AlarmClock<milliseconds> alerter(ms, FakeSleep); // cout << "TEST: expecting false for expired" << endl; EXPECT_FALSE(alerter.Expired()); // cout << "TEST: waiting for alarm clock to expire" << endl; WaitForAlarmClockToExpire(alerter); // cout << "TEST: expecting true for expired" << endl; EXPECT_TRUE(alerter.Expired()); // Reset after AlarmClock has expired // cout << "TEST: resetting alarm clock" << endl; alerter.Reset(); // cout << "TEST: expecting false for expired" << endl; EXPECT_FALSE(alerter.Expired()); // cout << "TEST: waiting for alarm clock to expire" << endl; WaitForAlarmClockToExpire(alerter); // cout << "TEST: expecting true for expired" << endl; EXPECT_TRUE(alerter.Expired()); // cout << "TEST: finished and calling destrcutor" << endl; } TEST_F(AlarmClockTest, milliseconds_ResetBeforeExpired) { int ms = 7500; AlarmClock<milliseconds> alerter(ms, FakeSleep); EXPECT_FALSE(alerter.Expired()); alerter.Reset(); WaitForAlarmClockToExpire(alerter); EXPECT_TRUE(alerter.Expired()); } TEST_F(AlarmClockTest, milliseconds_MultipleResetsAfterExpired) { // First run int ms = 750; AlarmClock<milliseconds> alerter(ms, FakeSleep); EXPECT_FALSE(alerter.Expired()); WaitForAlarmClockToExpire(alerter); EXPECT_TRUE(alerter.Expired()); // Reset after AlarmClock has expired alerter.Reset(); EXPECT_FALSE(alerter.Expired()); WaitForAlarmClockToExpire(alerter); EXPECT_TRUE(alerter.Expired()); // Reset again after it has expired alerter.Reset(); EXPECT_FALSE(alerter.Expired()); WaitForAlarmClockToExpire(alerter); EXPECT_TRUE(alerter.Expired()); } TEST_F(AlarmClockTest, milliseconds_MultipleResetsBeforeExpired) { int ms = 7500; AlarmClock<milliseconds> alerter(ms, FakeSleep); EXPECT_FALSE(alerter.Expired()); alerter.Reset(); EXPECT_FALSE(alerter.Expired()); alerter.Reset(); WaitForAlarmClockToExpire(alerter); EXPECT_TRUE(alerter.Expired()); } TEST_F(AlarmClockTest, milliseconds_MultipleResetsMixed) { int ms = 750; AlarmClock<milliseconds> alerter(ms, FakeSleep); EXPECT_FALSE(alerter.Expired()); WaitForAlarmClockToExpire(alerter); EXPECT_TRUE(alerter.Expired()); alerter.Reset(); EXPECT_FALSE(alerter.Expired()); WaitForAlarmClockToExpire(alerter); EXPECT_TRUE(alerter.Expired()); alerter.Reset(); EXPECT_FALSE(alerter.Expired()); alerter.Reset(); EXPECT_FALSE(alerter.Expired()); WaitForAlarmClockToExpire(alerter); EXPECT_TRUE(alerter.Expired()); } <commit_msg>Chasing down concurrency issues<commit_after>/* * File: AlarmClockTest.cpp * Author: Craig Cogdill * Created: October 15, 2015 10:45am * Modifier: Amanda Carbonari * Modified Date: January 5, 2015 3:45pm */ #include "AlarmClockTest.h" #include "AlarmClock.h" #include "StopWatch.h" #include <chrono> #include <iostream> #include <thread> std::atomic<unsigned int> AlarmClockTest::mFakeSleepUs(0); namespace { typedef std::chrono::microseconds microseconds; typedef std::chrono::milliseconds milliseconds; typedef std::chrono::seconds seconds; unsigned int kFakeSleepLeeway = 100; template<typename T> void WaitForAlarmClockToExpire(AlarmClock<T>& alerter) { while (!alerter.Expired()); } template<typename Duration> unsigned int ConvertToMicroSeconds(Duration t) { return std::chrono::duration_cast<microseconds>(t).count(); } template<typename Duration> unsigned int ConvertToMilliSeconds(Duration t) { return std::chrono::duration_cast<milliseconds>(t).count(); } unsigned int FakeSleep(unsigned int usToSleep) { AlarmClockTest::mFakeSleepUs.store(usToSleep); std::this_thread::sleep_for(microseconds(100)); return 0; } } TEST_F(AlarmClockTest, GetUsSleepTimeInUs) { int us = 123456; AlarmClock<microseconds> alerter(us); EXPECT_EQ(us, alerter.SleepTimeUs()); } TEST_F(AlarmClockTest, GetUsSleepTimeInMs) { int us = 123456; AlarmClock<microseconds> alerter(us); EXPECT_EQ(ConvertToMilliSeconds(microseconds(us)), alerter.SleepTimeMs()); } TEST_F(AlarmClockTest, GetMsSleepTimeInMs) { int ms = 123456; AlarmClock<milliseconds> alerter(ms); EXPECT_EQ(ms, alerter.SleepTimeMs()); } TEST_F(AlarmClockTest, GetMsSleepTimeInUs) { int ms = 123456; AlarmClock<milliseconds> alerter(ms); EXPECT_EQ(ConvertToMicroSeconds(milliseconds(ms)), alerter.SleepTimeUs()); } TEST_F(AlarmClockTest, GetSecSleepTimeInUs) { int sec = 1; AlarmClock<seconds> alerter(sec); EXPECT_EQ(ConvertToMicroSeconds(seconds(sec)), alerter.SleepTimeUs()); } TEST_F(AlarmClockTest, GetSecSleepTimeInMs) { int sec = 1; AlarmClock<seconds> alerter(sec); EXPECT_EQ(ConvertToMilliSeconds(seconds(sec)), alerter.SleepTimeMs()); } TEST_F(AlarmClockTest, microsecondsLessThan500ms) { int us = 900; AlarmClock<microseconds> alerter(us, FakeSleep); EXPECT_FALSE(alerter.Expired()); WaitForAlarmClockToExpire(alerter); EXPECT_TRUE(alerter.Expired()); EXPECT_GE(AlarmClockTest::mFakeSleepUs, us-kFakeSleepLeeway); EXPECT_LE(AlarmClockTest::mFakeSleepUs, us); } TEST_F(AlarmClockTest, microsecondsGreaterThan500ms) { int us = 600000; AlarmClock<microseconds> alerter(us, FakeSleep); EXPECT_FALSE(alerter.Expired()); WaitForAlarmClockToExpire(alerter); EXPECT_TRUE(alerter.Expired()); EXPECT_GE(AlarmClockTest::mFakeSleepUs, us-kFakeSleepLeeway); EXPECT_LE(AlarmClockTest::mFakeSleepUs, us); } TEST_F(AlarmClockTest, weirdNumberOfMicroseconds) { int us = 724509; StopWatch sw; AlarmClock<microseconds> alerter(us, FakeSleep); EXPECT_FALSE(alerter.Expired()); WaitForAlarmClockToExpire(alerter); EXPECT_TRUE(alerter.Expired()); EXPECT_GE(AlarmClockTest::mFakeSleepUs, us-kFakeSleepLeeway); EXPECT_LE(AlarmClockTest::mFakeSleepUs, us); } TEST_F(AlarmClockTest, millisecondsLessThan500) { unsigned int ms = 100; AlarmClock<milliseconds> alerter(ms, FakeSleep); EXPECT_FALSE(alerter.Expired()); WaitForAlarmClockToExpire(alerter); EXPECT_TRUE(alerter.Expired()); EXPECT_GE(AlarmClockTest::mFakeSleepUs, alerter.SleepTimeUs()-kFakeSleepLeeway); EXPECT_LE(AlarmClockTest::mFakeSleepUs, alerter.SleepTimeUs()); } TEST_F(AlarmClockTest, oneSecondInMilliseconds) { unsigned int ms = 1000; AlarmClock<milliseconds> alerter(ms, FakeSleep); EXPECT_FALSE(alerter.Expired()); WaitForAlarmClockToExpire(alerter); EXPECT_TRUE(alerter.Expired()); EXPECT_GE(AlarmClockTest::mFakeSleepUs, alerter.SleepTimeUs()-kFakeSleepLeeway); EXPECT_LE(AlarmClockTest::mFakeSleepUs, alerter.SleepTimeUs()); } TEST_F(AlarmClockTest, millisecondsNotDivisibleBy500) { unsigned int ms = 1000; AlarmClock<milliseconds> alerter(ms, FakeSleep); EXPECT_FALSE(alerter.Expired()); WaitForAlarmClockToExpire(alerter); EXPECT_TRUE(alerter.Expired()); EXPECT_GE(AlarmClockTest::mFakeSleepUs, alerter.SleepTimeUs()-kFakeSleepLeeway); EXPECT_LE(AlarmClockTest::mFakeSleepUs, alerter.SleepTimeUs()); } TEST_F(AlarmClockTest, secondsSimple) { unsigned int sec = 1; AlarmClock<seconds> alerter(sec, FakeSleep); EXPECT_FALSE(alerter.Expired()); WaitForAlarmClockToExpire(alerter); EXPECT_TRUE(alerter.Expired()); EXPECT_GE(AlarmClockTest::mFakeSleepUs, alerter.SleepTimeUs()-kFakeSleepLeeway); EXPECT_LE(AlarmClockTest::mFakeSleepUs, alerter.SleepTimeUs()); } // Not working, not sure what it's supposed to be testing? TEST_F(AlarmClockTest, LongTimeout_ImmediatelyDestructed) { unsigned int sec = 1000; StopWatch sw; // cout << "TEST: Creating pointer" << endl; std::unique_ptr<AlarmClock<seconds>> acPtr(new AlarmClock<seconds>(sec, FakeSleep)); // cout << "TEST: expecting false for expired" << endl; EXPECT_FALSE(acPtr->Expired()); this_thread::sleep_for(microseconds(10)); // cout << "TEST: resetting pointer" << endl; acPtr.reset(); // cout << "TEST: expecting true for elapsed seconds" << endl; EXPECT_TRUE(sw.ElapsedSec() < 2); // cout << "TEST: calling destructor" << endl; } TEST_F(AlarmClockTest, milliseconds_ResetAfterExpired) { // First run int ms = 750; cout << "TEST: creating alarm clock" << endl; AlarmClock<milliseconds> alerter(ms, FakeSleep); cout << "TEST: expecting false for expired" << endl; EXPECT_FALSE(alerter.Expired()); cout << "TEST: waiting for alarm clock to expire" << endl; WaitForAlarmClockToExpire(alerter); cout << "TEST: expecting true for expired" << endl; EXPECT_TRUE(alerter.Expired()); // Reset after AlarmClock has expired cout << "TEST: resetting alarm clock" << endl; alerter.Reset(); cout << "TEST: expecting false for expired" << endl; EXPECT_FALSE(alerter.Expired()); cout << "TEST: waiting for alarm clock to expire" << endl; WaitForAlarmClockToExpire(alerter); cout << "TEST: expecting true for expired" << endl; EXPECT_TRUE(alerter.Expired()); cout << "TEST: finished and calling destrcutor" << endl; } TEST_F(AlarmClockTest, milliseconds_ResetBeforeExpired) { int ms = 7500; AlarmClock<milliseconds> alerter(ms, FakeSleep); EXPECT_FALSE(alerter.Expired()); alerter.Reset(); WaitForAlarmClockToExpire(alerter); EXPECT_TRUE(alerter.Expired()); } TEST_F(AlarmClockTest, milliseconds_MultipleResetsAfterExpired) { // First run int ms = 750; AlarmClock<milliseconds> alerter(ms, FakeSleep); EXPECT_FALSE(alerter.Expired()); WaitForAlarmClockToExpire(alerter); EXPECT_TRUE(alerter.Expired()); // Reset after AlarmClock has expired alerter.Reset(); EXPECT_FALSE(alerter.Expired()); WaitForAlarmClockToExpire(alerter); EXPECT_TRUE(alerter.Expired()); // Reset again after it has expired alerter.Reset(); EXPECT_FALSE(alerter.Expired()); WaitForAlarmClockToExpire(alerter); EXPECT_TRUE(alerter.Expired()); } TEST_F(AlarmClockTest, milliseconds_MultipleResetsBeforeExpired) { int ms = 7500; AlarmClock<milliseconds> alerter(ms, FakeSleep); EXPECT_FALSE(alerter.Expired()); alerter.Reset(); EXPECT_FALSE(alerter.Expired()); alerter.Reset(); WaitForAlarmClockToExpire(alerter); EXPECT_TRUE(alerter.Expired()); } TEST_F(AlarmClockTest, milliseconds_MultipleResetsMixed) { int ms = 750; AlarmClock<milliseconds> alerter(ms, FakeSleep); EXPECT_FALSE(alerter.Expired()); WaitForAlarmClockToExpire(alerter); EXPECT_TRUE(alerter.Expired()); alerter.Reset(); EXPECT_FALSE(alerter.Expired()); WaitForAlarmClockToExpire(alerter); EXPECT_TRUE(alerter.Expired()); alerter.Reset(); EXPECT_FALSE(alerter.Expired()); alerter.Reset(); EXPECT_FALSE(alerter.Expired()); WaitForAlarmClockToExpire(alerter); EXPECT_TRUE(alerter.Expired()); } <|endoftext|>
<commit_before>/* * This file is part of meego-im-framework * * * Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). * All rights reserved. * Contact: Nokia Corporation (directui@nokia.com) * * If you have questions regarding the use of this file, please contact * Nokia at directui@nokia.com. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1 as published by the Free Software Foundation * and appearing in the file LICENSE.LGPL included in the packaging * of this file. */ #include "mainwindow.h" #include <QApplication> #include <cstdlib> int main(int argc, char** argv) { // Set input method to MInputContext #ifdef HAVE_LEGACY_NAMES setenv("QT_IM_MODULE", "MInputContext", 1); #else setenv("QT_IM_MODULE", "Maliit", 1); #endif QApplication kit(argc, argv); #ifdef Q_WS_QPA // Workaround for lighthouse Qt kit.setInputContext(QInputContextFactory::create("Maliit", &kit)); #endif MainWindow window; return kit.exec(); } <commit_msg>Do not set the input context in example in Qt 5<commit_after>/* * This file is part of meego-im-framework * * * Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). * All rights reserved. * Contact: Nokia Corporation (directui@nokia.com) * * If you have questions regarding the use of this file, please contact * Nokia at directui@nokia.com. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1 as published by the Free Software Foundation * and appearing in the file LICENSE.LGPL included in the packaging * of this file. */ #include "mainwindow.h" #include <QApplication> #include <cstdlib> int main(int argc, char** argv) { // Set input method to MInputContext #ifdef HAVE_LEGACY_NAMES setenv("QT_IM_MODULE", "MInputContext", 1); #else setenv("QT_IM_MODULE", "Maliit", 1); #endif QApplication kit(argc, argv); #if defined(Q_WS_QPA) && (QT_VERSION < 0x050000) // Workaround for lighthouse Qt kit.setInputContext(QInputContextFactory::create("Maliit", &kit)); #endif MainWindow window; return kit.exec(); } <|endoftext|>