text
stringlengths
54
60.6k
<commit_before>/******************************************************************************\ * File: shell.cpp * Purpose: Implementation of class wxExSTCShell * Author: Anton van Wezenbeek * RCS-ID: $Id$ * * Copyright (c) 1998-2009 Anton van Wezenbeek * All rights are reserved. Reproduction in whole or part is prohibited * without the written consent of the copyright owner. \******************************************************************************/ #include <wx/wxprec.h> #ifndef WX_PRECOMP #include <wx/wx.h> #endif #include <numeric> #include <functional> #include <wx/config.h> #include <wx/tokenzr.h> #include <wx/extension/shell.h> #include <wx/extension/defs.h> // for ID_SHELL_COMMAND #if wxUSE_GUI BEGIN_EVENT_TABLE(wxExSTCShell, wxExSTC) EVT_KEY_DOWN(wxExSTCShell::OnKey) EVT_MENU(wxID_PASTE, wxExSTCShell::OnCommand) END_EVENT_TABLE() wxExSTCShell::wxExSTCShell( wxWindow* parent, const wxString& prompt, const wxString& command_end, bool echo, int commands_save_in_config, long menu_flags, wxWindowID id, const wxPoint& pos, const wxSize& size, long style) : wxExSTC( parent, wxEmptyString, 0, menu_flags, id, pos, size, style) , m_Command(wxEmptyString) , m_CommandEnd((command_end == wxEmptyString ? GetEOL(): command_end)) , m_CommandStartPosition(0) , m_Echo(echo) // take a char that is not likely to appear inside commands , m_CommandsInConfigDelimiter(wxUniChar(0x03)) , m_CommandsSaveInConfig(commands_save_in_config) , m_Prompt(prompt) { // Override defaults from config. SetEdgeMode(wxSTC_EDGE_NONE); ResetMargins(false); // do not reset divider margin // Start with a prompt. Prompt(); if (m_CommandsSaveInConfig > 0) { // Get all previous commands. wxStringTokenizer tkz(wxConfigBase::Get()->Read("Shell"), m_CommandsInConfigDelimiter); while (tkz.HasMoreTokens()) { const wxString val = tkz.GetNextToken(); m_Commands.push_front(val); } } // Take care that m_CommandsIterator is valid. m_CommandsIterator = m_Commands.end(); } wxExSTCShell::~wxExSTCShell() { if (m_CommandsSaveInConfig > 0) { wxString values; int items = 0; // using a const_reverse_iterator here does not compile under Visual Studio 2003 for ( std::list < wxString >::reverse_iterator it = m_Commands.rbegin(); it != m_Commands.rend() && items < m_CommandsSaveInConfig; it++) { values += *it + m_CommandsInConfigDelimiter; items++; } wxConfigBase::Get()->Write("Shell", values); } } const wxString wxExSTCShell::GetHistory() const { return accumulate(m_Commands.begin(), m_Commands.end(), wxString()); } void wxExSTCShell::KeepCommand() { m_Commands.remove(m_Command); m_Commands.push_back(m_Command); } void wxExSTCShell::OnCommand(wxCommandEvent& command) { switch (command.GetId()) { case wxID_PASTE: // Take care that we cannot paste somewhere inside. if (GetCurrentPos() < m_CommandStartPosition) { DocumentEnd(); } Paste(); break; default: wxFAIL; break; } } void wxExSTCShell::OnKey(wxKeyEvent& event) { const auto key = event.GetKeyCode(); // Enter key pressed, we might have entered a command. if (key == WXK_RETURN) { // First get the command. SetTargetStart(GetTextLength()); SetTargetEnd(0); SetSearchFlags(wxSTC_FIND_REGEXP); if (SearchInTarget("^" + m_Prompt + ".*") != -1) { m_Command = GetText().substr( GetTargetStart() + m_Prompt.length(), GetTextLength() - 1); m_Command.Trim(); } if (m_Command.empty()) { Prompt(); } else if ( m_CommandEnd == GetEOL() || m_Command.EndsWith(m_CommandEnd)) { // We have a command. EmptyUndoBuffer(); // History command. if (m_Command == wxString("history") + (m_CommandEnd == GetEOL() ? wxString(wxEmptyString): m_CommandEnd)) { KeepCommand(); ShowHistory(); Prompt(); } // !.. command, get it from history. else if (m_Command.StartsWith("!")) { if (SetCommandFromHistory(m_Command.substr(1))) { AppendText(GetEOL() + m_Command); // We don't keep the command, so commands are not rearranged and // repeatingly calling !5 always gives the same command, just as bash does. wxCommandEvent event(wxEVT_COMMAND_MENU_SELECTED, ID_SHELL_COMMAND); event.SetString(m_Command); wxPostEvent(GetParent(), event); } else { Prompt(GetEOL() + m_Command + ": " + _("event not found")); } } // Other command, send to parent. else { KeepCommand(); wxCommandEvent event(wxEVT_COMMAND_MENU_SELECTED, ID_SHELL_COMMAND); event.SetString(m_Command); wxPostEvent(GetParent(), event); } m_Command.clear(); } else { if (m_Echo) event.Skip(); } m_CommandsIterator = m_Commands.end(); } // Up or down key pressed, and at the end of document. else if ((key == WXK_UP || key == WXK_DOWN) && GetCurrentPos() == GetTextLength()) { ShowCommand(key); } // Home key pressed. else if (key == WXK_HOME) { Home(); const wxString line = GetLine(GetCurrentLine()); if (line.StartsWith(m_Prompt)) { GotoPos(GetCurrentPos() + m_Prompt.length()); } } // Ctrl-Q pressed, used to stop processing. else if (event.GetModifiers() == wxMOD_CONTROL && key == 'Q') { wxCommandEvent event(wxEVT_COMMAND_MENU_SELECTED, ID_SHELL_COMMAND_STOP); wxPostEvent(GetParent(), event); } // Ctrl-V pressed, used for pasting as well. else if (event.GetModifiers() == wxMOD_CONTROL && key == 'V') { if (GetCurrentPos() < m_CommandStartPosition) DocumentEnd(); if (m_Echo) event.Skip(); } // Backspace or delete key pressed. else if (key == WXK_BACK || key == WXK_DELETE) { if (GetCurrentPos() <= m_CommandStartPosition) { // Ignore, so do nothing. } else { // Allow. if (m_Echo) event.Skip(); } } // The rest. else { // If we enter regular text and not already building a command, first goto end. if (event.GetModifiers() == wxMOD_NONE && key < WXK_START && GetCurrentPos() < m_CommandStartPosition) { DocumentEnd(); } m_CommandsIterator = m_Commands.end(); if (m_Echo) event.Skip(); } } void wxExSTCShell::Prompt(const wxString& text, bool add_eol) { if (!text.empty()) { AppendText(text); } if (GetTextLength() > 0 && add_eol) { AppendText(GetEOL()); } AppendText(m_Prompt); DocumentEnd(); m_CommandStartPosition = GetCurrentPos(); EmptyUndoBuffer(); } bool wxExSTCShell::SetCommandFromHistory(const wxString& short_command) { const auto no_asked_for = atoi(short_command.c_str()); if (no_asked_for > 0) { int no = 1; for ( auto it = m_Commands.begin(); it != m_Commands.end(); it++) { if (no == no_asked_for) { m_Command = *it; return true; } no++; } } else { wxString short_command_check; if (m_CommandEnd == GetEOL()) { short_command_check = short_command; } else { short_command_check = short_command.substr( 0, short_command.length() - m_CommandEnd.length()); } // using a const_reverse_iterator here does not compile under Visual Studio 2003 for ( std::list < wxString >::reverse_iterator it = m_Commands.rbegin(); it != m_Commands.rend(); it++) { const wxString command = *it; if (command.StartsWith(short_command_check)) { m_Command = command; return true; } } } return false; } void wxExSTCShell::ShowCommand(int key) { SetTargetStart(GetTextLength()); SetTargetEnd(0); SetSearchFlags(wxSTC_FIND_REGEXP); if (SearchInTarget("^" + m_Prompt + ".*") != -1) { SetTargetEnd(GetTextLength()); if (key == WXK_UP) { if (m_CommandsIterator != m_Commands.begin()) { m_CommandsIterator--; } } else { if (m_CommandsIterator != m_Commands.end()) { m_CommandsIterator++; } } if (m_CommandsIterator != m_Commands.end()) { ReplaceTarget(m_Prompt + *m_CommandsIterator); } else { ReplaceTarget(m_Prompt); } DocumentEnd(); } } void wxExSTCShell::ShowHistory() { int command_no = 1; for ( auto it = m_Commands.begin(); it != m_Commands.end(); it++) { const wxString command = *it; AppendText(wxString::Format("\n%d %s", command_no++, command.c_str())); } } #endif // wxUSE_GUI <commit_msg>replace iterator for auto<commit_after>/******************************************************************************\ * File: shell.cpp * Purpose: Implementation of class wxExSTCShell * Author: Anton van Wezenbeek * RCS-ID: $Id$ * * Copyright (c) 1998-2009 Anton van Wezenbeek * All rights are reserved. Reproduction in whole or part is prohibited * without the written consent of the copyright owner. \******************************************************************************/ #include <wx/wxprec.h> #ifndef WX_PRECOMP #include <wx/wx.h> #endif #include <numeric> #include <functional> #include <wx/config.h> #include <wx/tokenzr.h> #include <wx/extension/shell.h> #include <wx/extension/defs.h> // for ID_SHELL_COMMAND #if wxUSE_GUI BEGIN_EVENT_TABLE(wxExSTCShell, wxExSTC) EVT_KEY_DOWN(wxExSTCShell::OnKey) EVT_MENU(wxID_PASTE, wxExSTCShell::OnCommand) END_EVENT_TABLE() wxExSTCShell::wxExSTCShell( wxWindow* parent, const wxString& prompt, const wxString& command_end, bool echo, int commands_save_in_config, long menu_flags, wxWindowID id, const wxPoint& pos, const wxSize& size, long style) : wxExSTC( parent, wxEmptyString, 0, menu_flags, id, pos, size, style) , m_Command(wxEmptyString) , m_CommandEnd((command_end == wxEmptyString ? GetEOL(): command_end)) , m_CommandStartPosition(0) , m_Echo(echo) // take a char that is not likely to appear inside commands , m_CommandsInConfigDelimiter(wxUniChar(0x03)) , m_CommandsSaveInConfig(commands_save_in_config) , m_Prompt(prompt) { // Override defaults from config. SetEdgeMode(wxSTC_EDGE_NONE); ResetMargins(false); // do not reset divider margin // Start with a prompt. Prompt(); if (m_CommandsSaveInConfig > 0) { // Get all previous commands. wxStringTokenizer tkz(wxConfigBase::Get()->Read("Shell"), m_CommandsInConfigDelimiter); while (tkz.HasMoreTokens()) { const wxString val = tkz.GetNextToken(); m_Commands.push_front(val); } } // Take care that m_CommandsIterator is valid. m_CommandsIterator = m_Commands.end(); } wxExSTCShell::~wxExSTCShell() { if (m_CommandsSaveInConfig > 0) { wxString values; int items = 0; // using a const_reverse_iterator here does not compile under Visual Studio 2003 for ( auto it = m_Commands.rbegin(); it != m_Commands.rend() && items < m_CommandsSaveInConfig; it++) { values += *it + m_CommandsInConfigDelimiter; items++; } wxConfigBase::Get()->Write("Shell", values); } } const wxString wxExSTCShell::GetHistory() const { return accumulate(m_Commands.begin(), m_Commands.end(), wxString()); } void wxExSTCShell::KeepCommand() { m_Commands.remove(m_Command); m_Commands.push_back(m_Command); } void wxExSTCShell::OnCommand(wxCommandEvent& command) { switch (command.GetId()) { case wxID_PASTE: // Take care that we cannot paste somewhere inside. if (GetCurrentPos() < m_CommandStartPosition) { DocumentEnd(); } Paste(); break; default: wxFAIL; break; } } void wxExSTCShell::OnKey(wxKeyEvent& event) { const auto key = event.GetKeyCode(); // Enter key pressed, we might have entered a command. if (key == WXK_RETURN) { // First get the command. SetTargetStart(GetTextLength()); SetTargetEnd(0); SetSearchFlags(wxSTC_FIND_REGEXP); if (SearchInTarget("^" + m_Prompt + ".*") != -1) { m_Command = GetText().substr( GetTargetStart() + m_Prompt.length(), GetTextLength() - 1); m_Command.Trim(); } if (m_Command.empty()) { Prompt(); } else if ( m_CommandEnd == GetEOL() || m_Command.EndsWith(m_CommandEnd)) { // We have a command. EmptyUndoBuffer(); // History command. if (m_Command == wxString("history") + (m_CommandEnd == GetEOL() ? wxString(wxEmptyString): m_CommandEnd)) { KeepCommand(); ShowHistory(); Prompt(); } // !.. command, get it from history. else if (m_Command.StartsWith("!")) { if (SetCommandFromHistory(m_Command.substr(1))) { AppendText(GetEOL() + m_Command); // We don't keep the command, so commands are not rearranged and // repeatingly calling !5 always gives the same command, just as bash does. wxCommandEvent event(wxEVT_COMMAND_MENU_SELECTED, ID_SHELL_COMMAND); event.SetString(m_Command); wxPostEvent(GetParent(), event); } else { Prompt(GetEOL() + m_Command + ": " + _("event not found")); } } // Other command, send to parent. else { KeepCommand(); wxCommandEvent event(wxEVT_COMMAND_MENU_SELECTED, ID_SHELL_COMMAND); event.SetString(m_Command); wxPostEvent(GetParent(), event); } m_Command.clear(); } else { if (m_Echo) event.Skip(); } m_CommandsIterator = m_Commands.end(); } // Up or down key pressed, and at the end of document. else if ((key == WXK_UP || key == WXK_DOWN) && GetCurrentPos() == GetTextLength()) { ShowCommand(key); } // Home key pressed. else if (key == WXK_HOME) { Home(); const wxString line = GetLine(GetCurrentLine()); if (line.StartsWith(m_Prompt)) { GotoPos(GetCurrentPos() + m_Prompt.length()); } } // Ctrl-Q pressed, used to stop processing. else if (event.GetModifiers() == wxMOD_CONTROL && key == 'Q') { wxCommandEvent event(wxEVT_COMMAND_MENU_SELECTED, ID_SHELL_COMMAND_STOP); wxPostEvent(GetParent(), event); } // Ctrl-V pressed, used for pasting as well. else if (event.GetModifiers() == wxMOD_CONTROL && key == 'V') { if (GetCurrentPos() < m_CommandStartPosition) DocumentEnd(); if (m_Echo) event.Skip(); } // Backspace or delete key pressed. else if (key == WXK_BACK || key == WXK_DELETE) { if (GetCurrentPos() <= m_CommandStartPosition) { // Ignore, so do nothing. } else { // Allow. if (m_Echo) event.Skip(); } } // The rest. else { // If we enter regular text and not already building a command, first goto end. if (event.GetModifiers() == wxMOD_NONE && key < WXK_START && GetCurrentPos() < m_CommandStartPosition) { DocumentEnd(); } m_CommandsIterator = m_Commands.end(); if (m_Echo) event.Skip(); } } void wxExSTCShell::Prompt(const wxString& text, bool add_eol) { if (!text.empty()) { AppendText(text); } if (GetTextLength() > 0 && add_eol) { AppendText(GetEOL()); } AppendText(m_Prompt); DocumentEnd(); m_CommandStartPosition = GetCurrentPos(); EmptyUndoBuffer(); } bool wxExSTCShell::SetCommandFromHistory(const wxString& short_command) { const auto no_asked_for = atoi(short_command.c_str()); if (no_asked_for > 0) { int no = 1; for ( auto it = m_Commands.begin(); it != m_Commands.end(); it++) { if (no == no_asked_for) { m_Command = *it; return true; } no++; } } else { wxString short_command_check; if (m_CommandEnd == GetEOL()) { short_command_check = short_command; } else { short_command_check = short_command.substr( 0, short_command.length() - m_CommandEnd.length()); } // using a const_reverse_iterator here does not compile under Visual Studio 2003 for ( auto it = m_Commands.rbegin(); it != m_Commands.rend(); it++) { const wxString command = *it; if (command.StartsWith(short_command_check)) { m_Command = command; return true; } } } return false; } void wxExSTCShell::ShowCommand(int key) { SetTargetStart(GetTextLength()); SetTargetEnd(0); SetSearchFlags(wxSTC_FIND_REGEXP); if (SearchInTarget("^" + m_Prompt + ".*") != -1) { SetTargetEnd(GetTextLength()); if (key == WXK_UP) { if (m_CommandsIterator != m_Commands.begin()) { m_CommandsIterator--; } } else { if (m_CommandsIterator != m_Commands.end()) { m_CommandsIterator++; } } if (m_CommandsIterator != m_Commands.end()) { ReplaceTarget(m_Prompt + *m_CommandsIterator); } else { ReplaceTarget(m_Prompt); } DocumentEnd(); } } void wxExSTCShell::ShowHistory() { int command_no = 1; for ( auto it = m_Commands.begin(); it != m_Commands.end(); it++) { const wxString command = *it; AppendText(wxString::Format("\n%d %s", command_no++, command.c_str())); } } #endif // wxUSE_GUI <|endoftext|>
<commit_before>#include <gtest/gtest.h> #include <string> #include <cpr/cprtypes.h> #include <cpr/ssl_options.h> #include "httpsServer.hpp" using namespace cpr; static HttpsServer* server; TEST(SslTests, HelloWorldTest) { std::this_thread::sleep_for(std::chrono::seconds(1)); std::string url = Url{server->GetBaseUrl() + "/hello.html"}; std::string baseDirPath = server->getBaseDirPath(); SslOptions sslOpts = Ssl( ssl::TLSv1{}, ssl::ALPN{false}, ssl::NPN{false}, ssl::CaPath{baseDirPath + "/ca.cer"}, ssl::CertFile{baseDirPath + "/client.cer"}, ssl::KeyFile{baseDirPath + "/client.key"}, ssl::VerifyPeer{false}, ssl::VerifyHost{false}, ssl::VerifyStatus{false}); Response response = cpr::Get(url, sslOpts, Timeout{5000}, Verbose{}); std::string expected_text = "Hello world!"; EXPECT_EQ(expected_text, response.text); EXPECT_EQ(url, response.url); EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]); EXPECT_EQ(200, response.status_code); EXPECT_EQ(ErrorCode::OK, response.error.code) << response.error.message; } int main(int argc, char** argv) { ::testing::InitGoogleTest(&argc, argv); std::string baseDirPath = "."; server = new HttpsServer(std::move(baseDirPath), "server.cer", "server.key"); ::testing::AddGlobalTestEnvironment(server); return RUN_ALL_TESTS(); } <commit_msg>Fixed ssl test cert location<commit_after>#include <gtest/gtest.h> #include <string> #include <cpr/cprtypes.h> #include <cpr/ssl_options.h> #include "httpsServer.hpp" using namespace cpr; static HttpsServer* server; TEST(SslTests, HelloWorldTest) { std::this_thread::sleep_for(std::chrono::seconds(1)); std::string url = Url{server->GetBaseUrl() + "/hello.html"}; std::string baseDirPath = server->getBaseDirPath(); SslOptions sslOpts = Ssl( ssl::TLSv1{}, ssl::ALPN{false}, ssl::NPN{false}, ssl::CaPath{baseDirPath + "/ca.cer"}, ssl::CertFile{baseDirPath + "/client.cer"}, ssl::KeyFile{baseDirPath + "/client.key"}, ssl::VerifyPeer{false}, ssl::VerifyHost{false}, ssl::VerifyStatus{false}); Response response = cpr::Get(url, sslOpts, Timeout{5000}, Verbose{}); std::string expected_text = "Hello world!"; EXPECT_EQ(expected_text, response.text); EXPECT_EQ(url, response.url); EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]); EXPECT_EQ(200, response.status_code); EXPECT_EQ(ErrorCode::OK, response.error.code) << response.error.message; } int main(int argc, char** argv) { ::testing::InitGoogleTest(&argc, argv); std::string baseDirPath = "build/bin"; std::string serverCertPath = baseDirPath + "/server.cer"; std::string serverKeyPath = baseDirPath + "/server.key"; server = new HttpsServer(std::move(baseDirPath), std::move(serverCertPath), std::move(serverKeyPath)); ::testing::AddGlobalTestEnvironment(server); return RUN_ALL_TESTS(); } <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: vtkDataSetReader.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 1993-2001 Ken Martin, Will Schroeder, Bill Lorensen 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 name of Ken Martin, Will Schroeder, or Bill Lorensen nor the names of any contributors may be used to endorse or promote products derived from this software without specific prior written permission. * Modified source versions must be plainly marked as such, and must not be misrepresented as being the original software. 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 AUTHORS 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 "vtkDataSetReader.h" #include "vtkPolyDataReader.h" #include "vtkStructuredPointsReader.h" #include "vtkStructuredGridReader.h" #include "vtkRectilinearGridReader.h" #include "vtkUnstructuredGridReader.h" #include "vtkObjectFactory.h" //-------------------------------------------------------------------------- vtkDataSetReader* vtkDataSetReader::New() { // First try to create the object from the vtkObjectFactory vtkObject* ret = vtkObjectFactory::CreateInstance("vtkDataSetReader"); if(ret) { return (vtkDataSetReader*)ret; } // If the factory was unable to create the object, then create it here. return new vtkDataSetReader; } vtkDataSetReader::vtkDataSetReader() { } vtkDataSetReader::~vtkDataSetReader() { } vtkDataSet * vtkDataSetReader::GetOutput() { // check to see if an execute is necessary. if (this->Outputs && this->Outputs[0] && this->Outputs[0]->GetUpdateTime() > this->GetMTime()) { return (vtkDataSet *)(this->Outputs[0]); } // The filename might have changed (changing the output). // We need to re execute. if (this->GetFileName() == NULL && (this->GetReadFromInputString() == 0 || this->GetInputString() == NULL)) { vtkWarningMacro(<< "FileName must be set"); return (vtkDataSet *) NULL; } this->Execute(); if (this->Outputs == NULL) { return NULL; } else { return (vtkDataSet *)this->Outputs[0]; } } void vtkDataSetReader::Execute() { char line[256]; vtkDataObject *output; vtkDebugMacro(<<"Reading vtk dataset..."); if (!this->OpenVTKFile() || !this->ReadHeader()) { return; } // Determine dataset type // if (!this->ReadString(line)) { vtkErrorMacro(<< "Premature EOF reading dataset keyword"); return; } if ( !strncmp(this->LowerCase(line),"dataset",(unsigned long)7) ) { // See if type is recognized. // if (!this->ReadString(line)) { vtkErrorMacro(<< "Premature EOF reading type"); this->CloseVTKFile (); return; } this->CloseVTKFile(); if ( ! strncmp(this->LowerCase(line),"polydata",8) ) { vtkPolyDataReader *preader = vtkPolyDataReader::New(); // Can we use the old output? output = this->Outputs ? this->Outputs[0] : NULL; if (output && strcmp(output->GetClassName(), "vtkPolyData") == 0) { preader->SetOutput((vtkPolyData *)(output)); } preader->SetFileName(this->GetFileName()); preader->SetInputString(this->GetInputString(), this->GetInputStringLength()); preader->SetReadFromInputString(this->GetReadFromInputString()); preader->SetScalarsName(this->GetScalarsName()); preader->SetVectorsName(this->GetVectorsName()); preader->SetNormalsName(this->GetNormalsName()); preader->SetTensorsName(this->GetTensorsName()); preader->SetTCoordsName(this->GetTCoordsName()); preader->SetLookupTableName(this->GetLookupTableName()); preader->SetFieldDataName(this->GetFieldDataName()); preader->Update(); // whether we used the old output or not, we need to set the output. this->SetNthOutput(0, preader->GetOutput()); preader->Delete(); } else if ( ! strncmp(line,"structured_points",17) ) { vtkStructuredPointsReader *preader = vtkStructuredPointsReader::New(); // Can we use the old output? output = this->Outputs ? this->Outputs[0] : NULL; if (output && strcmp(output->GetClassName(), "vtkStructuredPoints") == 0) { preader->SetOutput((vtkStructuredPoints *)(output)); } preader->SetFileName(this->GetFileName()); preader->SetInputString(this->GetInputString(), this->GetInputStringLength()); preader->SetReadFromInputString(this->GetReadFromInputString()); preader->SetScalarsName(this->GetScalarsName()); preader->SetVectorsName(this->GetVectorsName()); preader->SetNormalsName(this->GetNormalsName()); preader->SetTensorsName(this->GetTensorsName()); preader->SetTCoordsName(this->GetTCoordsName()); preader->SetLookupTableName(this->GetLookupTableName()); preader->SetFieldDataName(this->GetFieldDataName()); preader->Update(); // whether we used the old output or not, we need to set the output. this->SetNthOutput(0, preader->GetOutput()); preader->Delete(); } else if ( ! strncmp(line,"structured_grid",15) ) { vtkStructuredGridReader *preader = vtkStructuredGridReader::New(); // Can we use the old output? output = this->Outputs ? this->Outputs[0] : NULL; if (output && strcmp(output->GetClassName(), "vtkStructuredGrid") == 0) { preader->SetOutput((vtkStructuredGrid *)(output)); } preader->SetFileName(this->GetFileName()); preader->SetInputString(this->GetInputString(), this->GetInputStringLength()); preader->SetReadFromInputString(this->GetReadFromInputString()); preader->SetScalarsName(this->GetScalarsName()); preader->SetVectorsName(this->GetVectorsName()); preader->SetNormalsName(this->GetNormalsName()); preader->SetTensorsName(this->GetTensorsName()); preader->SetTCoordsName(this->GetTCoordsName()); preader->SetLookupTableName(this->GetLookupTableName()); preader->SetFieldDataName(this->GetFieldDataName()); preader->Update(); // whether we used the old output or not, we need to set the output. this->SetNthOutput(0, preader->GetOutput()); preader->Delete(); } else if ( ! strncmp(line,"rectilinear_grid",16) ) { vtkRectilinearGridReader *preader = vtkRectilinearGridReader::New(); // Can we use the old output? output = this->Outputs ? this->Outputs[0] : NULL; if (output && strcmp(output->GetClassName(), "vtkRectilinearGrid") == 0) { preader->SetOutput((vtkRectilinearGrid *)(output)); } preader->SetFileName(this->GetFileName()); preader->SetInputString(this->GetInputString(), this->GetInputStringLength()); preader->SetReadFromInputString(this->GetReadFromInputString()); preader->SetScalarsName(this->GetScalarsName()); preader->SetVectorsName(this->GetVectorsName()); preader->SetNormalsName(this->GetNormalsName()); preader->SetTensorsName(this->GetTensorsName()); preader->SetTCoordsName(this->GetTCoordsName()); preader->SetLookupTableName(this->GetLookupTableName()); preader->SetFieldDataName(this->GetFieldDataName()); preader->Update(); // whether we used the old output or not, we need to set the output. this->SetNthOutput(0, preader->GetOutput()); preader->Delete(); } else if ( ! strncmp(line,"unstructured_grid",17) ) { vtkUnstructuredGridReader *preader = vtkUnstructuredGridReader::New(); // Can we use the old output? output = this->Outputs ? this->Outputs[0] : NULL; if (output && strcmp(output->GetClassName(), "vtkUnstructuredGrid") == 0) { preader->SetOutput((vtkUnstructuredGrid *)(output)); } preader->SetFileName(this->GetFileName()); preader->SetInputString(this->GetInputString(), this->GetInputStringLength()); preader->SetReadFromInputString(this->GetReadFromInputString()); preader->SetScalarsName(this->GetScalarsName()); preader->SetVectorsName(this->GetVectorsName()); preader->SetNormalsName(this->GetNormalsName()); preader->SetTensorsName(this->GetTensorsName()); preader->SetTCoordsName(this->GetTCoordsName()); preader->SetLookupTableName(this->GetLookupTableName()); preader->SetFieldDataName(this->GetFieldDataName()); preader->Update(); // whether we used the old output or not, we need to set the output. this->SetNthOutput(0, preader->GetOutput()); preader->Delete(); } else { vtkErrorMacro(<< "Cannot read dataset type: " << line); return; } } else if ( !strncmp(this->LowerCase(line),"field",(unsigned long)5) ) { vtkErrorMacro(<<"This object can only read datasets, not fields"); } else { vtkErrorMacro(<<"Expecting DATASET keyword, got " << line << " instead"); } return; } vtkPolyData *vtkDataSetReader::GetPolyDataOutput() { return vtkPolyData::SafeDownCast(this->GetOutput()); } vtkStructuredPoints *vtkDataSetReader::GetStructuredPointsOutput() { return vtkStructuredPoints::SafeDownCast(this->GetOutput()); } vtkStructuredGrid *vtkDataSetReader::GetStructuredGridOutput() { return vtkStructuredGrid::SafeDownCast(this->GetOutput()); } vtkUnstructuredGrid *vtkDataSetReader::GetUnstructuredGridOutput() { return vtkUnstructuredGrid::SafeDownCast(this->GetOutput()); } vtkRectilinearGrid *vtkDataSetReader::GetRectilinearGridOutput() { return vtkRectilinearGrid::SafeDownCast(this->GetOutput()); } //---------------------------------------------------------------------------- void vtkDataSetReader::Update() { if (this->GetOutput()) { this->GetOutput()->Update(); } } void vtkDataSetReader::PrintSelf(ostream& os, vtkIndent indent) { vtkDataReader::PrintSelf(os,indent); } <commit_msg>Setting the output to NULL and back again each execute modifies the reader. This is bad (my own mistake years ago) so I changed it back the way it used to be.<commit_after>/*========================================================================= Program: Visualization Toolkit Module: vtkDataSetReader.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 1993-2001 Ken Martin, Will Schroeder, Bill Lorensen 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 name of Ken Martin, Will Schroeder, or Bill Lorensen nor the names of any contributors may be used to endorse or promote products derived from this software without specific prior written permission. * Modified source versions must be plainly marked as such, and must not be misrepresented as being the original software. 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 AUTHORS 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 "vtkDataSetReader.h" #include "vtkPolyDataReader.h" #include "vtkStructuredPointsReader.h" #include "vtkStructuredGridReader.h" #include "vtkRectilinearGridReader.h" #include "vtkUnstructuredGridReader.h" #include "vtkObjectFactory.h" //-------------------------------------------------------------------------- vtkDataSetReader* vtkDataSetReader::New() { // First try to create the object from the vtkObjectFactory vtkObject* ret = vtkObjectFactory::CreateInstance("vtkDataSetReader"); if(ret) { return (vtkDataSetReader*)ret; } // If the factory was unable to create the object, then create it here. return new vtkDataSetReader; } vtkDataSetReader::vtkDataSetReader() { } vtkDataSetReader::~vtkDataSetReader() { } vtkDataSet * vtkDataSetReader::GetOutput() { // check to see if an execute is necessary. if (this->Outputs && this->Outputs[0] && this->Outputs[0]->GetUpdateTime() > this->GetMTime()) { return (vtkDataSet *)(this->Outputs[0]); } // The filename might have changed (changing the output). // We need to re execute. if (this->GetFileName() == NULL && (this->GetReadFromInputString() == 0 || this->GetInputString() == NULL)) { vtkWarningMacro(<< "FileName must be set"); return (vtkDataSet *) NULL; } this->Execute(); if (this->Outputs == NULL) { return NULL; } else { return (vtkDataSet *)this->Outputs[0]; } } void vtkDataSetReader::Execute() { char line[256]; vtkDataObject *output; vtkDebugMacro(<<"Reading vtk dataset..."); if (!this->OpenVTKFile() || !this->ReadHeader()) { return; } // Determine dataset type // if (!this->ReadString(line)) { vtkErrorMacro(<< "Premature EOF reading dataset keyword"); return; } if ( !strncmp(this->LowerCase(line),"dataset",(unsigned long)7) ) { // See if type is recognized. // if (!this->ReadString(line)) { vtkErrorMacro(<< "Premature EOF reading type"); this->CloseVTKFile (); return; } this->CloseVTKFile(); if ( ! strncmp(this->LowerCase(line),"polydata",8) ) { vtkPolyDataReader *preader = vtkPolyDataReader::New(); preader->SetFileName(this->GetFileName()); preader->SetInputString(this->GetInputString(), this->GetInputStringLength()); preader->SetReadFromInputString(this->GetReadFromInputString()); preader->SetScalarsName(this->GetScalarsName()); preader->SetVectorsName(this->GetVectorsName()); preader->SetNormalsName(this->GetNormalsName()); preader->SetTensorsName(this->GetTensorsName()); preader->SetTCoordsName(this->GetTCoordsName()); preader->SetLookupTableName(this->GetLookupTableName()); preader->SetFieldDataName(this->GetFieldDataName()); preader->Update(); // Can we use the old output? output = this->Outputs ? this->Outputs[0] : NULL; if (output && strcmp(output->GetClassName(), "vtkPolyData") == 0) { output->ShallowCopy(preader->GetOutput()); } else { this->SetNthOutput(0, preader->GetOutput()); } preader->Delete(); } else if ( ! strncmp(line,"structured_points",17) ) { vtkStructuredPointsReader *preader = vtkStructuredPointsReader::New(); preader->SetFileName(this->GetFileName()); preader->SetInputString(this->GetInputString(), this->GetInputStringLength()); preader->SetReadFromInputString(this->GetReadFromInputString()); preader->SetScalarsName(this->GetScalarsName()); preader->SetVectorsName(this->GetVectorsName()); preader->SetNormalsName(this->GetNormalsName()); preader->SetTensorsName(this->GetTensorsName()); preader->SetTCoordsName(this->GetTCoordsName()); preader->SetLookupTableName(this->GetLookupTableName()); preader->SetFieldDataName(this->GetFieldDataName()); preader->Update(); // Can we use the old output? output = this->Outputs ? this->Outputs[0] : NULL; if (output && strcmp(output->GetClassName(), "vtkStructuredPoints") == 0) { output->ShallowCopy(preader->GetOutput()); } else { this->SetNthOutput(0, preader->GetOutput()); } preader->Delete(); } else if ( ! strncmp(line,"structured_grid",15) ) { vtkStructuredGridReader *preader = vtkStructuredGridReader::New(); preader->SetFileName(this->GetFileName()); preader->SetInputString(this->GetInputString(), this->GetInputStringLength()); preader->SetReadFromInputString(this->GetReadFromInputString()); preader->SetScalarsName(this->GetScalarsName()); preader->SetVectorsName(this->GetVectorsName()); preader->SetNormalsName(this->GetNormalsName()); preader->SetTensorsName(this->GetTensorsName()); preader->SetTCoordsName(this->GetTCoordsName()); preader->SetLookupTableName(this->GetLookupTableName()); preader->SetFieldDataName(this->GetFieldDataName()); preader->Update(); // Can we use the old output? output = this->Outputs ? this->Outputs[0] : NULL; if (output && strcmp(output->GetClassName(), "vtkStructuredGrid") == 0) { output->ShallowCopy(preader->GetOutput()); } else { this->SetNthOutput(0, preader->GetOutput()); } preader->Delete(); } else if ( ! strncmp(line,"rectilinear_grid",16) ) { vtkRectilinearGridReader *preader = vtkRectilinearGridReader::New(); preader->SetFileName(this->GetFileName()); preader->SetInputString(this->GetInputString(), this->GetInputStringLength()); preader->SetReadFromInputString(this->GetReadFromInputString()); preader->SetScalarsName(this->GetScalarsName()); preader->SetVectorsName(this->GetVectorsName()); preader->SetNormalsName(this->GetNormalsName()); preader->SetTensorsName(this->GetTensorsName()); preader->SetTCoordsName(this->GetTCoordsName()); preader->SetLookupTableName(this->GetLookupTableName()); preader->SetFieldDataName(this->GetFieldDataName()); preader->Update(); // Can we use the old output? output = this->Outputs ? this->Outputs[0] : NULL; if (output && strcmp(output->GetClassName(), "vtkRectilinearGrid") == 0) { output->ShallowCopy(preader->GetOutput()); } else { this->SetNthOutput(0, preader->GetOutput()); } preader->Delete(); } else if ( ! strncmp(line,"unstructured_grid",17) ) { vtkUnstructuredGridReader *preader = vtkUnstructuredGridReader::New(); preader->SetFileName(this->GetFileName()); preader->SetInputString(this->GetInputString(), this->GetInputStringLength()); preader->SetReadFromInputString(this->GetReadFromInputString()); preader->SetScalarsName(this->GetScalarsName()); preader->SetVectorsName(this->GetVectorsName()); preader->SetNormalsName(this->GetNormalsName()); preader->SetTensorsName(this->GetTensorsName()); preader->SetTCoordsName(this->GetTCoordsName()); preader->SetLookupTableName(this->GetLookupTableName()); preader->SetFieldDataName(this->GetFieldDataName()); preader->Update(); // Can we use the old output? output = this->Outputs ? this->Outputs[0] : NULL; if (output && strcmp(output->GetClassName(), "vtkUnstructuredGrid") == 0) { output->ShallowCopy(preader->GetOutput()); } else { this->SetNthOutput(0, preader->GetOutput()); } preader->Delete(); } else { vtkErrorMacro(<< "Cannot read dataset type: " << line); return; } } else if ( !strncmp(this->LowerCase(line),"field",(unsigned long)5) ) { vtkErrorMacro(<<"This object can only read datasets, not fields"); } else { vtkErrorMacro(<<"Expecting DATASET keyword, got " << line << " instead"); } return; } vtkPolyData *vtkDataSetReader::GetPolyDataOutput() { return vtkPolyData::SafeDownCast(this->GetOutput()); } vtkStructuredPoints *vtkDataSetReader::GetStructuredPointsOutput() { return vtkStructuredPoints::SafeDownCast(this->GetOutput()); } vtkStructuredGrid *vtkDataSetReader::GetStructuredGridOutput() { return vtkStructuredGrid::SafeDownCast(this->GetOutput()); } vtkUnstructuredGrid *vtkDataSetReader::GetUnstructuredGridOutput() { return vtkUnstructuredGrid::SafeDownCast(this->GetOutput()); } vtkRectilinearGrid *vtkDataSetReader::GetRectilinearGridOutput() { return vtkRectilinearGrid::SafeDownCast(this->GetOutput()); } //---------------------------------------------------------------------------- void vtkDataSetReader::Update() { if (this->GetOutput()) { this->GetOutput()->Update(); } } void vtkDataSetReader::PrintSelf(ostream& os, vtkIndent indent) { vtkDataReader::PrintSelf(os,indent); } <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: vtkOpenGLTexture.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 1993-2001 Ken Martin, Will Schroeder, Bill Lorensen 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 name of Ken Martin, Will Schroeder, or Bill Lorensen nor the names of any contributors may be used to endorse or promote products derived from this software without specific prior written permission. * Modified source versions must be plainly marked as such, and must not be misrepresented as being the original software. 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 AUTHORS 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 <math.h> #include <string.h> #include "vtkRenderWindow.h" #ifdef __APPLE__ #include <OpenGL/gl.h> #include "vtkQuartzRenderWindow.h" #else #ifdef _WIN32 #include "vtkWin32OpenGLRenderWindow.h" #else #include "vtkOpenGLRenderWindow.h" #endif #endif #include "vtkOpenGLRenderer.h" #include "vtkOpenGLTexture.h" #ifndef VTK_IMPLEMENT_MESA_CXX #ifndef __APPLE__ #include <GL/gl.h> #endif #endif #include "vtkObjectFactory.h" #ifndef VTK_IMPLEMENT_MESA_CXX //------------------------------------------------------------------------------ vtkOpenGLTexture* vtkOpenGLTexture::New() { // First try to create the object from the vtkObjectFactory vtkObject* ret = vtkObjectFactory::CreateInstance("vtkOpenGLTexture"); if(ret) { return (vtkOpenGLTexture*)ret; } // If the factory was unable to create the object, then create it here. return new vtkOpenGLTexture; } #endif // Initializes an instance, generates a unique index. vtkOpenGLTexture::vtkOpenGLTexture() { this->Index = 0; this->RenderWindow = 0; } vtkOpenGLTexture::~vtkOpenGLTexture() { this->RenderWindow = NULL; } // Release the graphics resources used by this texture. void vtkOpenGLTexture::ReleaseGraphicsResources(vtkWindow *renWin) { if (this->Index && renWin) { ((vtkRenderWindow *) renWin)->MakeCurrent(); #ifdef GL_VERSION_1_1 // free any textures if (glIsTexture(this->Index)) { GLuint tempIndex; tempIndex = this->Index; // NOTE: Sun's OpenGL seems to require disabling of texture before delete glDisable(GL_TEXTURE_2D); glDeleteTextures(1, &tempIndex); } #else if (glIsList(this->Index)) { glDeleteLists(this->Index,1); } #endif } this->Index = 0; this->RenderWindow = NULL; this->Modified(); } // Implement base class method. void vtkOpenGLTexture::Load(vtkRenderer *ren) { GLenum format = GL_LUMINANCE; vtkImageData *input = this->GetInput(); // need to reload the texture if (this->GetMTime() > this->LoadTime.GetMTime() || input->GetMTime() > this->LoadTime.GetMTime() || (this->GetLookupTable() && this->GetLookupTable()->GetMTime () > this->LoadTime.GetMTime()) || ren->GetRenderWindow() != this->RenderWindow) { int bytesPerPixel; int *size; vtkScalars *scalars; unsigned char *dataPtr; int rowLength; unsigned char *resultData=NULL; int xsize, ysize; unsigned short xs,ys; GLuint tempIndex=0; // get some info size = input->GetDimensions(); scalars = (input->GetPointData())->GetScalars(); // make sure scalars are non null if (!scalars) { vtkErrorMacro(<< "No scalar values found for texture input!"); return; } bytesPerPixel = scalars->GetNumberOfComponents(); // make sure using unsigned char data of color scalars type if (this->MapColorScalarsThroughLookupTable || scalars->GetDataType() != VTK_UNSIGNED_CHAR ) { dataPtr = this->MapScalarsToColors (scalars); bytesPerPixel = 4; } else { dataPtr = ((vtkUnsignedCharArray *)scalars->GetData())->GetPointer(0); } // we only support 2d texture maps right now // so one of the three sizes must be 1, but it // could be any of them, so lets find it if (size[0] == 1) { xsize = size[1]; ysize = size[2]; } else { xsize = size[0]; if (size[1] == 1) { ysize = size[2]; } else { ysize = size[1]; if (size[2] != 1) { vtkErrorMacro(<< "3D texture maps currently are not supported!"); return; } } } // xsize and ysize must be a power of 2 in OpenGL xs = (unsigned short)xsize; ys = (unsigned short)ysize; while (!(xs & 0x01)) { xs = xs >> 1; } while (!(ys & 0x01)) { ys = ys >> 1; } // -- decide whether the texture needs to be resampled -- bool resampleNeeded = false; // if not a power of two then resampling is required if ((xs > 1)||(ys > 1)) { resampleNeeded = true; } int maxDimGL; glGetIntegerv(GL_MAX_TEXTURE_SIZE,&maxDimGL); // if larger than permitted by the graphics library then must resample if ( xsize > maxDimGL || ysize > maxDimGL ) { vtkDebugMacro( "Texture too big for gl, maximum is " << maxDimGL); resampleNeeded = true; } if ( resampleNeeded ) { vtkDebugMacro(<< "Resampling texture to power of two for OpenGL"); resultData = this->ResampleToPowerOfTwo(xsize, ysize, dataPtr, bytesPerPixel); } // format the data so that it can be sent to opengl // each row must be a multiple of 4 bytes in length // the best idea is to make your size a multiple of 4 // so that this conversion will never be done. rowLength = ((xsize*bytesPerPixel +3 )/4)*4; if (rowLength == xsize*bytesPerPixel) { if ( resultData == NULL ) { resultData = dataPtr; } } else { int col; unsigned char *src,*dest; int srcLength; srcLength = xsize*bytesPerPixel; resultData = new unsigned char [rowLength*ysize]; src = dataPtr; dest = resultData; for (col = 0; col < ysize; col++) { memcpy(dest,src,srcLength); src += srcLength; dest += rowLength; } } // free any old display lists (from the old context) if (this->RenderWindow) { this->ReleaseGraphicsResources(this->RenderWindow); } this->RenderWindow = ren->GetRenderWindow(); // make the new context current before we mess with opengl this->RenderWindow->MakeCurrent(); // define a display list for this texture // get a unique display list id #ifdef GL_VERSION_1_1 glGenTextures(1, &tempIndex); this->Index = (long) tempIndex; glBindTexture(GL_TEXTURE_2D, this->Index); #else this->Index = glGenLists(1); glDeleteLists ((GLuint) this->Index, (GLsizei) 0); glNewList ((GLuint) this->Index, GL_COMPILE); #endif #ifdef VTK_USE_QUARTZ ((vtkQuartzRenderWindow *)(ren->GetRenderWindow()))->RegisterTextureResource(this->Index); #else #ifdef _WIN32 ((vtkWin32OpenGLRenderWindow *)(ren->GetRenderWindow()))->RegisterTextureResource( this->Index ); #else ((vtkOpenGLRenderWindow *)(ren->GetRenderWindow()))->RegisterTextureResource( this->Index ); #endif #endif if (this->Interpolate) { glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR ); } else { glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST ); glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST ); } if (this->Repeat) { glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT ); glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT ); } else { glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP ); glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP ); } int internalFormat = bytesPerPixel; switch (bytesPerPixel) { case 1: format = GL_LUMINANCE; break; case 2: format = GL_LUMINANCE_ALPHA; break; case 3: format = GL_RGB; break; case 4: format = GL_RGBA; break; } // if we are using OpenGL 1.1, you can force 32 or16 bit textures #ifdef GL_VERSION_1_1 if (this->Quality == VTK_TEXTURE_QUALITY_32BIT) { switch (bytesPerPixel) { case 1: internalFormat = GL_LUMINANCE8; break; case 2: internalFormat = GL_LUMINANCE8_ALPHA8; break; case 3: internalFormat = GL_RGB8; break; case 4: internalFormat = GL_RGBA8; break; } } else if (this->Quality == VTK_TEXTURE_QUALITY_16BIT) { switch (bytesPerPixel) { case 1: internalFormat = GL_LUMINANCE4; break; case 2: internalFormat = GL_LUMINANCE4_ALPHA4; break; case 3: internalFormat = GL_RGB4; break; case 4: internalFormat = GL_RGBA4; break; } } #endif glTexImage2D( GL_TEXTURE_2D, 0 , internalFormat, xsize, ysize, 0, format, GL_UNSIGNED_BYTE, (const GLvoid *)resultData ); #ifndef GL_VERSION_1_1 glEndList (); #endif // modify the load time to the current time this->LoadTime.Modified(); // free memory if (resultData != dataPtr) { delete [] resultData; } } // execute the display list that uses creates the texture #ifdef GL_VERSION_1_1 glBindTexture(GL_TEXTURE_2D, this->Index); #else glCallList ((GLuint) this->Index); #endif // don't accept fragments if they have zero opacity. this will stop the // zbuffer from be blocked by totally transparent texture fragments. glAlphaFunc (GL_GREATER, (GLclampf) 0); glEnable (GL_ALPHA_TEST); // now bind it glEnable(GL_TEXTURE_2D); } static int FindPowerOfTwo(int i) { int size; for ( i--, size=1; i > 0; size*=2 ) { i /= 2; } // [these lines added by Tim Hutton (implementing Joris Vanden Wyngaerd's suggestions)] // limit the size of the texture to the maximum allowed by OpenGL // (slightly more graceful than texture failing but not ideal) int maxDimGL; glGetIntegerv(GL_MAX_TEXTURE_SIZE,&maxDimGL); if ( size > maxDimGL ) { size = maxDimGL ; } // end of Tim's additions return size; } // Creates resampled unsigned char texture map that is a power of two in bith x and y. unsigned char *vtkOpenGLTexture::ResampleToPowerOfTwo(int &xs, int &ys, unsigned char *dptr, int bpp) { unsigned char *tptr, *p, *p1, *p2, *p3, *p4; int xsize, ysize, i, j, k, jOffset, iIdx, jIdx; float pcoords[3], hx, hy, rm, sm, w0, w1, w2, w3; xsize = FindPowerOfTwo(xs); ysize = FindPowerOfTwo(ys); hx = (float)(xs - 1.0) / (xsize - 1.0); hy = (float)(ys - 1.0) / (ysize - 1.0); tptr = p = new unsigned char[xsize*ysize*bpp]; //Resample from the previous image. Compute parametric coordinates and interpolate for (j=0; j < ysize; j++) { pcoords[1] = j*hy; jIdx = (int)pcoords[1]; if ( jIdx >= (ys-1) ) //make sure to interpolate correctly at edge { jIdx = ys - 2; pcoords[1] = 1.0; } else { pcoords[1] = pcoords[1] - jIdx; } jOffset = jIdx*xs; sm = 1.0 - pcoords[1]; for (i=0; i < xsize; i++) { pcoords[0] = i*hx; iIdx = (int)pcoords[0]; if ( iIdx >= (xs-1) ) { iIdx = xs - 2; pcoords[0] = 1.0; } else { pcoords[0] = pcoords[0] - iIdx; } rm = 1.0 - pcoords[0]; // Get pointers to 4 surrounding pixels p1 = dptr + bpp*(iIdx + jOffset); p2 = p1 + bpp; p3 = p1 + bpp*xs; p4 = p3 + bpp; // Compute interpolation weights interpolate components w0 = rm*sm; w1 = pcoords[0]*sm; w2 = rm*pcoords[1]; w3 = pcoords[0]*pcoords[1]; for (k=0; k < bpp; k++) { *p++ = (unsigned char) (p1[k]*w0 + p2[k]*w1 + p3[k]*w2 + p4[k]*w3); } } } xs = xsize; ys = ysize; return tptr; } <commit_msg>ERR: avoiding use of bool...<commit_after>/*========================================================================= Program: Visualization Toolkit Module: vtkOpenGLTexture.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 1993-2001 Ken Martin, Will Schroeder, Bill Lorensen 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 name of Ken Martin, Will Schroeder, or Bill Lorensen nor the names of any contributors may be used to endorse or promote products derived from this software without specific prior written permission. * Modified source versions must be plainly marked as such, and must not be misrepresented as being the original software. 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 AUTHORS 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 <math.h> #include <string.h> #include "vtkRenderWindow.h" #ifdef __APPLE__ #include <OpenGL/gl.h> #include "vtkQuartzRenderWindow.h" #else #ifdef _WIN32 #include "vtkWin32OpenGLRenderWindow.h" #else #include "vtkOpenGLRenderWindow.h" #endif #endif #include "vtkOpenGLRenderer.h" #include "vtkOpenGLTexture.h" #ifndef VTK_IMPLEMENT_MESA_CXX #ifndef __APPLE__ #include <GL/gl.h> #endif #endif #include "vtkObjectFactory.h" #ifndef VTK_IMPLEMENT_MESA_CXX //------------------------------------------------------------------------------ vtkOpenGLTexture* vtkOpenGLTexture::New() { // First try to create the object from the vtkObjectFactory vtkObject* ret = vtkObjectFactory::CreateInstance("vtkOpenGLTexture"); if(ret) { return (vtkOpenGLTexture*)ret; } // If the factory was unable to create the object, then create it here. return new vtkOpenGLTexture; } #endif // Initializes an instance, generates a unique index. vtkOpenGLTexture::vtkOpenGLTexture() { this->Index = 0; this->RenderWindow = 0; } vtkOpenGLTexture::~vtkOpenGLTexture() { this->RenderWindow = NULL; } // Release the graphics resources used by this texture. void vtkOpenGLTexture::ReleaseGraphicsResources(vtkWindow *renWin) { if (this->Index && renWin) { ((vtkRenderWindow *) renWin)->MakeCurrent(); #ifdef GL_VERSION_1_1 // free any textures if (glIsTexture(this->Index)) { GLuint tempIndex; tempIndex = this->Index; // NOTE: Sun's OpenGL seems to require disabling of texture before delete glDisable(GL_TEXTURE_2D); glDeleteTextures(1, &tempIndex); } #else if (glIsList(this->Index)) { glDeleteLists(this->Index,1); } #endif } this->Index = 0; this->RenderWindow = NULL; this->Modified(); } // Implement base class method. void vtkOpenGLTexture::Load(vtkRenderer *ren) { GLenum format = GL_LUMINANCE; vtkImageData *input = this->GetInput(); // need to reload the texture if (this->GetMTime() > this->LoadTime.GetMTime() || input->GetMTime() > this->LoadTime.GetMTime() || (this->GetLookupTable() && this->GetLookupTable()->GetMTime () > this->LoadTime.GetMTime()) || ren->GetRenderWindow() != this->RenderWindow) { int bytesPerPixel; int *size; vtkScalars *scalars; unsigned char *dataPtr; int rowLength; unsigned char *resultData=NULL; int xsize, ysize; unsigned short xs,ys; GLuint tempIndex=0; // get some info size = input->GetDimensions(); scalars = (input->GetPointData())->GetScalars(); // make sure scalars are non null if (!scalars) { vtkErrorMacro(<< "No scalar values found for texture input!"); return; } bytesPerPixel = scalars->GetNumberOfComponents(); // make sure using unsigned char data of color scalars type if (this->MapColorScalarsThroughLookupTable || scalars->GetDataType() != VTK_UNSIGNED_CHAR ) { dataPtr = this->MapScalarsToColors (scalars); bytesPerPixel = 4; } else { dataPtr = ((vtkUnsignedCharArray *)scalars->GetData())->GetPointer(0); } // we only support 2d texture maps right now // so one of the three sizes must be 1, but it // could be any of them, so lets find it if (size[0] == 1) { xsize = size[1]; ysize = size[2]; } else { xsize = size[0]; if (size[1] == 1) { ysize = size[2]; } else { ysize = size[1]; if (size[2] != 1) { vtkErrorMacro(<< "3D texture maps currently are not supported!"); return; } } } // xsize and ysize must be a power of 2 in OpenGL xs = (unsigned short)xsize; ys = (unsigned short)ysize; while (!(xs & 0x01)) { xs = xs >> 1; } while (!(ys & 0x01)) { ys = ys >> 1; } // -- decide whether the texture needs to be resampled -- int resampleNeeded = 0; // if not a power of two then resampling is required if ((xs > 1)||(ys > 1)) { resampleNeeded = 1; } int maxDimGL; glGetIntegerv(GL_MAX_TEXTURE_SIZE,&maxDimGL); // if larger than permitted by the graphics library then must resample if ( xsize > maxDimGL || ysize > maxDimGL ) { vtkDebugMacro( "Texture too big for gl, maximum is " << maxDimGL); resampleNeeded = 1; } if ( resampleNeeded ) { vtkDebugMacro(<< "Resampling texture to power of two for OpenGL"); resultData = this->ResampleToPowerOfTwo(xsize, ysize, dataPtr, bytesPerPixel); } // format the data so that it can be sent to opengl // each row must be a multiple of 4 bytes in length // the best idea is to make your size a multiple of 4 // so that this conversion will never be done. rowLength = ((xsize*bytesPerPixel +3 )/4)*4; if (rowLength == xsize*bytesPerPixel) { if ( resultData == NULL ) { resultData = dataPtr; } } else { int col; unsigned char *src,*dest; int srcLength; srcLength = xsize*bytesPerPixel; resultData = new unsigned char [rowLength*ysize]; src = dataPtr; dest = resultData; for (col = 0; col < ysize; col++) { memcpy(dest,src,srcLength); src += srcLength; dest += rowLength; } } // free any old display lists (from the old context) if (this->RenderWindow) { this->ReleaseGraphicsResources(this->RenderWindow); } this->RenderWindow = ren->GetRenderWindow(); // make the new context current before we mess with opengl this->RenderWindow->MakeCurrent(); // define a display list for this texture // get a unique display list id #ifdef GL_VERSION_1_1 glGenTextures(1, &tempIndex); this->Index = (long) tempIndex; glBindTexture(GL_TEXTURE_2D, this->Index); #else this->Index = glGenLists(1); glDeleteLists ((GLuint) this->Index, (GLsizei) 0); glNewList ((GLuint) this->Index, GL_COMPILE); #endif #ifdef VTK_USE_QUARTZ ((vtkQuartzRenderWindow *)(ren->GetRenderWindow()))->RegisterTextureResource(this->Index); #else #ifdef _WIN32 ((vtkWin32OpenGLRenderWindow *)(ren->GetRenderWindow()))->RegisterTextureResource( this->Index ); #else ((vtkOpenGLRenderWindow *)(ren->GetRenderWindow()))->RegisterTextureResource( this->Index ); #endif #endif if (this->Interpolate) { glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR ); } else { glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST ); glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST ); } if (this->Repeat) { glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT ); glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT ); } else { glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP ); glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP ); } int internalFormat = bytesPerPixel; switch (bytesPerPixel) { case 1: format = GL_LUMINANCE; break; case 2: format = GL_LUMINANCE_ALPHA; break; case 3: format = GL_RGB; break; case 4: format = GL_RGBA; break; } // if we are using OpenGL 1.1, you can force 32 or16 bit textures #ifdef GL_VERSION_1_1 if (this->Quality == VTK_TEXTURE_QUALITY_32BIT) { switch (bytesPerPixel) { case 1: internalFormat = GL_LUMINANCE8; break; case 2: internalFormat = GL_LUMINANCE8_ALPHA8; break; case 3: internalFormat = GL_RGB8; break; case 4: internalFormat = GL_RGBA8; break; } } else if (this->Quality == VTK_TEXTURE_QUALITY_16BIT) { switch (bytesPerPixel) { case 1: internalFormat = GL_LUMINANCE4; break; case 2: internalFormat = GL_LUMINANCE4_ALPHA4; break; case 3: internalFormat = GL_RGB4; break; case 4: internalFormat = GL_RGBA4; break; } } #endif glTexImage2D( GL_TEXTURE_2D, 0 , internalFormat, xsize, ysize, 0, format, GL_UNSIGNED_BYTE, (const GLvoid *)resultData ); #ifndef GL_VERSION_1_1 glEndList (); #endif // modify the load time to the current time this->LoadTime.Modified(); // free memory if (resultData != dataPtr) { delete [] resultData; } } // execute the display list that uses creates the texture #ifdef GL_VERSION_1_1 glBindTexture(GL_TEXTURE_2D, this->Index); #else glCallList ((GLuint) this->Index); #endif // don't accept fragments if they have zero opacity. this will stop the // zbuffer from be blocked by totally transparent texture fragments. glAlphaFunc (GL_GREATER, (GLclampf) 0); glEnable (GL_ALPHA_TEST); // now bind it glEnable(GL_TEXTURE_2D); } static int FindPowerOfTwo(int i) { int size; for ( i--, size=1; i > 0; size*=2 ) { i /= 2; } // [these lines added by Tim Hutton (implementing Joris Vanden Wyngaerd's suggestions)] // limit the size of the texture to the maximum allowed by OpenGL // (slightly more graceful than texture failing but not ideal) int maxDimGL; glGetIntegerv(GL_MAX_TEXTURE_SIZE,&maxDimGL); if ( size > maxDimGL ) { size = maxDimGL ; } // end of Tim's additions return size; } // Creates resampled unsigned char texture map that is a power of two in bith x and y. unsigned char *vtkOpenGLTexture::ResampleToPowerOfTwo(int &xs, int &ys, unsigned char *dptr, int bpp) { unsigned char *tptr, *p, *p1, *p2, *p3, *p4; int xsize, ysize, i, j, k, jOffset, iIdx, jIdx; float pcoords[3], hx, hy, rm, sm, w0, w1, w2, w3; xsize = FindPowerOfTwo(xs); ysize = FindPowerOfTwo(ys); hx = (float)(xs - 1.0) / (xsize - 1.0); hy = (float)(ys - 1.0) / (ysize - 1.0); tptr = p = new unsigned char[xsize*ysize*bpp]; //Resample from the previous image. Compute parametric coordinates and interpolate for (j=0; j < ysize; j++) { pcoords[1] = j*hy; jIdx = (int)pcoords[1]; if ( jIdx >= (ys-1) ) //make sure to interpolate correctly at edge { jIdx = ys - 2; pcoords[1] = 1.0; } else { pcoords[1] = pcoords[1] - jIdx; } jOffset = jIdx*xs; sm = 1.0 - pcoords[1]; for (i=0; i < xsize; i++) { pcoords[0] = i*hx; iIdx = (int)pcoords[0]; if ( iIdx >= (xs-1) ) { iIdx = xs - 2; pcoords[0] = 1.0; } else { pcoords[0] = pcoords[0] - iIdx; } rm = 1.0 - pcoords[0]; // Get pointers to 4 surrounding pixels p1 = dptr + bpp*(iIdx + jOffset); p2 = p1 + bpp; p3 = p1 + bpp*xs; p4 = p3 + bpp; // Compute interpolation weights interpolate components w0 = rm*sm; w1 = pcoords[0]*sm; w2 = rm*pcoords[1]; w3 = pcoords[0]*pcoords[1]; for (k=0; k < bpp; k++) { *p++ = (unsigned char) (p1[k]*w0 + p2[k]*w1 + p3[k]*w2 + p4[k]*w3); } } } xs = xsize; ys = ysize; return tptr; } <|endoftext|>
<commit_before>/************************************************************************** * * Copyright 2015 VMware, Inc * 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 "qubjson.h" #include <QDebug> #include <QVariant> #include <QJsonArray> #include "ubjson.hpp" using namespace ubjson; static Marker readMarker(QDataStream &stream) { quint8 byte; stream >> byte; return static_cast<ubjson::Marker>(byte); } static int8_t readInt8(QDataStream &stream) { qint8 i; stream >> i; return i; } static uint8_t readUInt8(QDataStream &stream) { quint8 u; stream >> u; return u; } static int16_t readInt16(QDataStream &stream) { qint16 i; stream >> i; return i; } static int32_t readInt32(QDataStream &stream) { qint32 i; stream >> i; return i; } static int64_t readInt64(QDataStream &stream) { qint64 i; stream >> i; return i; } static float readFloat32(QDataStream &stream) { float f; stream.setFloatingPointPrecision(QDataStream::SinglePrecision); stream >> f; return f; } static float readFloat64(QDataStream &stream) { double f; stream.setFloatingPointPrecision(QDataStream::DoublePrecision); stream >> f; return f; } static size_t readSize(QDataStream &stream) { Marker type = readMarker(stream); switch (type) { case MARKER_INT8: return readInt8(stream); case MARKER_UINT8: return readUInt8(stream); case MARKER_INT16: return readInt16(stream); case MARKER_INT32: return readInt32(stream); case MARKER_INT64: return readInt64(stream); default: Q_UNIMPLEMENTED(); return 0; } } static QString readString(QDataStream &stream) { size_t size = readSize(stream); char *buf = new char [size]; stream.readRawData(buf, size); QString str = QString::fromLocal8Bit(buf, size); free(buf); return str; } static QVariant readVariant(QDataStream &stream, Marker type); static QVariant readArray(QDataStream &stream) { Marker marker = readMarker(stream); if (marker == MARKER_TYPE) { Marker type = readMarker(stream); Q_ASSERT(type == MARKER_UINT8); marker = readMarker(stream); Q_ASSERT(marker == MARKER_COUNT); size_t count = readSize(stream); QByteArray array(count, Qt::Uninitialized); int read = stream.readRawData(array.data(), count); Q_ASSERT(read == count); marker = readMarker(stream); Q_ASSERT(marker == MARKER_ARRAY_END); return array; } else { Q_ASSERT(marker != MARKER_COUNT); QVariantList array; while (marker != MARKER_ARRAY_END) { QVariant value = readVariant(stream, marker); array.append(value); marker = readMarker(stream); } return array; } } static QVariantMap readObject(QDataStream &stream) { QVariantMap object; Marker marker = readMarker(stream); while (marker != MARKER_OBJECT_END) { Q_ASSERT(marker == MARKER_STRING); QString name = readString(stream); marker = readMarker(stream); QVariant value = readVariant(stream, marker); object[name] = value; marker = readMarker(stream); } return object; } static QVariant readVariant(QDataStream &stream, Marker type) { switch (type) { case MARKER_NULL: return QVariant(); case MARKER_NOOP: return QVariant(); case MARKER_TRUE: return true; case MARKER_FALSE: return false; case MARKER_INT8: return readInt8(stream); case MARKER_UINT8: return readUInt8(stream); case MARKER_INT16: return readInt16(stream); case MARKER_INT32: return readInt32(stream); case MARKER_INT64: return (qlonglong)readInt64(stream); case MARKER_FLOAT32: return readFloat32(stream); case MARKER_FLOAT64: return readFloat64(stream); case MARKER_HIGH_PRECISION: Q_UNIMPLEMENTED(); return QVariant(); case MARKER_CHAR: Q_UNIMPLEMENTED(); return QVariant(); case MARKER_STRING: return readString(stream); case MARKER_ARRAY_BEGIN: return readArray(stream); case MARKER_OBJECT_BEGIN: return readObject(stream); case MARKER_ARRAY_END: case MARKER_OBJECT_END: case MARKER_TYPE: case MARKER_COUNT: default: Q_ASSERT(0); return QVariant(); } } QVariantMap decodeUBJSONObject(QIODevice *io) { QDataStream stream(io); stream.setByteOrder(QDataStream::BigEndian); Marker marker = readMarker(stream); Q_ASSERT(marker == MARKER_OBJECT_BEGIN); return readObject(stream); } <commit_msg>gui: Ensure QDataStream is included.<commit_after>/************************************************************************** * * Copyright 2015 VMware, Inc * 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 "qubjson.h" #include <QDebug> #include <QVariant> #include <QJsonArray> #include <QDataStream> #include "ubjson.hpp" using namespace ubjson; static Marker readMarker(QDataStream &stream) { quint8 byte; stream >> byte; return static_cast<ubjson::Marker>(byte); } static int8_t readInt8(QDataStream &stream) { qint8 i; stream >> i; return i; } static uint8_t readUInt8(QDataStream &stream) { quint8 u; stream >> u; return u; } static int16_t readInt16(QDataStream &stream) { qint16 i; stream >> i; return i; } static int32_t readInt32(QDataStream &stream) { qint32 i; stream >> i; return i; } static int64_t readInt64(QDataStream &stream) { qint64 i; stream >> i; return i; } static float readFloat32(QDataStream &stream) { float f; stream.setFloatingPointPrecision(QDataStream::SinglePrecision); stream >> f; return f; } static float readFloat64(QDataStream &stream) { double f; stream.setFloatingPointPrecision(QDataStream::DoublePrecision); stream >> f; return f; } static size_t readSize(QDataStream &stream) { Marker type = readMarker(stream); switch (type) { case MARKER_INT8: return readInt8(stream); case MARKER_UINT8: return readUInt8(stream); case MARKER_INT16: return readInt16(stream); case MARKER_INT32: return readInt32(stream); case MARKER_INT64: return readInt64(stream); default: Q_UNIMPLEMENTED(); return 0; } } static QString readString(QDataStream &stream) { size_t size = readSize(stream); char *buf = new char [size]; stream.readRawData(buf, size); QString str = QString::fromLocal8Bit(buf, size); free(buf); return str; } static QVariant readVariant(QDataStream &stream, Marker type); static QVariant readArray(QDataStream &stream) { Marker marker = readMarker(stream); if (marker == MARKER_TYPE) { Marker type = readMarker(stream); Q_ASSERT(type == MARKER_UINT8); marker = readMarker(stream); Q_ASSERT(marker == MARKER_COUNT); size_t count = readSize(stream); QByteArray array(count, Qt::Uninitialized); int read = stream.readRawData(array.data(), count); Q_ASSERT(read == count); marker = readMarker(stream); Q_ASSERT(marker == MARKER_ARRAY_END); return array; } else { Q_ASSERT(marker != MARKER_COUNT); QVariantList array; while (marker != MARKER_ARRAY_END) { QVariant value = readVariant(stream, marker); array.append(value); marker = readMarker(stream); } return array; } } static QVariantMap readObject(QDataStream &stream) { QVariantMap object; Marker marker = readMarker(stream); while (marker != MARKER_OBJECT_END) { Q_ASSERT(marker == MARKER_STRING); QString name = readString(stream); marker = readMarker(stream); QVariant value = readVariant(stream, marker); object[name] = value; marker = readMarker(stream); } return object; } static QVariant readVariant(QDataStream &stream, Marker type) { switch (type) { case MARKER_NULL: return QVariant(); case MARKER_NOOP: return QVariant(); case MARKER_TRUE: return true; case MARKER_FALSE: return false; case MARKER_INT8: return readInt8(stream); case MARKER_UINT8: return readUInt8(stream); case MARKER_INT16: return readInt16(stream); case MARKER_INT32: return readInt32(stream); case MARKER_INT64: return (qlonglong)readInt64(stream); case MARKER_FLOAT32: return readFloat32(stream); case MARKER_FLOAT64: return readFloat64(stream); case MARKER_HIGH_PRECISION: Q_UNIMPLEMENTED(); return QVariant(); case MARKER_CHAR: Q_UNIMPLEMENTED(); return QVariant(); case MARKER_STRING: return readString(stream); case MARKER_ARRAY_BEGIN: return readArray(stream); case MARKER_OBJECT_BEGIN: return readObject(stream); case MARKER_ARRAY_END: case MARKER_OBJECT_END: case MARKER_TYPE: case MARKER_COUNT: default: Q_ASSERT(0); return QVariant(); } } QVariantMap decodeUBJSONObject(QIODevice *io) { QDataStream stream(io); stream.setByteOrder(QDataStream::BigEndian); Marker marker = readMarker(stream); Q_ASSERT(marker == MARKER_OBJECT_BEGIN); return readObject(stream); } <|endoftext|>
<commit_before>/** * @doc The Vec class * * @copyright 2012-2013 David H. Bronke and Christopher S. Case * Licensed under the MIT license; see the LICENSE file for details. */ #include <cmath> #include <erl_nif.h> #include "angles.h" #include "Vec.h" /* ----------------------------------------------------------------------------------------------------------------- */ /* Some useful constants */ #define NORMALIZED_TOLERANCE 0.0000001 // -------------------------------------------------------------------------------------------------------------------- Vec::Vec() : x(0), y(0), z(0) { } // end Vec Vec::Vec(double x, double y, double z) : x(x), y(y), z(z) { } // end Vec // -------------------------------------------------------------------------------------------------------------------- // Operations that produce new `Vec` instances /// Perform cross product. Vec Vec::cross(const Vec& other) const { return Vec( y * other.z - z * other.y, -x * other.z + z * other.x, x * other.y - y * other.x ); } // end cross /// Returns a unit vector in the same direction as Vec. Vec Vec::unit() const { return Vec(*this).normalize(); } // end unit /// Gets the Yaw and Pitch required to point in the direction of the given vector. Vec Vec::hprAlong() const { Vec tempVec = unit(); double yaw = -atan2(tempVec.x, tempVec.y); double pitch = atan2(tempVec.z, sqrt(pow(tempVec.x, 2) + pow(tempVec.y, 2))); return Vec(rad2deg(yaw), rad2deg(pitch), 0); } // end hpr_to // As stated at http://courses.cms.caltech.edu/cs11/material/cpp/donnie/cpp-ops.html, // "Define your binary arithmetic operators using your compound assignment operators." #define BINARY_OP(OP, OTHER_TYPE) \ Vec Vec::operator OP(const OTHER_TYPE& other) const \ { return Vec(*this) OP##= other; } // Operator overloads (Vec <op> Vec) BINARY_OP(+, Vec) BINARY_OP(-, Vec) // Operator overloads (Vec <op> <other type>) BINARY_OP(*, double) BINARY_OP(*, int32_t) BINARY_OP(*, u_int32_t) BINARY_OP(*, int64_t) BINARY_OP(*, u_int64_t) BINARY_OP(/, double) BINARY_OP(/, int32_t) BINARY_OP(/, u_int32_t) BINARY_OP(/, int64_t) BINARY_OP(/, u_int64_t) // -------------------------------------------------------------------------------------------------------------------- // Operations that produce other values /// Perform dot product. double Vec::dot(const Vec& other) const { return x * other.x + y * other.y + z * other.z; } // end dot /// Returns the squared length of the vector. This is useful in some optimization cases, as it avoids a sqrt call. double Vec::squaredNorm() const { // Yes, these two are equivalent. //return dot(*this); return x * x + y * y + z * z; } // end squared_norm /// Returns the length of the vector. double Vec::norm() const { return sqrt(squaredNorm()); } // end norm /// Checks to see if this is a zero vector. bool Vec::isZero() const { return fabs(x) < NORMALIZED_TOLERANCE && fabs(y) < NORMALIZED_TOLERANCE && fabs(z) < NORMALIZED_TOLERANCE; } // end isZero /// Access components using Vec[idx] double Vec::operator [](const size_t& idx) const throw(BadIndex<size_t>) { if(idx > 2 || idx < 0) { throw BadIndex<size_t>(idx); } // end if return *(&x + idx); /* NOTE: This is equivalent to: switch(idx) { case 0: return x; case 1: return y; case 2: return z; default: throw BadIndex<size_t>(idx); } // end switch */ } // end operator [] // -------------------------------------------------------------------------------------------------------------------- // In-place modifications /// Changes the length of this vector so that it's a unit vector. Vec& Vec::normalize() { double sqrNorm = squaredNorm(); // Don't renormalize if we're already less than our tolerance away from being a unit vector. if(fabs(sqrNorm - 1) < NORMALIZED_TOLERANCE) { return *this; } // end if // Also don't renormalize if we're already less than our tolerance away from being a zero vector. if(sqrNorm < NORMALIZED_TOLERANCE) { return *this; } // end if return *this /= sqrt(sqrNorm); } // end normalize // Create a compound assignment operator overload that sets each component of the Vec to `this.coord OP other.coord`. #define COMP_ASSIGN_OP_ZIP(OP, OTHER_TYPE) \ Vec& Vec::operator OP##=(const OTHER_TYPE& other) \ { \ x OP##= other.x; \ y OP##= other.y; \ z OP##= other.z; \ return *this; \ } // Operator overloads (Vec <op> Vec) COMP_ASSIGN_OP_ZIP(+, Vec) COMP_ASSIGN_OP_ZIP(-, Vec) // Create a compound assignment operator overload that sets each component of the Vec to `this.coord OP other`. #define COMP_ASSIGN_OP_MAP(OP, OTHER_TYPE) \ Vec& Vec::operator OP##=(const OTHER_TYPE& other) \ { \ x OP##= other; \ y OP##= other; \ z OP##= other; \ return *this; \ } // Operator overloads (Vec <op>= <other type>) COMP_ASSIGN_OP_MAP(*, double) COMP_ASSIGN_OP_MAP(*, int32_t) COMP_ASSIGN_OP_MAP(*, u_int32_t) COMP_ASSIGN_OP_MAP(*, int64_t) COMP_ASSIGN_OP_MAP(*, u_int64_t) COMP_ASSIGN_OP_MAP(/, double) COMP_ASSIGN_OP_MAP(/, int32_t) COMP_ASSIGN_OP_MAP(/, u_int32_t) COMP_ASSIGN_OP_MAP(/, int64_t) COMP_ASSIGN_OP_MAP(/, u_int64_t) <commit_msg>Minor format fix.<commit_after>/** * @doc The Vec class * * @copyright 2012-2013 David H. Bronke and Christopher S. Case * Licensed under the MIT license; see the LICENSE file for details. */ #include <cmath> #include <erl_nif.h> #include "angles.h" #include "Vec.h" /* ----------------------------------------------------------------------------------------------------------------- */ /* Some useful constants */ #define NORMALIZED_TOLERANCE 0.0000001 // -------------------------------------------------------------------------------------------------------------------- Vec::Vec() : x(0), y(0), z(0) { } // end Vec Vec::Vec(double x, double y, double z) : x(x), y(y), z(z) { } // end Vec // -------------------------------------------------------------------------------------------------------------------- // Operations that produce new `Vec` instances /// Perform cross product. Vec Vec::cross(const Vec& other) const { return Vec( y * other.z - z * other.y, -x * other.z + z * other.x, x * other.y - y * other.x ); } // end cross /// Returns a unit vector in the same direction as Vec. Vec Vec::unit() const { return Vec(*this).normalize(); } // end unit /// Gets the Yaw and Pitch required to point in the direction of the given vector. Vec Vec::hprAlong() const { Vec tempVec = unit(); double yaw = -atan2(tempVec.x, tempVec.y); double pitch = atan2(tempVec.z, sqrt(pow(tempVec.x, 2) + pow(tempVec.y, 2))); return Vec(rad2deg(yaw), rad2deg(pitch), 0); } // end hpr_to // As stated at http://courses.cms.caltech.edu/cs11/material/cpp/donnie/cpp-ops.html, // "Define your binary arithmetic operators using your compound assignment operators." #define BINARY_OP(OP, OTHER_TYPE) \ Vec Vec::operator OP(const OTHER_TYPE& other) const \ { return Vec(*this) OP##= other; } // Operator overloads (Vec <op> Vec) BINARY_OP(+, Vec) BINARY_OP(-, Vec) // Operator overloads (Vec <op> <other type>) BINARY_OP(*, double) BINARY_OP(*, int32_t) BINARY_OP(*, u_int32_t) BINARY_OP(*, int64_t) BINARY_OP(*, u_int64_t) BINARY_OP(/, double) BINARY_OP(/, int32_t) BINARY_OP(/, u_int32_t) BINARY_OP(/, int64_t) BINARY_OP(/, u_int64_t) // -------------------------------------------------------------------------------------------------------------------- // Operations that produce other values /// Perform dot product. double Vec::dot(const Vec& other) const { return x * other.x + y * other.y + z * other.z; } // end dot /// Returns the squared length of the vector. This is useful in some optimization cases, as it avoids a sqrt call. double Vec::squaredNorm() const { // Yes, these two are equivalent. //return dot(*this); return x * x + y * y + z * z; } // end squared_norm /// Returns the length of the vector. double Vec::norm() const { return sqrt(squaredNorm()); } // end norm /// Checks to see if this is a zero vector. bool Vec::isZero() const { return fabs(x) < NORMALIZED_TOLERANCE && fabs(y) < NORMALIZED_TOLERANCE && fabs(z) < NORMALIZED_TOLERANCE; } // end isZero /// Access components using Vec[idx] double Vec::operator [](const size_t& idx) const throw(BadIndex<size_t>) { if(idx > 2 || idx < 0) { throw BadIndex<size_t>(idx); } // end if return *(&x + idx); /* NOTE: This is equivalent to: switch(idx) { case 0: return x; case 1: return y; case 2: return z; default: throw BadIndex<size_t>(idx); } // end switch */ } // end operator [] // -------------------------------------------------------------------------------------------------------------------- // In-place modifications /// Changes the length of this vector so that it's a unit vector. Vec& Vec::normalize() { double sqrNorm = squaredNorm(); // Don't renormalize if we're already less than our tolerance away from being a unit vector. if(fabs(sqrNorm - 1) < NORMALIZED_TOLERANCE) { return *this; } // end if // Also don't renormalize if we're already less than our tolerance away from being a zero vector. if(sqrNorm < NORMALIZED_TOLERANCE) { return *this; } // end if return *this /= sqrt(sqrNorm); } // end normalize // Create a compound assignment operator overload that sets each component of the Vec to `this.coord OP other.coord`. #define COMP_ASSIGN_OP_ZIP(OP, OTHER_TYPE) \ Vec& Vec::operator OP##=(const OTHER_TYPE& other) \ { \ x OP##= other.x; \ y OP##= other.y; \ z OP##= other.z; \ return *this; \ } // Operator overloads (Vec <op> Vec) COMP_ASSIGN_OP_ZIP(+, Vec) COMP_ASSIGN_OP_ZIP(-, Vec) // Create a compound assignment operator overload that sets each component of the Vec to `this.coord OP other`. #define COMP_ASSIGN_OP_MAP(OP, OTHER_TYPE) \ Vec& Vec::operator OP##=(const OTHER_TYPE& other) \ { \ x OP##= other; \ y OP##= other; \ z OP##= other; \ return *this; \ } // Operator overloads (Vec <op>= <other type>) COMP_ASSIGN_OP_MAP(*, double) COMP_ASSIGN_OP_MAP(*, int32_t) COMP_ASSIGN_OP_MAP(*, u_int32_t) COMP_ASSIGN_OP_MAP(*, int64_t) COMP_ASSIGN_OP_MAP(*, u_int64_t) COMP_ASSIGN_OP_MAP(/, double) COMP_ASSIGN_OP_MAP(/, int32_t) COMP_ASSIGN_OP_MAP(/, u_int32_t) COMP_ASSIGN_OP_MAP(/, int64_t) COMP_ASSIGN_OP_MAP(/, u_int64_t) <|endoftext|>
<commit_before>/* * GridMapTest.cpp * * Created on: Mar 24, 2015 * Author: Martin Wermelinger * Institute: ETH Zurich, Autonomous Systems Lab */ #include "grid_map_core/GridMap.hpp" #include "grid_map/GridMapRosConverter.hpp" #include "grid_map_core/iterators/GridMapIterator.hpp" // gtest #include <gtest/gtest.h> // Eigen #include <Eigen/Core> // STD #include <string> #include <vector> using namespace std; using namespace grid_map; TEST(RosbagHandling, saveLoad) { string layer = "layer"; string pathToBag = "test.bag"; string topic = "topic"; vector<string> layers; layers.push_back(layer); grid_map::GridMap gridMapIn(layers), gridMapOut; gridMapIn.setGeometry(grid_map::Length(1.0, 1.0), 0.5); double a = 1.0; for (grid_map::GridMapIterator iterator(gridMapIn); !iterator.isPastEnd(); ++iterator) { gridMapIn.at(layer, *iterator) = a; a += 1.0; } EXPECT_FALSE(gridMapOut.exists(layer)); EXPECT_TRUE(GridMapRosConverter::saveToBag(gridMapIn, pathToBag, topic)); EXPECT_TRUE(GridMapRosConverter::loadFromBag(pathToBag, topic, gridMapOut)); EXPECT_TRUE(gridMapOut.exists(layer)); for (grid_map::GridMapIterator iterator(gridMapIn); !iterator.isPastEnd(); ++iterator) { EXPECT_DOUBLE_EQ(gridMapIn.at(layer, *iterator), gridMapOut.at(layer, *iterator)); } } TEST(RosbagHandling, saveLoadWithTime) { string layer = "layer"; string pathToBag = "test.bag"; string topic = "topic"; vector<string> layers; layers.push_back(layer); grid_map::GridMap gridMapIn(layers), gridMapOut; gridMapIn.setGeometry(grid_map::Length(1.0, 1.0), 0.5); double a = 1.0; for (grid_map::GridMapIterator iterator(gridMapIn); !iterator.isPastEnd(); ++iterator) { gridMapIn.at(layer, *iterator) = a; a += 1.0; } EXPECT_FALSE(gridMapOut.exists(layer)); if (!ros::Time::isValid()) ros::Time::init(); // TODO Do other time than now. gridMapIn.setTimestamp(ros::Time::now().toNSec()); EXPECT_TRUE(GridMapRosConverter::saveToBag(gridMapIn, pathToBag, topic)); EXPECT_TRUE(GridMapRosConverter::loadFromBag(pathToBag, topic, gridMapOut)); EXPECT_TRUE(gridMapOut.exists(layer)); for (grid_map::GridMapIterator iterator(gridMapIn); !iterator.isPastEnd(); ++iterator) { EXPECT_DOUBLE_EQ(gridMapIn.at(layer, *iterator), gridMapOut.at(layer, *iterator)); } } TEST(OccupancyGridConversion, withMove) { grid_map::GridMap map; map.setGeometry(grid_map::Length(8.0, 5.0), 0.5, grid_map::Position(0.0, 0.0)); map.add("layer", 1.0); // Convert to OccupancyGrid msg. nav_msgs::OccupancyGrid occupancyGrid; grid_map::GridMapRosConverter::toOccupancyGrid(map, "layer", 0.0, 1.0, occupancyGrid); // Expect the (0, 0) cell to have value 100. EXPECT_DOUBLE_EQ(100.0, occupancyGrid.data[0]); // Move the map, so the cell (0, 0) will move to unobserved space. map.move(grid_map::Position(-1.0, -1.0)); // Convert again to OccupancyGrid msg. nav_msgs::OccupancyGrid occupancyGridNew; grid_map::GridMapRosConverter::toOccupancyGrid(map, "layer", 0.0, 1.0, occupancyGridNew); // Now the (0, 0) cell should be unobserved (-1). EXPECT_DOUBLE_EQ(-1.0, occupancyGridNew.data[0]); } <commit_msg>Added unit test for round trip conversion from occupancy grid to grid map and back to occupancy grid.<commit_after>/* * GridMapTest.cpp * * Created on: Mar 24, 2015 * Author: Peter Fankhauser, Martin Wermelinger * Institute: ETH Zurich, Autonomous Systems Lab */ #include "grid_map_core/GridMap.hpp" #include "grid_map/GridMapRosConverter.hpp" #include "grid_map_core/iterators/GridMapIterator.hpp" // gtest #include <gtest/gtest.h> // Eigen #include <Eigen/Core> // STD #include <string> #include <vector> #include <stdlib.h> #include <iterator> // ROS #include <nav_msgs/OccupancyGrid.h> using namespace std; using namespace grid_map; TEST(RosbagHandling, saveLoad) { string layer = "layer"; string pathToBag = "test.bag"; string topic = "topic"; vector<string> layers; layers.push_back(layer); grid_map::GridMap gridMapIn(layers), gridMapOut; gridMapIn.setGeometry(grid_map::Length(1.0, 1.0), 0.5); double a = 1.0; for (grid_map::GridMapIterator iterator(gridMapIn); !iterator.isPastEnd(); ++iterator) { gridMapIn.at(layer, *iterator) = a; a += 1.0; } EXPECT_FALSE(gridMapOut.exists(layer)); EXPECT_TRUE(GridMapRosConverter::saveToBag(gridMapIn, pathToBag, topic)); EXPECT_TRUE(GridMapRosConverter::loadFromBag(pathToBag, topic, gridMapOut)); EXPECT_TRUE(gridMapOut.exists(layer)); for (grid_map::GridMapIterator iterator(gridMapIn); !iterator.isPastEnd(); ++iterator) { EXPECT_DOUBLE_EQ(gridMapIn.at(layer, *iterator), gridMapOut.at(layer, *iterator)); } } TEST(RosbagHandling, saveLoadWithTime) { string layer = "layer"; string pathToBag = "test.bag"; string topic = "topic"; vector<string> layers; layers.push_back(layer); grid_map::GridMap gridMapIn(layers), gridMapOut; gridMapIn.setGeometry(grid_map::Length(1.0, 1.0), 0.5); double a = 1.0; for (grid_map::GridMapIterator iterator(gridMapIn); !iterator.isPastEnd(); ++iterator) { gridMapIn.at(layer, *iterator) = a; a += 1.0; } EXPECT_FALSE(gridMapOut.exists(layer)); if (!ros::Time::isValid()) ros::Time::init(); // TODO Do other time than now. gridMapIn.setTimestamp(ros::Time::now().toNSec()); EXPECT_TRUE(GridMapRosConverter::saveToBag(gridMapIn, pathToBag, topic)); EXPECT_TRUE(GridMapRosConverter::loadFromBag(pathToBag, topic, gridMapOut)); EXPECT_TRUE(gridMapOut.exists(layer)); for (grid_map::GridMapIterator iterator(gridMapIn); !iterator.isPastEnd(); ++iterator) { EXPECT_DOUBLE_EQ(gridMapIn.at(layer, *iterator), gridMapOut.at(layer, *iterator)); } } TEST(OccupancyGridConversion, withMove) { grid_map::GridMap map; map.setGeometry(grid_map::Length(8.0, 5.0), 0.5, grid_map::Position(0.0, 0.0)); map.add("layer", 1.0); // Convert to OccupancyGrid msg. nav_msgs::OccupancyGrid occupancyGrid; grid_map::GridMapRosConverter::toOccupancyGrid(map, "layer", 0.0, 1.0, occupancyGrid); // Expect the (0, 0) cell to have value 100. EXPECT_DOUBLE_EQ(100.0, occupancyGrid.data[0]); // Move the map, so the cell (0, 0) will move to unobserved space. map.move(grid_map::Position(-1.0, -1.0)); // Convert again to OccupancyGrid msg. nav_msgs::OccupancyGrid occupancyGridNew; grid_map::GridMapRosConverter::toOccupancyGrid(map, "layer", 0.0, 1.0, occupancyGridNew); // Now the (0, 0) cell should be unobserved (-1). EXPECT_DOUBLE_EQ(-1.0, occupancyGridNew.data[0]); } TEST(OccupancyGridConversion, roundTrip) { // Create occupancy grid. nav_msgs::OccupancyGrid occupancyGrid; occupancyGrid.header.stamp = ros::Time(5.0); occupancyGrid.header.frame_id = "map"; occupancyGrid.info.resolution = 0.1; occupancyGrid.info.width = 50; occupancyGrid.info.height = 100; occupancyGrid.info.origin.position.x = 3.0; occupancyGrid.info.origin.position.y = 6.0; occupancyGrid.info.origin.orientation.w = 1.0; occupancyGrid.data.resize(occupancyGrid.info.width * occupancyGrid.info.height); for (auto& cell : occupancyGrid.data) { cell = rand() % 102 - 1; // [-1, 100] } // Convert to grid map. grid_map::GridMap gridMap; grid_map::GridMapRosConverter::fromOccupancyGrid(occupancyGrid, "layer", gridMap); // Convert back to occupancy grid. nav_msgs::OccupancyGrid occupancyGridResult; grid_map::GridMapRosConverter::toOccupancyGrid(gridMap, "layer", -1.0, 100.0, occupancyGridResult); // Check map info. EXPECT_EQ(occupancyGrid.header.stamp, occupancyGridResult.header.stamp); EXPECT_EQ(occupancyGrid.header.frame_id, occupancyGridResult.header.frame_id); EXPECT_EQ(occupancyGrid.info.width, occupancyGridResult.info.width); EXPECT_EQ(occupancyGrid.info.height, occupancyGridResult.info.height); EXPECT_DOUBLE_EQ(occupancyGrid.info.origin.position.x, occupancyGridResult.info.origin.position.x); EXPECT_DOUBLE_EQ(occupancyGrid.info.origin.position.x, occupancyGridResult.info.origin.position.x); EXPECT_DOUBLE_EQ(occupancyGrid.info.origin.orientation.x, occupancyGridResult.info.origin.orientation.x); EXPECT_DOUBLE_EQ(occupancyGrid.info.origin.orientation.y, occupancyGridResult.info.origin.orientation.y); EXPECT_DOUBLE_EQ(occupancyGrid.info.origin.orientation.z, occupancyGridResult.info.origin.orientation.z); EXPECT_DOUBLE_EQ(occupancyGrid.info.origin.orientation.w, occupancyGridResult.info.origin.orientation.w); // Check map data. for (std::vector<int8_t>::iterator iterator = occupancyGrid.data.begin(); iterator != occupancyGrid.data.end(); ++iterator) { size_t i = std::distance(occupancyGrid.data.begin(), iterator); EXPECT_EQ((int)*iterator, (int)occupancyGridResult.data[i]); } } <|endoftext|>
<commit_before>// Copyright 2014-2015 Open Source Robotics Foundation, 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. #include "types.hpp" #include <string> #include "rmw/error_handling.h" std::string create_type_name( const message_type_support_callbacks_t * callbacks, const std::string & sep) { return std::string(callbacks->package_name) + "::" + sep + "::dds_::" + callbacks->message_name + "_"; } void CustomDataReaderListener::add_information( const DDS::SampleInfo & sample_info, const std::string & topic_name, const std::string & type_name) { // store topic name and type name auto & topic_types = topic_names_and_types[topic_name]; topic_types.insert(type_name); // store mapping to instance handle TopicDescriptor topic_descriptor; topic_descriptor.instance_handle = sample_info.instance_handle; topic_descriptor.name = topic_name; topic_descriptor.type = type_name; topic_descriptors.push_back(topic_descriptor); } void CustomDataReaderListener::remove_information(const DDS::SampleInfo & sample_info) { // find entry by instance handle for (auto it = topic_descriptors.begin(); it != topic_descriptors.end(); ++it) { if (it->instance_handle == sample_info.instance_handle) { // remove entries auto & topic_types = topic_names_and_types[it->name]; topic_types.erase(topic_types.find(it->type)); if (topic_types.empty()) { topic_names_and_types.erase(it->name); } topic_descriptors.erase(it); break; } } } CustomPublisherListener::CustomPublisherListener(rmw_guard_condition_t * graph_guard_condition) : graph_guard_condition_(graph_guard_condition) { } void CustomPublisherListener::on_data_available(DDS::DataReader * reader) { DDS::PublicationBuiltinTopicDataDataReader * builtin_reader = DDS::PublicationBuiltinTopicDataDataReader::_narrow(reader); DDS::PublicationBuiltinTopicDataSeq data_seq; DDS::SampleInfoSeq info_seq; DDS::ReturnCode_t retcode = builtin_reader->take( data_seq, info_seq, DDS::LENGTH_UNLIMITED, DDS::ANY_SAMPLE_STATE, DDS::ANY_VIEW_STATE, DDS::ANY_INSTANCE_STATE); if (retcode == DDS::RETCODE_NO_DATA) { return; } if (retcode != DDS::RETCODE_OK) { fprintf(stderr, "failed to access data from the built-in reader\n"); return; } for (DDS::ULong i = 0; i < data_seq.length(); ++i) { if (info_seq[i].valid_data) { add_information(info_seq[i], data_seq[i].topic_name.in(), data_seq[i].type_name.in()); } else { remove_information(info_seq[i]); } } if (data_seq.length() > 0) { rmw_ret_t ret = rmw_trigger_guard_condition(graph_guard_condition_); if (ret != RMW_RET_OK) { fprintf(stderr, "failed to trigger graph guard condition: %s\n", rmw_get_error_string_safe()); } } builtin_reader->return_loan(data_seq, info_seq); } CustomSubscriberListener::CustomSubscriberListener(rmw_guard_condition_t * graph_guard_condition) : graph_guard_condition_(graph_guard_condition) { } void CustomSubscriberListener::on_data_available(DDS::DataReader * reader) { DDS::SubscriptionBuiltinTopicDataDataReader * builtin_reader = DDS::SubscriptionBuiltinTopicDataDataReader::_narrow(reader); DDS::SubscriptionBuiltinTopicDataSeq data_seq; DDS::SampleInfoSeq info_seq; DDS::ReturnCode_t retcode = builtin_reader->take( data_seq, info_seq, DDS::LENGTH_UNLIMITED, DDS::ANY_SAMPLE_STATE, DDS::ANY_VIEW_STATE, DDS::ANY_INSTANCE_STATE); if (retcode == DDS::RETCODE_NO_DATA) { return; } if (retcode != DDS::RETCODE_OK) { fprintf(stderr, "failed to access data from the built-in reader\n"); return; } for (DDS::ULong i = 0; i < data_seq.length(); ++i) { if (info_seq[i].valid_data) { add_information(info_seq[i], data_seq[i].topic_name.in(), data_seq[i].type_name.in()); } else { remove_information(info_seq[i]); } } if (data_seq.length() > 0) { rmw_ret_t ret = rmw_trigger_guard_condition(graph_guard_condition_); if (ret != RMW_RET_OK) { fprintf(stderr, "failed to trigger graph guard condition: %s\n", rmw_get_error_string_safe()); } } builtin_reader->return_loan(data_seq, info_seq); } <commit_msg>fix publish/subscribe state management<commit_after>// Copyright 2014-2015 Open Source Robotics Foundation, 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. #include "types.hpp" #include <string> #include "rmw/error_handling.h" std::string create_type_name( const message_type_support_callbacks_t * callbacks, const std::string & sep) { return std::string(callbacks->package_name) + "::" + sep + "::dds_::" + callbacks->message_name + "_"; } void CustomDataReaderListener::add_information( const DDS::SampleInfo & sample_info, const std::string & topic_name, const std::string & type_name) { // store topic name and type name auto & topic_types = topic_names_and_types[topic_name]; topic_types.insert(type_name); // store mapping to instance handle TopicDescriptor topic_descriptor; topic_descriptor.instance_handle = sample_info.instance_handle; topic_descriptor.name = topic_name; topic_descriptor.type = type_name; topic_descriptors.push_back(topic_descriptor); } void CustomDataReaderListener::remove_information(const DDS::SampleInfo & sample_info) { // find entry by instance handle for (auto it = topic_descriptors.begin(); it != topic_descriptors.end(); ++it) { if (it->instance_handle == sample_info.instance_handle) { // remove entries auto & topic_types = topic_names_and_types[it->name]; topic_types.erase(topic_types.find(it->type)); if (topic_types.empty()) { topic_names_and_types.erase(it->name); } topic_descriptors.erase(it); break; } } } CustomPublisherListener::CustomPublisherListener(rmw_guard_condition_t * graph_guard_condition) : graph_guard_condition_(graph_guard_condition) { } void CustomPublisherListener::on_data_available(DDS::DataReader * reader) { DDS::PublicationBuiltinTopicDataDataReader * builtin_reader = DDS::PublicationBuiltinTopicDataDataReader::_narrow(reader); DDS::PublicationBuiltinTopicDataSeq data_seq; DDS::SampleInfoSeq info_seq; DDS::ReturnCode_t retcode = builtin_reader->take( data_seq, info_seq, DDS::LENGTH_UNLIMITED, DDS::ANY_SAMPLE_STATE, DDS::ANY_VIEW_STATE, DDS::ANY_INSTANCE_STATE); if (retcode == DDS::RETCODE_NO_DATA) { return; } if (retcode != DDS::RETCODE_OK) { fprintf(stderr, "failed to access data from the built-in reader\n"); return; } for (DDS::ULong i = 0; i < data_seq.length(); ++i) { if (info_seq[i].valid_data) { if (info_seq[i].instance_state == DDS::ALIVE_INSTANCE_STATE) { add_information(info_seq[i], data_seq[i].topic_name.in(), data_seq[i].type_name.in()); } else { remove_information(info_seq[i]); } } else { remove_information(info_seq[i]); } } if (data_seq.length() > 0) { rmw_ret_t ret = rmw_trigger_guard_condition(graph_guard_condition_); if (ret != RMW_RET_OK) { fprintf(stderr, "failed to trigger graph guard condition: %s\n", rmw_get_error_string_safe()); } } builtin_reader->return_loan(data_seq, info_seq); } CustomSubscriberListener::CustomSubscriberListener(rmw_guard_condition_t * graph_guard_condition) : graph_guard_condition_(graph_guard_condition) { } void CustomSubscriberListener::on_data_available(DDS::DataReader * reader) { DDS::SubscriptionBuiltinTopicDataDataReader * builtin_reader = DDS::SubscriptionBuiltinTopicDataDataReader::_narrow(reader); DDS::SubscriptionBuiltinTopicDataSeq data_seq; DDS::SampleInfoSeq info_seq; DDS::ReturnCode_t retcode = builtin_reader->take( data_seq, info_seq, DDS::LENGTH_UNLIMITED, DDS::ANY_SAMPLE_STATE, DDS::ANY_VIEW_STATE, DDS::ANY_INSTANCE_STATE); if (retcode == DDS::RETCODE_NO_DATA) { return; } if (retcode != DDS::RETCODE_OK) { fprintf(stderr, "failed to access data from the built-in reader\n"); return; } for (DDS::ULong i = 0; i < data_seq.length(); ++i) { if (info_seq[i].valid_data) { if (info_seq[i].instance_state == DDS::ALIVE_INSTANCE_STATE) { add_information(info_seq[i], data_seq[i].topic_name.in(), data_seq[i].type_name.in()); } else { remove_information(info_seq[i]); } } else { remove_information(info_seq[i]); } } if (data_seq.length() > 0) { rmw_ret_t ret = rmw_trigger_guard_condition(graph_guard_condition_); if (ret != RMW_RET_OK) { fprintf(stderr, "failed to trigger graph guard condition: %s\n", rmw_get_error_string_safe()); } } builtin_reader->return_loan(data_seq, info_seq); } <|endoftext|>
<commit_before>// ======================================================================== // // Copyright 2009-2015 Intel Corporation // // // // 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 "default.h" #include "distribution2d.h" #include "../common/scenegraph/scenegraph.h" #include "../common/image/image.h" namespace embree { /* name of the tutorial */ const char* tutorialName = "convert"; struct HeightField : public RefCount { HeightField (Ref<Image> texture, const BBox3fa& bounds) : texture(texture), bounds(bounds) {} const Vec3fa at(const size_t x, const size_t y) { const size_t width = texture->width; const size_t height = texture->height; const Color4 c = texture->get(x,y); const Vec2f p(x/float(width-1),y/float(height-1)); const float px = p.x*(bounds.upper.x-bounds.lower.x) + bounds.lower.x; const float py = c.r*(bounds.upper.y-bounds.lower.y) + bounds.lower.y; const float pz = p.y*(bounds.upper.z-bounds.lower.z) + bounds.lower.z; return Vec3fa(px,py,pz); } const AffineSpace3fa get(Vec2f p) { const size_t width = texture->width; const size_t height = texture->height; const size_t x = clamp((size_t)(p.x*(width-1)),(size_t)0,width-1); const size_t y = clamp((size_t)(p.y*(height-1)),(size_t)0,height-1); const Color4 c = texture->get(x,y); const float px = p.x*(bounds.upper.x-bounds.lower.x) + bounds.lower.x; const float py = c.r*(bounds.upper.y-bounds.lower.y) + bounds.lower.y; const float pz = p.y*(bounds.upper.z-bounds.lower.z) + bounds.lower.z; return AffineSpace3fa::translate(Vec3fa(px,py,pz)); } Ref<SceneGraph::Node> geometry() { OBJMaterial material(1.0f,Vec3fa(0.5f),Vec3fa(0.0f),1.0f); Ref<SceneGraph::MaterialNode> mnode = new SceneGraph::MaterialNode((Material&)material); Ref<SceneGraph::TriangleMeshNode> mesh = new SceneGraph::TriangleMeshNode(mnode); const size_t width = texture->width; const size_t height = texture->height; mesh->v.resize(height*width); for (size_t y=0; y<height; y++) for (size_t x=0; x<width; x++) mesh->v[y*width+x] = at(x,y); mesh->triangles.resize(2*(height-1)*(width-1)); for (size_t y=0; y<height-1; y++) { for (size_t x=0; x<width-1; x++) { const size_t p00 = (y+0)*width+(x+0); const size_t p01 = (y+0)*width+(x+1); const size_t p10 = (y+1)*width+(x+0); const size_t p11 = (y+1)*width+(x+1); const size_t tri = y*(width-1)+x; mesh->triangles[2*tri+0] = SceneGraph::TriangleMeshNode::Triangle(p00,p01,p10); mesh->triangles[2*tri+1] = SceneGraph::TriangleMeshNode::Triangle(p01,p11,p10); } } return mesh.dynamicCast<SceneGraph::Node>(); } private: Ref<Image> texture; BBox3fa bounds; }; struct Instantiator : public RefCount { Instantiator(const Ref<HeightField>& heightField, const Ref<SceneGraph::Node>& object, const Ref<Image>& distribution, float minDistance, size_t N) : heightField(heightField), object(object), dist(nullptr), minDistance(minDistance), N(N) { /* create distribution */ size_t width = distribution->width; size_t height = distribution->height; float* values = new float[width*height]; for (size_t y=0; y<height; y++) for (size_t x=0; x<width; x++) values[y*width+x] = luminance(distribution->get(x,y)); dist = new Distribution2D(values,width,height); delete values; } void instantiate(Ref<SceneGraph::GroupNode>& group) { for (size_t i=0; i<N; i++) { Vec2f r = Vec2f(random<float>(),random<float>()); Vec2f p = dist->sample(r); p.x *= rcp(float(dist->width)); p.y *= rcp(float(dist->height)); const AffineSpace3fa space = heightField->get(p); group->add(new SceneGraph::TransformNode(space,object)); } } private: Ref<HeightField> heightField; Ref<SceneGraph::Node> object; Ref<Distribution2D> dist; float minDistance; size_t N; }; /* scene */ Ref<SceneGraph::GroupNode> g_scene = new SceneGraph::GroupNode; Ref<HeightField> g_height_field = nullptr; static void parseCommandLine(Ref<ParseStream> cin, const FileName& path) { while (true) { std::string tag = cin->getString(); if (tag == "") return; /* parse command line parameters from a file */ else if (tag == "-c") { FileName file = path + cin->getFileName(); parseCommandLine(new ParseStream(new LineCommentFilter(file, "#")), file.path()); } /* load model */ else if (tag == "-i") { g_scene->add(SceneGraph::load(path + cin->getFileName())); } /* load terrain */ else if (tag == "-terrain") { Ref<Image> tex = loadImage(path + cin->getFileName()); const Vec3fa lower = cin->getVec3fa(); const Vec3fa upper = cin->getVec3fa(); g_height_field = new HeightField(tex,BBox3fa(lower,upper)); g_scene->add(g_height_field->geometry()); } /* instantiate model */ else if (tag == "-instantiate") { Ref<SceneGraph::Node> object = SceneGraph::load(path + cin->getFileName()); Ref<Image> distribution = loadImage(path + cin->getFileName()); const float minDistance = cin->getFloat(); const size_t N = cin->getInt(); Ref<Instantiator> instantiator = new Instantiator(g_height_field,object,distribution,minDistance,N); instantiator->instantiate(g_scene); } /* output filename */ else if (tag == "-o") { SceneGraph::store(g_scene.dynamicCast<SceneGraph::Node>(),path + cin->getFileName()); } /* skip unknown command line parameter */ else { std::cerr << "unknown command line parameter: " << tag << " "; while (cin->peek() != "" && cin->peek()[0] != '-') std::cerr << cin->getString() << " "; std::cerr << std::endl; } } } /* main function in embree namespace */ int main(int argc, char** argv) { /* create stream for parsing */ Ref<ParseStream> stream = new ParseStream(new CommandLineStream(argc, argv)); /* parse command line */ parseCommandLine(stream, FileName()); return 0; } } int main(int argc, char** argv) { try { return embree::main(argc, argv); } catch (const std::exception& e) { std::cout << "Error: " << e.what() << std::endl; return 1; } catch (...) { std::cout << "Error: unknown exception caught." << std::endl; return 1; } } <commit_msg>convert app rotates instances<commit_after>// ======================================================================== // // Copyright 2009-2015 Intel Corporation // // // // 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 "default.h" #include "distribution2d.h" #include "../common/scenegraph/scenegraph.h" #include "../common/image/image.h" namespace embree { /* name of the tutorial */ const char* tutorialName = "convert"; struct HeightField : public RefCount { HeightField (Ref<Image> texture, const BBox3fa& bounds) : texture(texture), bounds(bounds) {} const Vec3fa at(const size_t x, const size_t y) { const size_t width = texture->width; const size_t height = texture->height; const Color4 c = texture->get(x,y); const Vec2f p(x/float(width-1),y/float(height-1)); const float px = p.x*(bounds.upper.x-bounds.lower.x) + bounds.lower.x; const float py = c.r*(bounds.upper.y-bounds.lower.y) + bounds.lower.y; const float pz = p.y*(bounds.upper.z-bounds.lower.z) + bounds.lower.z; return Vec3fa(px,py,pz); } const AffineSpace3fa get(Vec2f p) { const size_t width = texture->width; const size_t height = texture->height; const size_t x = clamp((size_t)(p.x*(width-1)),(size_t)0,width-1); const size_t y = clamp((size_t)(p.y*(height-1)),(size_t)0,height-1); const Color4 c = texture->get(x,y); const float px = p.x*(bounds.upper.x-bounds.lower.x) + bounds.lower.x; const float py = c.r*(bounds.upper.y-bounds.lower.y) + bounds.lower.y; const float pz = p.y*(bounds.upper.z-bounds.lower.z) + bounds.lower.z; return AffineSpace3fa::translate(Vec3fa(px,py,pz)); } Ref<SceneGraph::Node> geometry() { OBJMaterial material(1.0f,Vec3fa(0.5f),Vec3fa(0.0f),1.0f); Ref<SceneGraph::MaterialNode> mnode = new SceneGraph::MaterialNode((Material&)material); Ref<SceneGraph::TriangleMeshNode> mesh = new SceneGraph::TriangleMeshNode(mnode); const size_t width = texture->width; const size_t height = texture->height; mesh->v.resize(height*width); for (size_t y=0; y<height; y++) for (size_t x=0; x<width; x++) mesh->v[y*width+x] = at(x,y); mesh->triangles.resize(2*(height-1)*(width-1)); for (size_t y=0; y<height-1; y++) { for (size_t x=0; x<width-1; x++) { const size_t p00 = (y+0)*width+(x+0); const size_t p01 = (y+0)*width+(x+1); const size_t p10 = (y+1)*width+(x+0); const size_t p11 = (y+1)*width+(x+1); const size_t tri = y*(width-1)+x; mesh->triangles[2*tri+0] = SceneGraph::TriangleMeshNode::Triangle(p00,p01,p10); mesh->triangles[2*tri+1] = SceneGraph::TriangleMeshNode::Triangle(p01,p11,p10); } } return mesh.dynamicCast<SceneGraph::Node>(); } private: Ref<Image> texture; BBox3fa bounds; }; struct Instantiator : public RefCount { Instantiator(const Ref<HeightField>& heightField, const Ref<SceneGraph::Node>& object, const Ref<Image>& distribution, float minDistance, size_t N) : heightField(heightField), object(object), dist(nullptr), minDistance(minDistance), N(N) { /* create distribution */ size_t width = distribution->width; size_t height = distribution->height; float* values = new float[width*height]; for (size_t y=0; y<height; y++) for (size_t x=0; x<width; x++) values[y*width+x] = luminance(distribution->get(x,y)); dist = new Distribution2D(values,width,height); delete values; } void instantiate(Ref<SceneGraph::GroupNode>& group) { for (size_t i=0; i<N; i++) { Vec2f r = Vec2f(random<float>(),random<float>()); Vec2f p = dist->sample(r); p.x *= rcp(float(dist->width)); p.y *= rcp(float(dist->height)); float angle = 2.0f*float(pi)*random<float>(); const AffineSpace3fa space = heightField->get(p)*AffineSpace3fa::rotate(Vec3fa(0,1,0),angle); group->add(new SceneGraph::TransformNode(space,object)); } } private: Ref<HeightField> heightField; Ref<SceneGraph::Node> object; Ref<Distribution2D> dist; float minDistance; size_t N; }; /* scene */ Ref<SceneGraph::GroupNode> g_scene = new SceneGraph::GroupNode; Ref<HeightField> g_height_field = nullptr; static void parseCommandLine(Ref<ParseStream> cin, const FileName& path) { while (true) { std::string tag = cin->getString(); if (tag == "") return; /* parse command line parameters from a file */ else if (tag == "-c") { FileName file = path + cin->getFileName(); parseCommandLine(new ParseStream(new LineCommentFilter(file, "#")), file.path()); } /* load model */ else if (tag == "-i") { g_scene->add(SceneGraph::load(path + cin->getFileName())); } /* load terrain */ else if (tag == "-terrain") { Ref<Image> tex = loadImage(path + cin->getFileName()); const Vec3fa lower = cin->getVec3fa(); const Vec3fa upper = cin->getVec3fa(); g_height_field = new HeightField(tex,BBox3fa(lower,upper)); g_scene->add(g_height_field->geometry()); } /* instantiate model */ else if (tag == "-instantiate") { Ref<SceneGraph::Node> object = SceneGraph::load(path + cin->getFileName()); Ref<Image> distribution = loadImage(path + cin->getFileName()); const float minDistance = cin->getFloat(); const size_t N = cin->getInt(); Ref<Instantiator> instantiator = new Instantiator(g_height_field,object,distribution,minDistance,N); instantiator->instantiate(g_scene); } /* output filename */ else if (tag == "-o") { SceneGraph::store(g_scene.dynamicCast<SceneGraph::Node>(),path + cin->getFileName()); } /* skip unknown command line parameter */ else { std::cerr << "unknown command line parameter: " << tag << " "; while (cin->peek() != "" && cin->peek()[0] != '-') std::cerr << cin->getString() << " "; std::cerr << std::endl; } } } /* main function in embree namespace */ int main(int argc, char** argv) { /* create stream for parsing */ Ref<ParseStream> stream = new ParseStream(new CommandLineStream(argc, argv)); /* parse command line */ parseCommandLine(stream, FileName()); return 0; } } int main(int argc, char** argv) { try { return embree::main(argc, argv); } catch (const std::exception& e) { std::cout << "Error: " << e.what() << std::endl; return 1; } catch (...) { std::cout << "Error: unknown exception caught." << std::endl; return 1; } } <|endoftext|>
<commit_before>#include "ovpCBoxAlgorithmFrequencyBandSelector.h" using namespace OpenViBE; using namespace OpenViBE::Kernel; using namespace OpenViBE::Plugins; using namespace OpenViBEPlugins; using namespace OpenViBEPlugins::SignalProcessing; #include <vector> #include <string> #include <cstdio> #define min(a,b) ((a)<(b)?(a):(b)) #define max(a,b) ((a)<(b)?(b):(a)) namespace { std::vector < std::string > split(const std::string& sString, const char c) { std::vector < std::string > l_vResult; std::string::size_type i=0; std::string::size_type j=0; while(i<sString.length()) { j=i; while(j<sString.length() && sString[j]!=c) { j++; } if(i!=j) { l_vResult.push_back(std::string(sString, i, j-i)); } i=j+1; } return l_vResult; } }; boolean CBoxAlgorithmFrequencyBandSelector::initialize(void) { CString l_sSettingValue=FSettingValueAutoCast(*this->getBoxAlgorithmContext(), 0); std::vector < std::string > l_vSetting=::split(l_sSettingValue.toASCIIString(), OV_Value_EnumeratedStringSeparator); std::vector < std::string > l_vSettingRange; std::vector < std::string >::const_iterator it; std::vector < std::string >::const_iterator itRange; for(it=l_vSetting.begin(); it!=l_vSetting.end(); it++) { boolean l_bGood=false; l_vSettingRange=::split(*it, '-'); if(l_vSettingRange.size() == 1) { double l_dValue; if(::sscanf(l_vSettingRange[0].c_str(), "%lf", &l_dValue)==1) { m_vSelected.push_back(std::pair < float64, float64 >(l_dValue, l_dValue)); l_bGood=true; } } else if(l_vSettingRange.size() == 2) { double l_dLowValue; double l_dHighValue; if(::sscanf(l_vSettingRange[0].c_str(), "%lf", &l_dLowValue)==1 && ::sscanf(l_vSettingRange[1].c_str(), "%lf", &l_dHighValue)==1) { m_vSelected.push_back(std::pair < float64, float64 >(min(l_dLowValue, l_dHighValue), max(l_dLowValue, l_dHighValue))); l_bGood=true; } } if(!l_bGood) { this->getLogManager() << LogLevel_ImportantWarning << "Ignored invalid frequency band : " << CString(it->c_str()) << "\n"; } } m_pStreamDecoder=&this->getAlgorithmManager().getAlgorithm(this->getAlgorithmManager().createAlgorithm(OVP_GD_ClassId_Algorithm_SpectrumStreamDecoder)); m_pStreamDecoder->initialize(); ip_pMemoryBuffer.initialize(m_pStreamDecoder->getInputParameter(OVP_GD_Algorithm_SpectrumStreamDecoder_InputParameterId_MemoryBufferToDecode)); op_pMatrix.initialize(m_pStreamDecoder->getOutputParameter(OVP_GD_Algorithm_SpectrumStreamDecoder_OutputParameterId_Matrix)); op_pBands.initialize(m_pStreamDecoder->getOutputParameter(OVP_GD_Algorithm_SpectrumStreamDecoder_OutputParameterId_MinMaxFrequencyBands)); m_pStreamEncoder=&this->getAlgorithmManager().getAlgorithm(this->getAlgorithmManager().createAlgorithm(OVP_GD_ClassId_Algorithm_SpectrumStreamEncoder)); m_pStreamEncoder->initialize(); ip_pMatrix.initialize(m_pStreamEncoder->getInputParameter(OVP_GD_Algorithm_SpectrumStreamEncoder_InputParameterId_Matrix)); ip_pBands.initialize(m_pStreamEncoder->getInputParameter(OVP_GD_Algorithm_SpectrumStreamEncoder_InputParameterId_MinMaxFrequencyBands)); op_pMemoryBuffer.initialize(m_pStreamEncoder->getOutputParameter(OVP_GD_Algorithm_SpectrumStreamEncoder_OutputParameterId_EncodedMemoryBuffer)); ip_pBands.setReferenceTarget(op_pBands); ip_pMatrix=&m_oMatrix; op_pMatrix=&m_oMatrix; return true; } boolean CBoxAlgorithmFrequencyBandSelector::uninitialize(void) { op_pMemoryBuffer.uninitialize(); ip_pBands.uninitialize(); ip_pMatrix.uninitialize(); m_pStreamEncoder->uninitialize(); this->getAlgorithmManager().releaseAlgorithm(*m_pStreamEncoder); m_pStreamEncoder=NULL; op_pBands.uninitialize(); op_pMatrix.uninitialize(); ip_pMemoryBuffer.uninitialize(); m_pStreamDecoder->uninitialize(); this->getAlgorithmManager().releaseAlgorithm(*m_pStreamDecoder); m_pStreamDecoder=NULL; return true; } boolean CBoxAlgorithmFrequencyBandSelector::processInput(uint32 ui32InputIndex) { getBoxAlgorithmContext()->markAlgorithmAsReadyToProcess(); return true; } boolean CBoxAlgorithmFrequencyBandSelector::process(void) { IBoxIO& l_rDynamicBoxContext=this->getDynamicBoxContext(); for(uint32 i=0; i<l_rDynamicBoxContext.getInputChunkCount(0); i++) { ip_pMemoryBuffer=l_rDynamicBoxContext.getInputChunk(0, i); op_pMemoryBuffer=l_rDynamicBoxContext.getOutputChunk(0); m_pStreamDecoder->process(); if(m_pStreamDecoder->isOutputTriggerActive(OVP_GD_Algorithm_SpectrumStreamDecoder_OutputTriggerId_ReceivedHeader)) { m_vSelectionFactor.clear(); for(uint32 j=0; j<ip_pBands->getDimensionSize(1); j++) { boolean l_bSelected=false; for(size_t k=0; k<m_vSelected.size(); k++) { float64 l_f64Min=ip_pBands->getBuffer()[j*2+0]; float64 l_f64Max=ip_pBands->getBuffer()[j*2+1]; float64 l_f64Mean=(l_f64Min+l_f64Max)*.5; // if(!(m_vSelected[j].second < l_f64Min || l_f64Max < m_vSelected[j].first)) if(m_vSelected[k].first <= l_f64Mean && l_f64Mean <= m_vSelected[k].second) { l_bSelected=true; } } m_vSelectionFactor.push_back(l_bSelected?1.:0.); } m_pStreamEncoder->process(OVP_GD_Algorithm_SpectrumStreamEncoder_InputTriggerId_EncodeHeader); } if(m_pStreamDecoder->isOutputTriggerActive(OVP_GD_Algorithm_SpectrumStreamDecoder_OutputTriggerId_ReceivedBuffer)) { uint32 l_ui32Offset=0; for(uint32 j=0; j<m_oMatrix.getDimensionSize(0); j++) { for(uint32 k=0; k<m_oMatrix.getDimensionSize(1); k++) { m_oMatrix.getBuffer()[l_ui32Offset]=m_vSelectionFactor[k]*m_oMatrix.getBuffer()[l_ui32Offset]; l_ui32Offset++; } } m_pStreamEncoder->process(OVP_GD_Algorithm_SpectrumStreamEncoder_InputTriggerId_EncodeBuffer); } if(m_pStreamDecoder->isOutputTriggerActive(OVP_GD_Algorithm_SpectrumStreamDecoder_OutputTriggerId_ReceivedEnd)) { m_pStreamEncoder->process(OVP_GD_Algorithm_SpectrumStreamEncoder_InputTriggerId_EncodeEnd); } l_rDynamicBoxContext.markOutputAsReadyToSend(0, l_rDynamicBoxContext.getInputChunkStartTime(0, i), l_rDynamicBoxContext.getInputChunkEndTime(0, i)); l_rDynamicBoxContext.markInputAsDeprecated(0, i); } return true; } <commit_msg>openvibe-plugins-signal-processing : * Frequency Band Selector : corrected bug on single frequency selection<commit_after>#include "ovpCBoxAlgorithmFrequencyBandSelector.h" using namespace OpenViBE; using namespace OpenViBE::Kernel; using namespace OpenViBE::Plugins; using namespace OpenViBEPlugins; using namespace OpenViBEPlugins::SignalProcessing; #include <vector> #include <string> #include <cstdio> #define min(a,b) ((a)<(b)?(a):(b)) #define max(a,b) ((a)<(b)?(b):(a)) namespace { std::vector < std::string > split(const std::string& sString, const char c) { std::vector < std::string > l_vResult; std::string::size_type i=0; std::string::size_type j=0; while(i<sString.length()) { j=i; while(j<sString.length() && sString[j]!=c) { j++; } if(i!=j) { l_vResult.push_back(std::string(sString, i, j-i)); } i=j+1; } return l_vResult; } }; boolean CBoxAlgorithmFrequencyBandSelector::initialize(void) { CString l_sSettingValue=FSettingValueAutoCast(*this->getBoxAlgorithmContext(), 0); std::vector < std::string > l_vSetting=::split(l_sSettingValue.toASCIIString(), OV_Value_EnumeratedStringSeparator); std::vector < std::string > l_vSettingRange; std::vector < std::string >::const_iterator it; std::vector < std::string >::const_iterator itRange; for(it=l_vSetting.begin(); it!=l_vSetting.end(); it++) { boolean l_bGood=false; l_vSettingRange=::split(*it, '-'); if(l_vSettingRange.size() == 1) { double l_dValue; if(::sscanf(l_vSettingRange[0].c_str(), "%lf", &l_dValue)==1) { m_vSelected.push_back(std::pair < float64, float64 >(l_dValue, l_dValue)); l_bGood=true; } } else if(l_vSettingRange.size() == 2) { double l_dLowValue; double l_dHighValue; if(::sscanf(l_vSettingRange[0].c_str(), "%lf", &l_dLowValue)==1 && ::sscanf(l_vSettingRange[1].c_str(), "%lf", &l_dHighValue)==1) { m_vSelected.push_back(std::pair < float64, float64 >(min(l_dLowValue, l_dHighValue), max(l_dLowValue, l_dHighValue))); l_bGood=true; } } if(!l_bGood) { this->getLogManager() << LogLevel_ImportantWarning << "Ignored invalid frequency band : " << CString(it->c_str()) << "\n"; } } m_pStreamDecoder=&this->getAlgorithmManager().getAlgorithm(this->getAlgorithmManager().createAlgorithm(OVP_GD_ClassId_Algorithm_SpectrumStreamDecoder)); m_pStreamDecoder->initialize(); ip_pMemoryBuffer.initialize(m_pStreamDecoder->getInputParameter(OVP_GD_Algorithm_SpectrumStreamDecoder_InputParameterId_MemoryBufferToDecode)); op_pMatrix.initialize(m_pStreamDecoder->getOutputParameter(OVP_GD_Algorithm_SpectrumStreamDecoder_OutputParameterId_Matrix)); op_pBands.initialize(m_pStreamDecoder->getOutputParameter(OVP_GD_Algorithm_SpectrumStreamDecoder_OutputParameterId_MinMaxFrequencyBands)); m_pStreamEncoder=&this->getAlgorithmManager().getAlgorithm(this->getAlgorithmManager().createAlgorithm(OVP_GD_ClassId_Algorithm_SpectrumStreamEncoder)); m_pStreamEncoder->initialize(); ip_pMatrix.initialize(m_pStreamEncoder->getInputParameter(OVP_GD_Algorithm_SpectrumStreamEncoder_InputParameterId_Matrix)); ip_pBands.initialize(m_pStreamEncoder->getInputParameter(OVP_GD_Algorithm_SpectrumStreamEncoder_InputParameterId_MinMaxFrequencyBands)); op_pMemoryBuffer.initialize(m_pStreamEncoder->getOutputParameter(OVP_GD_Algorithm_SpectrumStreamEncoder_OutputParameterId_EncodedMemoryBuffer)); ip_pBands.setReferenceTarget(op_pBands); ip_pMatrix=&m_oMatrix; op_pMatrix=&m_oMatrix; return true; } boolean CBoxAlgorithmFrequencyBandSelector::uninitialize(void) { op_pMemoryBuffer.uninitialize(); ip_pBands.uninitialize(); ip_pMatrix.uninitialize(); m_pStreamEncoder->uninitialize(); this->getAlgorithmManager().releaseAlgorithm(*m_pStreamEncoder); m_pStreamEncoder=NULL; op_pBands.uninitialize(); op_pMatrix.uninitialize(); ip_pMemoryBuffer.uninitialize(); m_pStreamDecoder->uninitialize(); this->getAlgorithmManager().releaseAlgorithm(*m_pStreamDecoder); m_pStreamDecoder=NULL; return true; } boolean CBoxAlgorithmFrequencyBandSelector::processInput(uint32 ui32InputIndex) { getBoxAlgorithmContext()->markAlgorithmAsReadyToProcess(); return true; } boolean CBoxAlgorithmFrequencyBandSelector::process(void) { IBoxIO& l_rDynamicBoxContext=this->getDynamicBoxContext(); for(uint32 i=0; i<l_rDynamicBoxContext.getInputChunkCount(0); i++) { ip_pMemoryBuffer=l_rDynamicBoxContext.getInputChunk(0, i); op_pMemoryBuffer=l_rDynamicBoxContext.getOutputChunk(0); m_pStreamDecoder->process(); if(m_pStreamDecoder->isOutputTriggerActive(OVP_GD_Algorithm_SpectrumStreamDecoder_OutputTriggerId_ReceivedHeader)) { m_vSelectionFactor.clear(); for(uint32 j=0; j<ip_pBands->getDimensionSize(1); j++) { boolean l_bSelected=false; for(size_t k=0; k<m_vSelected.size(); k++) { float64 l_f64Min=ip_pBands->getBuffer()[j*2+0]; float64 l_f64Max=ip_pBands->getBuffer()[j*2+1]; float64 l_f64Mean=(l_f64Min+l_f64Max)*.5; // if(!(m_vSelected[j].second < l_f64Min || l_f64Max < m_vSelected[j].first)) // if(m_vSelected[k].first <= l_f64Mean && l_f64Mean <= m_vSelected[k].second) if(m_vSelected[k].first < l_f64Max && l_f64Min <= m_vSelected[k].second) { l_bSelected=true; } } m_vSelectionFactor.push_back(l_bSelected?1.:0.); } m_pStreamEncoder->process(OVP_GD_Algorithm_SpectrumStreamEncoder_InputTriggerId_EncodeHeader); } if(m_pStreamDecoder->isOutputTriggerActive(OVP_GD_Algorithm_SpectrumStreamDecoder_OutputTriggerId_ReceivedBuffer)) { uint32 l_ui32Offset=0; for(uint32 j=0; j<m_oMatrix.getDimensionSize(0); j++) { for(uint32 k=0; k<m_oMatrix.getDimensionSize(1); k++) { m_oMatrix.getBuffer()[l_ui32Offset]=m_vSelectionFactor[k]*m_oMatrix.getBuffer()[l_ui32Offset]; l_ui32Offset++; } } m_pStreamEncoder->process(OVP_GD_Algorithm_SpectrumStreamEncoder_InputTriggerId_EncodeBuffer); } if(m_pStreamDecoder->isOutputTriggerActive(OVP_GD_Algorithm_SpectrumStreamDecoder_OutputTriggerId_ReceivedEnd)) { m_pStreamEncoder->process(OVP_GD_Algorithm_SpectrumStreamEncoder_InputTriggerId_EncodeEnd); } l_rDynamicBoxContext.markOutputAsReadyToSend(0, l_rDynamicBoxContext.getInputChunkStartTime(0, i), l_rDynamicBoxContext.getInputChunkEndTime(0, i)); l_rDynamicBoxContext.markInputAsDeprecated(0, i); } return true; } <|endoftext|>
<commit_before>// -*- Mode: c++-mode; c-basic-offset: 2; indent-tabs-mode: t; tab-width: 2; -*- // // Copyright (C) 2003 Grzegorz Jaskiewicz <gj at pointblue.com.pl> // // gaduregisteraccount.cpp // // 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., 59 Temple Place - Suite 330, Boston, MA // 02111-1307, USA. #include <qstring.h> #include <qregexp.h> #include <qpushbutton.h> #include <qlabel.h> #include <klineedit.h> #include <kmessagebox.h> #include <kdebug.h> #include <klocale.h> #include "gaduregisteraccountui.h" #include "gaduregisteraccount.h" #include "gaducommands.h" GaduRegisterAccount::GaduRegisterAccount( QWidget* parent, const char* name ) : KDialogBase( parent, name, true, i18n( "Register New Account" ), KDialogBase::User1 | KDialogBase::Ok, KDialogBase::User1, true ) { ui = new GaduRegisterAccountUI( this ); setMainWidget( ui ); ui->valueVerificationSequence->setDisabled( true ); setButtonText( User1, i18n( "&Register" ) ); setButtonText( Ok, i18n( "&Cancel" ) ); enableButton( User1, false ); cRegister = new RegisterCommand( this ); emailRegexp = new QRegExp( "[\\w\\d.+_-]{1,}@[\\w\\d.-]{1,}" ); connect( this, SIGNAL( user1Clicked() ), SLOT( doRegister() ) ); connect( this, SIGNAL( okClicked() ), SLOT( slotClose() ) ); connect( ui->valueEmailAddress, SIGNAL( textChanged( const QString &) ), SLOT( inputChanged( const QString & ) ) ); connect( ui->valuePassword, SIGNAL( textChanged( const QString & ) ), SLOT( inputChanged( const QString & ) ) ); connect( ui->valuePasswordVerify, SIGNAL( textChanged( const QString & ) ), SLOT( inputChanged( const QString & ) ) ); connect( ui->valueVerificationSequence, SIGNAL( textChanged( const QString & ) ), SLOT( inputChanged( const QString & ) ) ); connect( cRegister, SIGNAL( tokenRecieved( QPixmap, QString ) ), SLOT( displayToken( QPixmap, QString ) ) ); connect( cRegister, SIGNAL( done( const QString&, const QString& ) ), SLOT( registrationDone( const QString&, const QString& ) ) ); connect( cRegister, SIGNAL( error( const QString&, const QString& ) ), SLOT( registrationError( const QString&, const QString& ) ) ); connect( cRegister, SIGNAL( operationStatus( const QString ) ), SLOT( updateStatus( const QString ) ) ); updateStatus( i18n( "Retrieving token" ) ); cRegister->requestToken(); show(); } void GaduRegisterAccount::doRegister( ) { cRegister->setUserinfo( ui->valueEmailAddress->text(), ui->valuePassword->text(), ui->valueVerificationSequence->text() ); cRegister->execute(); enableButton( User1, false ); } void GaduRegisterAccount::validateInput() { // FIXME: These need to use KDE default text color instead of hardcoded black. ui->labelEmailAddress->unsetPalette(); ui->labelPassword->unsetPalette(); ui->labelPasswordVerify->unsetPalette(); ui->labelVerificationSequence->unsetPalette(); if ( emailRegexp->exactMatch( ui->valueEmailAddress->text() ) && ui->valuePassword->text() == ui->valuePasswordVerify->text() && !ui->valuePassword->text().isEmpty() && !ui->valuePasswordVerify->text().isEmpty() && !ui->valueVerificationSequence->text().isEmpty() ) { enableButton( User1, true ); updateStatus( "" ); } else { if ( !emailRegexp->exactMatch( ui->valueEmailAddress->text() ) ) { updateStatus( i18n( "Please enter a valid E-Mail Address." ) ); ui->labelEmailAddress->setPaletteForegroundColor( QColor( 0, 0, 255 ) ); } else if ( ( ui->valuePassword->text().isEmpty() ) || ( ui->valuePasswordVerify->text().isEmpty() ) ) { updateStatus( i18n( "Please enter the same password twice." ) ); ui->labelPassword->setPaletteForegroundColor( QColor( 0, 0, 255 ) ); ui->labelPasswordVerify->setPaletteForegroundColor( QColor( 0, 0, 255 ) ); } else if ( ui->valuePassword->text() != ui->valuePasswordVerify->text() ) { updateStatus( i18n( "Password entries do not match." ) ); ui->labelPassword->setPaletteForegroundColor( QColor( 255, 0, 0 ) ); ui->labelPasswordVerify->setPaletteForegroundColor( QColor( 255, 0, 0 ) ); } else if ( ui->valueVerificationSequence->text().isEmpty() ) { updateStatus( i18n( "Please enter the verification sequence." ) ); ui->labelVerificationSequence->setPaletteForegroundColor( QColor( 0, 0, 255 ) ); } enableButton( User1, false ); } } void GaduRegisterAccount::inputChanged( const QString & ) { validateInput(); } void GaduRegisterAccount::registrationDone( const QString& /*title*/, const QString& /*what */ ) { ui->valueEmailAddress->setDisabled( true ); ui->valuePassword->setDisabled( true ); ui->valuePasswordVerify->setDisabled( true ); ui->valueVerificationSequence->setDisabled( true ); ui->labelEmailAddress->setDisabled( true ); ui->labelPassword->setDisabled( true ); ui->labelPasswordVerify->setDisabled( true ); ui->labelVerificationSequence->setDisabled( true ); ui->labelInstructions->setDisabled( true ); emit registeredNumber( cRegister->newUin(), ui->valuePassword->text() ); updateStatus( i18n( "Account created; your new UIN is %1." ).arg(QString::number( cRegister->newUin() ) ) ); enableButton( User1, false ); setButtonText( Ok, i18n( "&Close" ) ); } void GaduRegisterAccount::registrationError( const QString& title, const QString& what ) { updateStatus( i18n( "Registration failed: %1" ).arg( what ) ); KMessageBox::sorry( this, what, title ); disconnect( this, SLOT( displayToken( QPixmap, QString ) ) ); disconnect( this, SLOT( registrationDone( const QString&, const QString& ) ) ); disconnect( this, SLOT( registrationError( const QString&, const QString& ) ) ); disconnect( this, SLOT( updateStatus( const QString ) ) ); // it is set to deleteLater, in case of error cRegister = NULL; ui->valueVerificationSequence->setDisabled( true ); ui->valueVerificationSequence->setText( "" ); enableButton( User1, false ); updateStatus( "" ); cRegister = new RegisterCommand( this ); connect( cRegister, SIGNAL( tokenRecieved( QPixmap, QString ) ), SLOT( displayToken( QPixmap, QString ) ) ); connect( cRegister, SIGNAL( done( const QString&, const QString& ) ), SLOT( registrationDone( const QString&, const QString& ) ) ); connect( cRegister, SIGNAL( error( const QString&, const QString& ) ), SLOT( registrationError( const QString&, const QString& ) ) ); connect( cRegister, SIGNAL( operationStatus( const QString ) ), SLOT( updateStatus( const QString ) ) ); updateStatus( i18n( "Retrieving token" ) ); cRegister->requestToken(); } void GaduRegisterAccount::displayToken( QPixmap image, QString /*tokenId */ ) { ui->valueVerificationSequence->setDisabled( false ); ui->pixmapToken->setPixmap( image ); validateInput(); } void GaduRegisterAccount::updateStatus( const QString status ) { ui->labelStatusMessage->setAlignment( AlignCenter ); ui->labelStatusMessage->setText( status ); } void GaduRegisterAccount::slotClose() { // deleteLater(); } GaduRegisterAccount::~GaduRegisterAccount( ) { kdDebug( 14100 ) << " register Cancel " << endl; // if ( cRegister ) { // cRegister->cancel(); // } } #include "gaduregisteraccount.moc" <commit_msg>Label colorations removed. The hint at the bottom should be sufficient, and there is no global color setting to use (will open bug concerning remaining places with hardcoded colors in Kopete).<commit_after>// -*- Mode: c++-mode; c-basic-offset: 2; indent-tabs-mode: t; tab-width: 2; -*- // // Copyright (C) 2003 Grzegorz Jaskiewicz <gj at pointblue.com.pl> // // gaduregisteraccount.cpp // // 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., 59 Temple Place - Suite 330, Boston, MA // 02111-1307, USA. #include <qstring.h> #include <qregexp.h> #include <qpushbutton.h> #include <qlabel.h> #include <klineedit.h> #include <kmessagebox.h> #include <kdebug.h> #include <klocale.h> #include "gaduregisteraccountui.h" #include "gaduregisteraccount.h" #include "gaducommands.h" GaduRegisterAccount::GaduRegisterAccount( QWidget* parent, const char* name ) : KDialogBase( parent, name, true, i18n( "Register New Account" ), KDialogBase::User1 | KDialogBase::Ok, KDialogBase::User1, true ) { ui = new GaduRegisterAccountUI( this ); setMainWidget( ui ); ui->valueVerificationSequence->setDisabled( true ); setButtonText( User1, i18n( "&Register" ) ); setButtonText( Ok, i18n( "&Cancel" ) ); enableButton( User1, false ); cRegister = new RegisterCommand( this ); emailRegexp = new QRegExp( "[\\w\\d.+_-]{1,}@[\\w\\d.-]{1,}" ); connect( this, SIGNAL( user1Clicked() ), SLOT( doRegister() ) ); connect( this, SIGNAL( okClicked() ), SLOT( slotClose() ) ); connect( ui->valueEmailAddress, SIGNAL( textChanged( const QString &) ), SLOT( inputChanged( const QString & ) ) ); connect( ui->valuePassword, SIGNAL( textChanged( const QString & ) ), SLOT( inputChanged( const QString & ) ) ); connect( ui->valuePasswordVerify, SIGNAL( textChanged( const QString & ) ), SLOT( inputChanged( const QString & ) ) ); connect( ui->valueVerificationSequence, SIGNAL( textChanged( const QString & ) ), SLOT( inputChanged( const QString & ) ) ); connect( cRegister, SIGNAL( tokenRecieved( QPixmap, QString ) ), SLOT( displayToken( QPixmap, QString ) ) ); connect( cRegister, SIGNAL( done( const QString&, const QString& ) ), SLOT( registrationDone( const QString&, const QString& ) ) ); connect( cRegister, SIGNAL( error( const QString&, const QString& ) ), SLOT( registrationError( const QString&, const QString& ) ) ); connect( cRegister, SIGNAL( operationStatus( const QString ) ), SLOT( updateStatus( const QString ) ) ); updateStatus( i18n( "Retrieving token" ) ); cRegister->requestToken(); show(); } void GaduRegisterAccount::doRegister( ) { cRegister->setUserinfo( ui->valueEmailAddress->text(), ui->valuePassword->text(), ui->valueVerificationSequence->text() ); cRegister->execute(); enableButton( User1, false ); } void GaduRegisterAccount::validateInput() { // FIXME: These need to use KDE default text color instead of hardcoded black. if ( emailRegexp->exactMatch( ui->valueEmailAddress->text() ) && ui->valuePassword->text() == ui->valuePasswordVerify->text() && !ui->valuePassword->text().isEmpty() && !ui->valuePasswordVerify->text().isEmpty() && !ui->valueVerificationSequence->text().isEmpty() ) { enableButton( User1, true ); updateStatus( "" ); } else { if ( !emailRegexp->exactMatch( ui->valueEmailAddress->text() ) ) { updateStatus( i18n( "Please enter a valid E-Mail Address." ) ); } else if ( ( ui->valuePassword->text().isEmpty() ) || ( ui->valuePasswordVerify->text().isEmpty() ) ) { updateStatus( i18n( "Please enter the same password twice." ) ); } else if ( ui->valuePassword->text() != ui->valuePasswordVerify->text() ) { updateStatus( i18n( "Password entries do not match." ) ); } else if ( ui->valueVerificationSequence->text().isEmpty() ) { updateStatus( i18n( "Please enter the verification sequence." ) ); } enableButton( User1, false ); } } void GaduRegisterAccount::inputChanged( const QString & ) { validateInput(); } void GaduRegisterAccount::registrationDone( const QString& /*title*/, const QString& /*what */ ) { ui->valueEmailAddress->setDisabled( true ); ui->valuePassword->setDisabled( true ); ui->valuePasswordVerify->setDisabled( true ); ui->valueVerificationSequence->setDisabled( true ); ui->labelEmailAddress->setDisabled( true ); ui->labelPassword->setDisabled( true ); ui->labelPasswordVerify->setDisabled( true ); ui->labelVerificationSequence->setDisabled( true ); ui->labelInstructions->setDisabled( true ); emit registeredNumber( cRegister->newUin(), ui->valuePassword->text() ); updateStatus( i18n( "Account created; your new UIN is %1." ).arg(QString::number( cRegister->newUin() ) ) ); enableButton( User1, false ); setButtonText( Ok, i18n( "&Close" ) ); } void GaduRegisterAccount::registrationError( const QString& title, const QString& what ) { updateStatus( i18n( "Registration failed: %1" ).arg( what ) ); KMessageBox::sorry( this, what, title ); disconnect( this, SLOT( displayToken( QPixmap, QString ) ) ); disconnect( this, SLOT( registrationDone( const QString&, const QString& ) ) ); disconnect( this, SLOT( registrationError( const QString&, const QString& ) ) ); disconnect( this, SLOT( updateStatus( const QString ) ) ); // it is set to deleteLater, in case of error cRegister = NULL; ui->valueVerificationSequence->setDisabled( true ); ui->valueVerificationSequence->setText( "" ); enableButton( User1, false ); updateStatus( "" ); cRegister = new RegisterCommand( this ); connect( cRegister, SIGNAL( tokenRecieved( QPixmap, QString ) ), SLOT( displayToken( QPixmap, QString ) ) ); connect( cRegister, SIGNAL( done( const QString&, const QString& ) ), SLOT( registrationDone( const QString&, const QString& ) ) ); connect( cRegister, SIGNAL( error( const QString&, const QString& ) ), SLOT( registrationError( const QString&, const QString& ) ) ); connect( cRegister, SIGNAL( operationStatus( const QString ) ), SLOT( updateStatus( const QString ) ) ); updateStatus( i18n( "Retrieving token" ) ); cRegister->requestToken(); } void GaduRegisterAccount::displayToken( QPixmap image, QString /*tokenId */ ) { ui->valueVerificationSequence->setDisabled( false ); ui->pixmapToken->setPixmap( image ); validateInput(); } void GaduRegisterAccount::updateStatus( const QString status ) { ui->labelStatusMessage->setAlignment( AlignCenter ); ui->labelStatusMessage->setText( status ); } void GaduRegisterAccount::slotClose() { // deleteLater(); } GaduRegisterAccount::~GaduRegisterAccount( ) { kdDebug( 14100 ) << " register Cancel " << endl; // if ( cRegister ) { // cRegister->cancel(); // } } #include "gaduregisteraccount.moc" <|endoftext|>
<commit_before>#pragma ident "$Id$" //============================================================================ // // This file is part of GPSTk, the GPS Toolkit. // // The GPSTk 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 // any later version. // // The GPSTk 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 GPSTk; if not, write to the Free Software Foundation, // Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Copyright 2004, The University of Texas at Austin // //============================================================================ //============================================================================ // //This software developed by Applied Research Laboratories at the University of //Texas at Austin, under contract to an agency or agencies within the U.S. //Department of Defense. The U.S. Government retains all rights to use, //duplicate, distribute, disclose, or release this software. // //Pursuant to DoD Directive 523024 // // DISTRIBUTION STATEMENT A: This software has been approved for public // release, distribution is unlimited. // //============================================================================= /** @file Various presentations/analysis on MDP streams */ #include "MDPProcessors.hpp" using namespace std; using namespace gpstk; gpstk::MDPStream d1; std::ofstream d2; MDPProcessor::MDPProcessor() : timeFormat("%4Y/%03j/%02H:%02M:%04.1f"), stopTime(gpstk::DayTime::END_OF_TIME), startTime(gpstk::DayTime::BEGINNING_OF_TIME), timeSpan(-1), processBad(false), bugMask(0), debugLevel(0), verboseLevel(0), in(d1), out(d2), die(false), pvtOut(false), obsOut(false), navOut(false), tstOut(false), followEOF(false) {} MDPProcessor::MDPProcessor(gpstk::MDPStream& in, std::ofstream& out) : timeFormat("%4Y/%03j/%02H:%02M:%04.1f"), stopTime(gpstk::DayTime::END_OF_TIME), startTime(gpstk::DayTime::BEGINNING_OF_TIME), timeSpan(-1), processBad(false), bugMask(0), debugLevel(0), verboseLevel(0), in(in), out(out), die(false), pvtOut(false), obsOut(false), navOut(false), tstOut(false), followEOF(false) {} void MDPProcessor::process() { MDPHeader header; msgCount=0; firstFC=0; lastFC=0; fcErrorCount=0; while (!die) { in >> header; if (debugLevel>2) { cerr << " Post Read:"; cerr << " " << in.gcount(); if (in.eof()) cerr << " in:eof"; if (in.fail()) cerr << " in.fail()"; if (in.bad()) cerr << " in.bad()"; cerr << endl; } if (in.eof()) { if (followEOF) in.clear(); else die=true; continue; } if (!in) break; if (startTime == DayTime(DayTime::BEGINNING_OF_TIME) && timeSpan>0) { startTime = header.time; if (debugLevel) cout << "startTime: " << startTime << endl; } if (stopTime == DayTime(DayTime::END_OF_TIME) && timeSpan>0) { stopTime = startTime + timeSpan; if (debugLevel) cout << "stopTime: " << stopTime << endl; } if (header.time > stopTime) return; if (header.time < startTime) continue; msgCount++; if (verboseLevel>5 || debugLevel>2) out << "Record: " << in.recordNumber << ", message: " << msgCount << endl; if (msgCount == 1) firstFC = lastFC = in.header.freshnessCount; else { if (in.header.freshnessCount != static_cast<unsigned short>(lastFC+1)) { fcErrorCount++; if (verboseLevel) cout << header.time.printf(timeFormat) <<" Freshness count error. Previous was " << lastFC << " current is " << in.header.freshnessCount << endl; } lastFC = in.header.freshnessCount; } switch (in.header.id) { case gpstk::MDPObsEpoch::myId: if (obsOut) { gpstk::MDPObsEpoch obs; in >> obs; if (obs || processBad) process(obs); } break; case gpstk::MDPPVTSolution::myId: if (pvtOut) { gpstk::MDPPVTSolution pvt; in >> pvt; if (pvt || processBad) process(pvt); } break; case gpstk::MDPNavSubframe::myId: if (navOut) { gpstk::MDPNavSubframe nav; in >> nav; if (nav || processBad) process(nav); } break; case gpstk::MDPSelftestStatus::myId: if (tstOut) { gpstk::MDPSelftestStatus sts; in >> sts; if (sts || processBad) process(sts); } break; } // end of switch() } // end of while() } //----------------------------------------------------------------------------- MDPTableProcessor::MDPTableProcessor(gpstk::MDPStream& in, std::ofstream& out) : MDPProcessor(in, out), headerDone(false) {} //----------------------------------------------------------------------------- void MDPTableProcessor::outputHeader() { if (headerDone) return; if (obsOut) out << "# time, 300, prn, chan, hlth, #SVs, ele, az, code, carrier, LC, SNR, range, phase, doppler" << endl; if (pvtOut) out << "# time, 301, #SV, dtime, ddtime, x, y, z, vx, vy, vz" << endl; if (navOut) out << "# time, 310, prn, carrier_code, range_code, nav_code, word1, word2, ..." << endl; if (tstOut) out << "# time, 400, tstTime, startTime, Tant, Trx, status, cpu, freq, ssw" << endl; headerDone=true; } //----------------------------------------------------------------------------- void MDPTableProcessor::process(const gpstk::MDPObsEpoch& oe) { outputHeader(); MDPObsEpoch::ObsMap::const_iterator i; for (i = oe.obs.begin(); i != oe.obs.end(); i++) { const MDPObsEpoch::Observation& obs=i->second; out << oe.time.printf(timeFormat) << fixed << ", " << setw(3) << oe.id << ", " << setw(2) << (int) oe.prn << ", " << setw(2) << (int) oe.channel << ", " << setw(2) << hex << (int) oe.status << dec << ", " << setw(2) << (int) oe.numSVs << setprecision(1) << ", " << setw(2) << (int) oe.elevation << ", " << setw(3) << (int) oe.azimuth << ", " << setw(1) << obs.range << ", " << setw(1) << obs.carrier << ", " << setw(7) << obs.lockCount << setprecision(2) << ", " << setw(5) << obs.snr << setprecision(4) << ", " << setw(13) << obs.pseudorange << ", " << setw(14) << obs.phase << ", " << setw(10) << obs.doppler << endl; } } //----------------------------------------------------------------------------- void MDPTableProcessor::process(const gpstk::MDPPVTSolution& pvt) { outputHeader(); out << pvt.time.printf(timeFormat) << fixed << ", " << setw(3) << pvt.id << ", " << setw(2) << (int)pvt.numSVs << setprecision(3) << ", " << setw(12) << pvt.dtime*1e9 << setprecision(6) << ", " << setw(9) << pvt.ddtime*1e9 << setprecision(3) << ", " << setw(12) << pvt.x[0] << ", " << setw(12) << pvt.x[1] << ", " << setw(12) << pvt.x[2] << setprecision(3) << ", " << setw(8) << pvt.v[0] << ", " << setw(8) << pvt.v[1] << ", " << setw(8) << pvt.v[2] << endl; } //----------------------------------------------------------------------------- void MDPTableProcessor::process(const gpstk::MDPNavSubframe& sf) { outputHeader(); out << sf.time.printf(timeFormat) << fixed << ", " << setw(3) << sf.id << ", " << setw(2) << sf.prn << ", " << int(sf.carrier) << ", " << int(sf.range) << ", " << int(sf.nav); if (verboseLevel) { out << setfill('0') << hex; for(int i = 1; i < sf.subframe.size(); i++) out << ", " << setw(8) << uppercase << sf.subframe[i]; out << dec << setfill(' '); } out << endl; } //----------------------------------------------------------------------------- void MDPTableProcessor::process(const gpstk::MDPSelftestStatus& sts) { outputHeader(); out << sts.time.printf(timeFormat) << fixed << ", " << setw(3) << sts.id << ", " << sts.selfTestTime.printf("%4F/%9.2g") << ", " << sts.firstPVTTime.printf("%4F/%9.2g") << ", " << setprecision(1) << sts.antennaTemp << ", " << setprecision(1) << sts.receiverTemp << ", " << hex << sts.status << dec << ", " << setprecision(1) << sts.cpuLoad << ", " << hex << sts.extFreqStatus << dec << ", " << hex << sts.saasmStatusWord << dec << endl; } //----------------------------------------------------------------------------- void MDPVerboseProcessor::process(const gpstk::MDPObsEpoch& oe) { if (verboseLevel) { oe.dump(out); out << endl; } else { out << oe.getName() << "-:" << " T:" << oe.time.printf(timeFormat) << left << " #SV:" << setw(2) << (int)oe.numSVs << " Ch:" << setw(2) << (int)oe.channel << " PRN:" << setw(2) << (int)oe.prn << " El:" << setw(2) << (int)oe.elevation; MDPObsEpoch::ObsMap::const_iterator i; for (i = oe.obs.begin(); i != oe.obs.end(); i++) { const MDPObsEpoch::Observation& obs=i->second; out << " " << StringUtils::asString(obs.carrier) << "-" << StringUtils::asString(obs.range); } out << endl; } } //----------------------------------------------------------------------------- void MDPVerboseProcessor::process(const gpstk::MDPPVTSolution& pvt) { if (verboseLevel) { pvt.dump(out); out << endl; } else { out << pvt.getName() << "-:" << " T:" << pvt.time.printf(timeFormat) << left << " #SV:" << setw(2) << (int)pvt.numSVs << " X:" << StringUtils::asString(pvt.x[0], 3) << " Y:" << StringUtils::asString(pvt.x[1], 3) << " Z:" << StringUtils::asString(pvt.x[2], 3) << endl; } } //----------------------------------------------------------------------------- void MDPVerboseProcessor::process(const gpstk::MDPNavSubframe& sf) { if (verboseLevel) { sf.dump(out); out << endl; } else { out << sf.getName() << "-:" << " T:" << sf.time.printf(timeFormat) << " PRN:" << sf.prn << " " << StringUtils::asString(sf.carrier) << "-" << StringUtils::asString(sf.range) << " " << static_cast<int>(sf.nav) << endl; } } //----------------------------------------------------------------------------- void MDPVerboseProcessor::process(const gpstk::MDPSelftestStatus& sts) { sts.dump(out); out << endl; } <commit_msg>removing some debug code<commit_after>#pragma ident "$Id$" //============================================================================ // // This file is part of GPSTk, the GPS Toolkit. // // The GPSTk 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 // any later version. // // The GPSTk 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 GPSTk; if not, write to the Free Software Foundation, // Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Copyright 2004, The University of Texas at Austin // //============================================================================ //============================================================================ // //This software developed by Applied Research Laboratories at the University of //Texas at Austin, under contract to an agency or agencies within the U.S. //Department of Defense. The U.S. Government retains all rights to use, //duplicate, distribute, disclose, or release this software. // //Pursuant to DoD Directive 523024 // // DISTRIBUTION STATEMENT A: This software has been approved for public // release, distribution is unlimited. // //============================================================================= /** @file Various presentations/analysis on MDP streams */ #include "MDPProcessors.hpp" using namespace std; using namespace gpstk; gpstk::MDPStream d1; std::ofstream d2; MDPProcessor::MDPProcessor() : timeFormat("%4Y/%03j/%02H:%02M:%04.1f"), stopTime(gpstk::DayTime::END_OF_TIME), startTime(gpstk::DayTime::BEGINNING_OF_TIME), timeSpan(-1), processBad(false), bugMask(0), debugLevel(0), verboseLevel(0), in(d1), out(d2), die(false), pvtOut(false), obsOut(false), navOut(false), tstOut(false), followEOF(false) {} MDPProcessor::MDPProcessor(gpstk::MDPStream& in, std::ofstream& out) : timeFormat("%4Y/%03j/%02H:%02M:%04.1f"), stopTime(gpstk::DayTime::END_OF_TIME), startTime(gpstk::DayTime::BEGINNING_OF_TIME), timeSpan(-1), processBad(false), bugMask(0), debugLevel(0), verboseLevel(0), in(in), out(out), die(false), pvtOut(false), obsOut(false), navOut(false), tstOut(false), followEOF(false) {} void MDPProcessor::process() { MDPHeader header; msgCount=0; firstFC=0; lastFC=0; fcErrorCount=0; while (!die) { in >> header; if (in.eof()) { if (followEOF) in.clear(); else die=true; continue; } if (!in) break; if (startTime == DayTime(DayTime::BEGINNING_OF_TIME) && timeSpan>0) { startTime = header.time; if (debugLevel) cout << "startTime: " << startTime << endl; } if (stopTime == DayTime(DayTime::END_OF_TIME) && timeSpan>0) { stopTime = startTime + timeSpan; if (debugLevel) cout << "stopTime: " << stopTime << endl; } if (header.time > stopTime) return; if (header.time < startTime) continue; msgCount++; if (verboseLevel>5 || debugLevel>2) out << "Record: " << in.recordNumber << ", message: " << msgCount << endl; if (msgCount == 1) firstFC = lastFC = in.header.freshnessCount; else { if (in.header.freshnessCount != static_cast<unsigned short>(lastFC+1)) { fcErrorCount++; if (verboseLevel) cout << header.time.printf(timeFormat) <<" Freshness count error. Previous was " << lastFC << " current is " << in.header.freshnessCount << endl; } lastFC = in.header.freshnessCount; } switch (in.header.id) { case gpstk::MDPObsEpoch::myId: if (obsOut) { gpstk::MDPObsEpoch obs; in >> obs; if (obs || processBad) process(obs); } break; case gpstk::MDPPVTSolution::myId: if (pvtOut) { gpstk::MDPPVTSolution pvt; in >> pvt; if (pvt || processBad) process(pvt); } break; case gpstk::MDPNavSubframe::myId: if (navOut) { gpstk::MDPNavSubframe nav; in >> nav; if (nav || processBad) process(nav); } break; case gpstk::MDPSelftestStatus::myId: if (tstOut) { gpstk::MDPSelftestStatus sts; in >> sts; if (sts || processBad) process(sts); } break; } // end of switch() } // end of while() } //----------------------------------------------------------------------------- MDPTableProcessor::MDPTableProcessor(gpstk::MDPStream& in, std::ofstream& out) : MDPProcessor(in, out), headerDone(false) {} //----------------------------------------------------------------------------- void MDPTableProcessor::outputHeader() { if (headerDone) return; if (obsOut) out << "# time, 300, prn, chan, hlth, #SVs, ele, az, code, carrier, LC, SNR, range, phase, doppler" << endl; if (pvtOut) out << "# time, 301, #SV, dtime, ddtime, x, y, z, vx, vy, vz" << endl; if (navOut) out << "# time, 310, prn, carrier_code, range_code, nav_code, word1, word2, ..." << endl; if (tstOut) out << "# time, 400, tstTime, startTime, Tant, Trx, status, cpu, freq, ssw" << endl; headerDone=true; } //----------------------------------------------------------------------------- void MDPTableProcessor::process(const gpstk::MDPObsEpoch& oe) { outputHeader(); MDPObsEpoch::ObsMap::const_iterator i; for (i = oe.obs.begin(); i != oe.obs.end(); i++) { const MDPObsEpoch::Observation& obs=i->second; out << oe.time.printf(timeFormat) << fixed << ", " << setw(3) << oe.id << ", " << setw(2) << (int) oe.prn << ", " << setw(2) << (int) oe.channel << ", " << setw(2) << hex << (int) oe.status << dec << ", " << setw(2) << (int) oe.numSVs << setprecision(1) << ", " << setw(2) << (int) oe.elevation << ", " << setw(3) << (int) oe.azimuth << ", " << setw(1) << obs.range << ", " << setw(1) << obs.carrier << ", " << setw(7) << obs.lockCount << setprecision(2) << ", " << setw(5) << obs.snr << setprecision(4) << ", " << setw(13) << obs.pseudorange << ", " << setw(14) << obs.phase << ", " << setw(10) << obs.doppler << endl; } } //----------------------------------------------------------------------------- void MDPTableProcessor::process(const gpstk::MDPPVTSolution& pvt) { outputHeader(); out << pvt.time.printf(timeFormat) << fixed << ", " << setw(3) << pvt.id << ", " << setw(2) << (int)pvt.numSVs << setprecision(3) << ", " << setw(12) << pvt.dtime*1e9 << setprecision(6) << ", " << setw(9) << pvt.ddtime*1e9 << setprecision(3) << ", " << setw(12) << pvt.x[0] << ", " << setw(12) << pvt.x[1] << ", " << setw(12) << pvt.x[2] << setprecision(3) << ", " << setw(8) << pvt.v[0] << ", " << setw(8) << pvt.v[1] << ", " << setw(8) << pvt.v[2] << endl; } //----------------------------------------------------------------------------- void MDPTableProcessor::process(const gpstk::MDPNavSubframe& sf) { outputHeader(); out << sf.time.printf(timeFormat) << fixed << ", " << setw(3) << sf.id << ", " << setw(2) << sf.prn << ", " << int(sf.carrier) << ", " << int(sf.range) << ", " << int(sf.nav); if (verboseLevel) { out << setfill('0') << hex; for(int i = 1; i < sf.subframe.size(); i++) out << ", " << setw(8) << uppercase << sf.subframe[i]; out << dec << setfill(' '); } out << endl; } //----------------------------------------------------------------------------- void MDPTableProcessor::process(const gpstk::MDPSelftestStatus& sts) { outputHeader(); out << sts.time.printf(timeFormat) << fixed << ", " << setw(3) << sts.id << ", " << sts.selfTestTime.printf("%4F/%9.2g") << ", " << sts.firstPVTTime.printf("%4F/%9.2g") << ", " << setprecision(1) << sts.antennaTemp << ", " << setprecision(1) << sts.receiverTemp << ", " << hex << sts.status << dec << ", " << setprecision(1) << sts.cpuLoad << ", " << hex << sts.extFreqStatus << dec << ", " << hex << sts.saasmStatusWord << dec << endl; } //----------------------------------------------------------------------------- void MDPVerboseProcessor::process(const gpstk::MDPObsEpoch& oe) { if (verboseLevel) { oe.dump(out); out << endl; } else { out << oe.getName() << "-:" << " T:" << oe.time.printf(timeFormat) << left << " #SV:" << setw(2) << (int)oe.numSVs << " Ch:" << setw(2) << (int)oe.channel << " PRN:" << setw(2) << (int)oe.prn << " El:" << setw(2) << (int)oe.elevation; MDPObsEpoch::ObsMap::const_iterator i; for (i = oe.obs.begin(); i != oe.obs.end(); i++) { const MDPObsEpoch::Observation& obs=i->second; out << " " << StringUtils::asString(obs.carrier) << "-" << StringUtils::asString(obs.range); } out << endl; } } //----------------------------------------------------------------------------- void MDPVerboseProcessor::process(const gpstk::MDPPVTSolution& pvt) { if (verboseLevel) { pvt.dump(out); out << endl; } else { out << pvt.getName() << "-:" << " T:" << pvt.time.printf(timeFormat) << left << " #SV:" << setw(2) << (int)pvt.numSVs << " X:" << StringUtils::asString(pvt.x[0], 3) << " Y:" << StringUtils::asString(pvt.x[1], 3) << " Z:" << StringUtils::asString(pvt.x[2], 3) << endl; } } //----------------------------------------------------------------------------- void MDPVerboseProcessor::process(const gpstk::MDPNavSubframe& sf) { if (verboseLevel) { sf.dump(out); out << endl; } else { out << sf.getName() << "-:" << " T:" << sf.time.printf(timeFormat) << " PRN:" << sf.prn << " " << StringUtils::asString(sf.carrier) << "-" << StringUtils::asString(sf.range) << " " << static_cast<int>(sf.nav) << endl; } } //----------------------------------------------------------------------------- void MDPVerboseProcessor::process(const gpstk::MDPSelftestStatus& sts) { sts.dump(out); out << endl; } <|endoftext|>
<commit_before>#include <stdio.h> #include <memory.h> #include <assert.h> #include <stdlib.h> #include <malloc.h> #include "halide_benchmark.h" #include "pipeline_cpu.h" #include "pipeline_hvx64.h" #include "pipeline_hvx128.h" #include "HalideRuntimeHexagonHost.h" #include "HalideBuffer.h" template <typename T> T clamp(T x, T min, T max) { if (x < min) x = min; if (x > max) x = max; return x; } int main(int argc, char **argv) { if (argc < 6) { printf("Usage: %s (cpu|hvx64) timing_iterations M N K\n", argv[0]); return 0; } int (*pipeline)(halide_buffer_t *, halide_buffer_t*, halide_buffer_t*); if (strcmp(argv[1], "cpu") == 0) { pipeline = pipeline_cpu; printf("Using CPU schedule\n"); } else if (strcmp(argv[1], "hvx64") == 0) { pipeline = pipeline_hvx64; printf("Using HVX 64 schedule\n"); } else if (strcmp(argv[1], "hvx128") == 0) { pipeline = pipeline_hvx128; printf("Using HVX 128 schedule\n"); } else { printf("Unknown schedule, valid schedules are cpu, hvx64, or hvx128\n"); return -1; } int iterations = atoi(argv[2]); const int M = atoi(argv[3]); const int N = atoi(argv[4]); const int K = atoi(argv[5]); // Hexagon's device_malloc implementation will also set the host // pointer if it is null, giving a zero copy buffer. Halide::Runtime::Buffer<uint8_t> mat_a(nullptr, N, M); Halide::Runtime::Buffer<uint8_t> mat_b(nullptr, K, N); Halide::Runtime::Buffer<uint32_t> mat_ab(nullptr, K, M); mat_a.device_malloc(halide_hexagon_device_interface()); mat_b.device_malloc(halide_hexagon_device_interface()); mat_ab.device_malloc(halide_hexagon_device_interface()); // Fill the input buffer with random data. mat_a.for_each_value([&](uint8_t &x) { x = static_cast<uint8_t>(rand()); }); mat_b.for_each_value([&](uint8_t &x) { x = static_cast<uint8_t>(rand()); }); // To avoid the cost of powering HVX on in each call of the // pipeline, power it on once now. Also, set Hexagon performance to turbo. halide_hexagon_set_performance_mode(nullptr, halide_hexagon_power_turbo); halide_hexagon_power_hvx_on(nullptr); printf("Running pipeline...\n"); double time = Halide::Tools::benchmark(iterations, 1, [&]() { int result = pipeline(mat_a, mat_b, mat_ab); if (result != 0) { printf("pipeline failed! %d\n", result); } }); printf("Done, time: %g s\n", time); // We're done with HVX, power it off, and reset the performance mode // to default to save power. halide_hexagon_power_hvx_off(nullptr); halide_hexagon_set_performance_mode(nullptr, halide_hexagon_power_default); // Copy the output back to the host. If the buffer is zero-copy (as // it should be on a real device), this will be a no-op. mat_ab.copy_to_host(); // Validate that the algorithm did what we expect. mat_ab.for_each_element([&](int x, int y) { // This reference implementation is very slow, so only check a subset of the result. if ((y * N + x) % 100 != 0) { return; } uint32_t ab_xy = 0; for (int k = 0; k < K; k++) { ab_xy += static_cast<uint32_t>(mat_a(k, y))*static_cast<uint32_t>(mat_b(x, k)); } if (ab_xy != mat_ab(x, y)) { printf("Mismatch at %d %d: %d != %d\n", x, y, ab_xy, mat_ab(x, y)); abort(); } }); printf("Success!\n"); return 0; } <commit_msg>Update hexagon_matmul to recent generator changes<commit_after>#include <stdio.h> #include <memory.h> #include <assert.h> #include <stdlib.h> #include <malloc.h> #include "halide_benchmark.h" #include "matmul_cpu.h" #include "matmul_hvx64.h" #include "matmul_hvx128.h" #include "HalideRuntimeHexagonHost.h" #include "HalideBuffer.h" template <typename T> T clamp(T x, T min, T max) { if (x < min) x = min; if (x > max) x = max; return x; } int main(int argc, char **argv) { if (argc < 6) { printf("Usage: %s (cpu|hvx64) timing_iterations M N K\n", argv[0]); return 0; } int (*pipeline)(halide_buffer_t *, halide_buffer_t*, halide_buffer_t*); if (strcmp(argv[1], "cpu") == 0) { pipeline = matmul_cpu; printf("Using CPU schedule\n"); } else if (strcmp(argv[1], "hvx64") == 0) { pipeline = matmul_hvx64; printf("Using HVX 64 schedule\n"); } else if (strcmp(argv[1], "hvx128") == 0) { pipeline = matmul_hvx128; printf("Using HVX 128 schedule\n"); } else { printf("Unknown schedule, valid schedules are cpu, hvx64, or hvx128\n"); return -1; } int iterations = atoi(argv[2]); const int M = atoi(argv[3]); const int N = atoi(argv[4]); const int K = atoi(argv[5]); // Hexagon's device_malloc implementation will also set the host // pointer if it is null, giving a zero copy buffer. Halide::Runtime::Buffer<uint8_t> mat_a(nullptr, N, M); Halide::Runtime::Buffer<uint8_t> mat_b(nullptr, K, N); Halide::Runtime::Buffer<uint32_t> mat_ab(nullptr, K, M); mat_a.device_malloc(halide_hexagon_device_interface()); mat_b.device_malloc(halide_hexagon_device_interface()); mat_ab.device_malloc(halide_hexagon_device_interface()); // Fill the input buffer with random data. mat_a.for_each_value([&](uint8_t &x) { x = static_cast<uint8_t>(rand()); }); mat_b.for_each_value([&](uint8_t &x) { x = static_cast<uint8_t>(rand()); }); // To avoid the cost of powering HVX on in each call of the // pipeline, power it on once now. Also, set Hexagon performance to turbo. halide_hexagon_set_performance_mode(nullptr, halide_hexagon_power_turbo); halide_hexagon_power_hvx_on(nullptr); printf("Running pipeline...\n"); double time = Halide::Tools::benchmark(iterations, 1, [&]() { int result = pipeline(mat_a, mat_b, mat_ab); if (result != 0) { printf("pipeline failed! %d\n", result); } }); printf("Done, time: %g s\n", time); // We're done with HVX, power it off, and reset the performance mode // to default to save power. halide_hexagon_power_hvx_off(nullptr); halide_hexagon_set_performance_mode(nullptr, halide_hexagon_power_default); // Copy the output back to the host. If the buffer is zero-copy (as // it should be on a real device), this will be a no-op. mat_ab.copy_to_host(); // Validate that the algorithm did what we expect. mat_ab.for_each_element([&](int x, int y) { // This reference implementation is very slow, so only check a subset of the result. if ((y * N + x) % 100 != 0) { return; } uint32_t ab_xy = 0; for (int k = 0; k < K; k++) { ab_xy += static_cast<uint32_t>(mat_a(k, y))*static_cast<uint32_t>(mat_b(x, k)); } if (ab_xy != mat_ab(x, y)) { printf("Mismatch at %d %d: %d != %d\n", x, y, ab_xy, mat_ab(x, y)); abort(); } }); printf("Success!\n"); return 0; } <|endoftext|>
<commit_before>#include "terminal.h" #include <iostream> #include "logging.h" #include "singletons.h" #include <unistd.h> #include <sys/wait.h> #include <iostream> //TODO: remove using namespace std; //TODO: remove //TODO: Windows... //A working implementation of popen3, with all pipes getting closed properly. //TODO: Eidheim is going to publish this one on his github, along with example uses pid_t popen3(const char *command, int &stdin, int &stdout, int &stderr) { pid_t pid; int p_stdin[2], p_stdout[2], p_stderr[2]; if (pipe(p_stdin) != 0 || pipe(p_stdout) != 0 || pipe(p_stderr) != 0) { close(p_stdin[0]); close(p_stdout[0]); close(p_stderr[0]); close(p_stdin[1]); close(p_stdout[1]); close(p_stderr[1]); return -1; } pid = fork(); if (pid < 0) { close(p_stdin[0]); close(p_stdout[0]); close(p_stderr[0]); close(p_stdin[1]); close(p_stdout[1]); close(p_stderr[1]); return pid; } else if (pid == 0) { close(p_stdin[1]); close(p_stdout[0]); close(p_stderr[0]); dup2(p_stdin[0], 0); dup2(p_stdout[1], 1); dup2(p_stderr[1], 2); setpgid(0, 0); execl("/bin/sh", "sh", "-c", command, NULL); perror("execl"); exit(EXIT_FAILURE); } close(p_stdin[0]); close(p_stdout[1]); close(p_stderr[1]); stdin = p_stdin[1]; stdout = p_stdout[0]; stderr = p_stderr[0]; return pid; } Terminal::InProgress::InProgress(const std::string& start_msg): stop(false) { waiting_print.connect([this](){ Singleton::terminal()->print(line_nr-1, "."); }); start(start_msg); } Terminal::InProgress::~InProgress() { stop=true; if(wait_thread.joinable()) wait_thread.join(); } void Terminal::InProgress::start(const std::string& msg) { line_nr=Singleton::terminal()->print(msg+"...\n"); wait_thread=std::thread([this](){ size_t c=0; while(!stop) { if(c%100==0) waiting_print(); std::this_thread::sleep_for(std::chrono::milliseconds(10)); c++; } }); } void Terminal::InProgress::done(const std::string& msg) { if(!stop) { stop=true; Singleton::terminal()->print(line_nr-1, msg); } } void Terminal::InProgress::cancel(const std::string& msg) { if(!stop) { stop=true; Singleton::terminal()->print(line_nr-1, msg); } } Terminal::Terminal() { set_editable(false); signal_size_allocate().connect([this](Gtk::Allocation& allocation){ auto end=get_buffer()->create_mark(get_buffer()->end()); scroll_to(end); get_buffer()->delete_mark(end); }); bold_tag=get_buffer()->create_tag(); bold_tag->property_weight()=PANGO_WEIGHT_BOLD; async_print_dispatcher.connect([this](){ async_print_strings_mutex.lock(); if(async_print_strings.size()>0) { for(auto &string_bold: async_print_strings) print(string_bold.first, string_bold.second); async_print_strings.clear(); } async_print_strings_mutex.unlock(); }); } int Terminal::execute(const std::string &command, const boost::filesystem::path &path) { std::string cd_path_and_command; if(path!="") { //TODO: Windows... cd_path_and_command="cd "+path.string()+" && "+command; } else cd_path_and_command=command; int stdin, stdout, stderr; auto pid=popen3(cd_path_and_command.c_str(), stdin, stdout, stderr); if (pid<=0) { async_print("Error: Failed to run command: " + command + "\n"); return -1; } else { std::thread stderr_thread([this, stderr](){ char buffer[1024]; ssize_t n; while ((n=read(stderr, buffer, 1024)) > 0) { std::string message; for(ssize_t c=0;c<n;c++) message+=buffer[c]; async_print(message, true); } }); stderr_thread.detach(); std::thread stdout_thread([this, stdout](){ char buffer[1024]; ssize_t n; INFO("read"); while ((n=read(stdout, buffer, 1024)) > 0) { std::string message; for(ssize_t c=0;c<n;c++) message+=buffer[c]; async_print(message); } }); stdout_thread.detach(); int exit_code; waitpid(pid, &exit_code, 0); close(stdin); close(stdout); close(stderr); return exit_code; } } void Terminal::async_execute(const std::string &command, const boost::filesystem::path &path, std::function<void(int exit_code)> callback) { std::thread async_execute_thread([this, command, path, callback](){ std::string cd_path_and_command; if(path!="") { //TODO: Windows... cd_path_and_command="cd "+path.string()+" && "+command; } else cd_path_and_command=command; int stdin, stdout, stderr; async_executes_mutex.lock(); stdin_buffer.clear(); auto pid=popen3(cd_path_and_command.c_str(), stdin, stdout, stderr); async_executes.emplace_back(pid, stdin); async_executes_mutex.unlock(); if (pid<=0) { async_print("Error: Failed to run command: " + command + "\n"); if(callback) callback(-1); } else { std::thread stderr_thread([this, stderr](){ char buffer[1024]; ssize_t n; while ((n=read(stderr, buffer, 1024)) > 0) { std::string message; for(ssize_t c=0;c<n;c++) message+=buffer[c]; async_print(message, true); } }); stderr_thread.detach(); std::thread stdout_thread([this, stdout](){ char buffer[1024]; ssize_t n; INFO("read"); while ((n=read(stdout, buffer, 1024)) > 0) { std::string message; for(ssize_t c=0;c<n;c++) message+=buffer[c]; async_print(message); } }); stdout_thread.detach(); int exit_code; waitpid(pid, &exit_code, 0); async_executes_mutex.lock(); for(auto it=async_executes.begin();it!=async_executes.end();it++) { if(it->first==pid) { async_executes.erase(it); break; } } stdin_buffer.clear(); close(stdin); close(stdout); close(stderr); async_executes_mutex.unlock(); if(callback) callback(exit_code); } }); async_execute_thread.detach(); } void Terminal::kill_last_async_execute(bool force) { async_executes_mutex.lock(); if(async_executes.size()>0) { if(force) kill(-async_executes.back().first, SIGTERM); else kill(-async_executes.back().first, SIGINT); } async_executes_mutex.unlock(); } void Terminal::kill_async_executes(bool force) { async_executes_mutex.lock(); for(auto &async_execute: async_executes) { if(force) kill(-async_execute.first, SIGTERM); else kill(-async_execute.first, SIGINT); } async_executes_mutex.unlock(); } int Terminal::print(const std::string &message, bool bold){ INFO("Terminal: PrintMessage"); if(bold) get_buffer()->insert_with_tag(get_buffer()->end(), message, bold_tag); else get_buffer()->insert(get_buffer()->end(), message); return get_buffer()->end().get_line(); } void Terminal::print(int line_nr, const std::string &message, bool bold){ INFO("Terminal: PrintMessage at line " << line_nr); auto iter=get_buffer()->get_iter_at_line(line_nr); while(!iter.ends_line()) iter++; if(bold) get_buffer()->insert_with_tag(iter, message, bold_tag); else get_buffer()->insert(iter, message); } std::shared_ptr<Terminal::InProgress> Terminal::print_in_progress(std::string start_msg) { std::shared_ptr<Terminal::InProgress> in_progress=std::shared_ptr<Terminal::InProgress>(new Terminal::InProgress(start_msg)); return in_progress; } void Terminal::async_print(const std::string &message, bool bold) { async_print_strings_mutex.lock(); bool dispatch=true; if(async_print_strings.size()>0) dispatch=false; async_print_strings.emplace_back(message, bold); async_print_strings_mutex.unlock(); if(dispatch) async_print_dispatcher(); } bool Terminal::on_key_press_event(GdkEventKey *event) { async_executes_mutex.lock(); if(async_executes.size()>0) { get_buffer()->place_cursor(get_buffer()->end()); auto unicode=gdk_keyval_to_unicode(event->keyval); char chr=(char)unicode; if(unicode>=32 && unicode<=126) { stdin_buffer+=chr; get_buffer()->insert_at_cursor(stdin_buffer.substr(stdin_buffer.size()-1)); scroll_to(get_buffer()->get_insert()); } else if(event->keyval==GDK_KEY_BackSpace) { if(stdin_buffer.size()>0 && get_buffer()->get_char_count()>0) { auto iter=get_buffer()->end(); iter--; stdin_buffer.pop_back(); get_buffer()->erase(iter, get_buffer()->end()); scroll_to(get_buffer()->get_insert()); } } else if(event->keyval==GDK_KEY_Return) { stdin_buffer+='\n'; write(async_executes.back().second, stdin_buffer.c_str(), stdin_buffer.size()); get_buffer()->insert_at_cursor(stdin_buffer.substr(stdin_buffer.size()-1)); stdin_buffer.clear(); scroll_to(get_buffer()->get_insert()); } } async_executes_mutex.unlock(); return true; } <commit_msg>Added TODO on how to get colors in terminal, for instance from cmake and make.<commit_after>#include "terminal.h" #include <iostream> #include "logging.h" #include "singletons.h" #include <unistd.h> #include <sys/wait.h> #include <iostream> //TODO: remove using namespace std; //TODO: remove //TODO: Windows... //A working implementation of popen3, with all pipes getting closed properly. //TODO: Eidheim is going to publish this one on his github, along with example uses pid_t popen3(const char *command, int &stdin, int &stdout, int &stderr) { pid_t pid; int p_stdin[2], p_stdout[2], p_stderr[2]; if (pipe(p_stdin) != 0 || pipe(p_stdout) != 0 || pipe(p_stderr) != 0) { close(p_stdin[0]); close(p_stdout[0]); close(p_stderr[0]); close(p_stdin[1]); close(p_stdout[1]); close(p_stderr[1]); return -1; } pid = fork(); if (pid < 0) { close(p_stdin[0]); close(p_stdout[0]); close(p_stderr[0]); close(p_stdin[1]); close(p_stdout[1]); close(p_stderr[1]); return pid; } else if (pid == 0) { close(p_stdin[1]); close(p_stdout[0]); close(p_stderr[0]); dup2(p_stdin[0], 0); dup2(p_stdout[1], 1); dup2(p_stderr[1], 2); setpgid(0, 0); //TODO: See here on how to emulate tty for colors: http://stackoverflow.com/questions/1401002/trick-an-application-into-thinking-its-stdin-is-interactive-not-a-pipe //TODO: One solution is: echo "command;exit"|script -q /dev/null execl("/bin/sh", "sh", "-c", command, NULL); perror("execl"); exit(EXIT_FAILURE); } close(p_stdin[0]); close(p_stdout[1]); close(p_stderr[1]); stdin = p_stdin[1]; stdout = p_stdout[0]; stderr = p_stderr[0]; return pid; } Terminal::InProgress::InProgress(const std::string& start_msg): stop(false) { waiting_print.connect([this](){ Singleton::terminal()->print(line_nr-1, "."); }); start(start_msg); } Terminal::InProgress::~InProgress() { stop=true; if(wait_thread.joinable()) wait_thread.join(); } void Terminal::InProgress::start(const std::string& msg) { line_nr=Singleton::terminal()->print(msg+"...\n"); wait_thread=std::thread([this](){ size_t c=0; while(!stop) { if(c%100==0) waiting_print(); std::this_thread::sleep_for(std::chrono::milliseconds(10)); c++; } }); } void Terminal::InProgress::done(const std::string& msg) { if(!stop) { stop=true; Singleton::terminal()->print(line_nr-1, msg); } } void Terminal::InProgress::cancel(const std::string& msg) { if(!stop) { stop=true; Singleton::terminal()->print(line_nr-1, msg); } } Terminal::Terminal() { set_editable(false); signal_size_allocate().connect([this](Gtk::Allocation& allocation){ auto end=get_buffer()->create_mark(get_buffer()->end()); scroll_to(end); get_buffer()->delete_mark(end); }); bold_tag=get_buffer()->create_tag(); bold_tag->property_weight()=PANGO_WEIGHT_BOLD; async_print_dispatcher.connect([this](){ async_print_strings_mutex.lock(); if(async_print_strings.size()>0) { for(auto &string_bold: async_print_strings) print(string_bold.first, string_bold.second); async_print_strings.clear(); } async_print_strings_mutex.unlock(); }); } int Terminal::execute(const std::string &command, const boost::filesystem::path &path) { std::string cd_path_and_command; if(path!="") { //TODO: Windows... cd_path_and_command="cd "+path.string()+" && "+command; } else cd_path_and_command=command; int stdin, stdout, stderr; auto pid=popen3(cd_path_and_command.c_str(), stdin, stdout, stderr); if (pid<=0) { async_print("Error: Failed to run command: " + command + "\n"); return -1; } else { std::thread stderr_thread([this, stderr](){ char buffer[1024]; ssize_t n; while ((n=read(stderr, buffer, 1024)) > 0) { std::string message; for(ssize_t c=0;c<n;c++) message+=buffer[c]; async_print(message, true); } }); stderr_thread.detach(); std::thread stdout_thread([this, stdout](){ char buffer[1024]; ssize_t n; INFO("read"); while ((n=read(stdout, buffer, 1024)) > 0) { std::string message; for(ssize_t c=0;c<n;c++) message+=buffer[c]; async_print(message); } }); stdout_thread.detach(); int exit_code; waitpid(pid, &exit_code, 0); close(stdin); close(stdout); close(stderr); return exit_code; } } void Terminal::async_execute(const std::string &command, const boost::filesystem::path &path, std::function<void(int exit_code)> callback) { std::thread async_execute_thread([this, command, path, callback](){ std::string cd_path_and_command; if(path!="") { //TODO: Windows... cd_path_and_command="cd "+path.string()+" && "+command; } else cd_path_and_command=command; int stdin, stdout, stderr; async_executes_mutex.lock(); stdin_buffer.clear(); auto pid=popen3(cd_path_and_command.c_str(), stdin, stdout, stderr); async_executes.emplace_back(pid, stdin); async_executes_mutex.unlock(); if (pid<=0) { async_print("Error: Failed to run command: " + command + "\n"); if(callback) callback(-1); } else { std::thread stderr_thread([this, stderr](){ char buffer[1024]; ssize_t n; while ((n=read(stderr, buffer, 1024)) > 0) { std::string message; for(ssize_t c=0;c<n;c++) message+=buffer[c]; async_print(message, true); } }); stderr_thread.detach(); std::thread stdout_thread([this, stdout](){ char buffer[1024]; ssize_t n; INFO("read"); while ((n=read(stdout, buffer, 1024)) > 0) { std::string message; for(ssize_t c=0;c<n;c++) message+=buffer[c]; async_print(message); } }); stdout_thread.detach(); int exit_code; waitpid(pid, &exit_code, 0); async_executes_mutex.lock(); for(auto it=async_executes.begin();it!=async_executes.end();it++) { if(it->first==pid) { async_executes.erase(it); break; } } stdin_buffer.clear(); close(stdin); close(stdout); close(stderr); async_executes_mutex.unlock(); if(callback) callback(exit_code); } }); async_execute_thread.detach(); } void Terminal::kill_last_async_execute(bool force) { async_executes_mutex.lock(); if(async_executes.size()>0) { if(force) kill(-async_executes.back().first, SIGTERM); else kill(-async_executes.back().first, SIGINT); } async_executes_mutex.unlock(); } void Terminal::kill_async_executes(bool force) { async_executes_mutex.lock(); for(auto &async_execute: async_executes) { if(force) kill(-async_execute.first, SIGTERM); else kill(-async_execute.first, SIGINT); } async_executes_mutex.unlock(); } int Terminal::print(const std::string &message, bool bold){ INFO("Terminal: PrintMessage"); if(bold) get_buffer()->insert_with_tag(get_buffer()->end(), message, bold_tag); else get_buffer()->insert(get_buffer()->end(), message); return get_buffer()->end().get_line(); } void Terminal::print(int line_nr, const std::string &message, bool bold){ INFO("Terminal: PrintMessage at line " << line_nr); auto iter=get_buffer()->get_iter_at_line(line_nr); while(!iter.ends_line()) iter++; if(bold) get_buffer()->insert_with_tag(iter, message, bold_tag); else get_buffer()->insert(iter, message); } std::shared_ptr<Terminal::InProgress> Terminal::print_in_progress(std::string start_msg) { std::shared_ptr<Terminal::InProgress> in_progress=std::shared_ptr<Terminal::InProgress>(new Terminal::InProgress(start_msg)); return in_progress; } void Terminal::async_print(const std::string &message, bool bold) { async_print_strings_mutex.lock(); bool dispatch=true; if(async_print_strings.size()>0) dispatch=false; async_print_strings.emplace_back(message, bold); async_print_strings_mutex.unlock(); if(dispatch) async_print_dispatcher(); } bool Terminal::on_key_press_event(GdkEventKey *event) { async_executes_mutex.lock(); if(async_executes.size()>0) { get_buffer()->place_cursor(get_buffer()->end()); auto unicode=gdk_keyval_to_unicode(event->keyval); char chr=(char)unicode; if(unicode>=32 && unicode<=126) { stdin_buffer+=chr; get_buffer()->insert_at_cursor(stdin_buffer.substr(stdin_buffer.size()-1)); scroll_to(get_buffer()->get_insert()); } else if(event->keyval==GDK_KEY_BackSpace) { if(stdin_buffer.size()>0 && get_buffer()->get_char_count()>0) { auto iter=get_buffer()->end(); iter--; stdin_buffer.pop_back(); get_buffer()->erase(iter, get_buffer()->end()); scroll_to(get_buffer()->get_insert()); } } else if(event->keyval==GDK_KEY_Return) { stdin_buffer+='\n'; write(async_executes.back().second, stdin_buffer.c_str(), stdin_buffer.size()); get_buffer()->insert_at_cursor(stdin_buffer.substr(stdin_buffer.size()-1)); stdin_buffer.clear(); scroll_to(get_buffer()->get_insert()); } } async_executes_mutex.unlock(); return true; } <|endoftext|>
<commit_before>/* * Copyright 2011 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "gm.h" #include "SkCanvas.h" #include "SkGradientShader.h" namespace skiagm { static void makebm(SkBitmap* bm, int w, int h) { bm->allocN32Pixels(w, h); bm->eraseColor(SK_ColorTRANSPARENT); SkCanvas canvas(*bm); SkScalar s = SkIntToScalar(SkMin32(w, h)); SkPoint pts[] = { { 0, 0 }, { s, s } }; SkColor colors[] = { SK_ColorRED, SK_ColorGREEN, SK_ColorBLUE }; SkScalar pos[] = { 0, SK_Scalar1/2, SK_Scalar1 }; SkPaint paint; paint.setDither(true); paint.setShader(SkGradientShader::CreateLinear(pts, colors, pos, SK_ARRAY_COUNT(colors), SkShader::kClamp_TileMode))->unref(); canvas.drawPaint(paint); } static SkShader* MakeBitmapShader(SkShader::TileMode tx, SkShader::TileMode ty, int w, int h) { static SkBitmap bmp; if (bmp.isNull()) { makebm(&bmp, w/2, h/4); } return SkShader::CreateBitmapShader(bmp, tx, ty); } /////////////////////////////////////////////////////////////////////////////// struct GradData { int fCount; const SkColor* fColors; const SkScalar* fPos; }; static const SkColor gColors[] = { SK_ColorRED, SK_ColorGREEN, SK_ColorBLUE, SK_ColorWHITE, SK_ColorBLACK }; static const GradData gGradData[] = { { 2, gColors, NULL }, { 5, gColors, NULL }, }; static SkShader* MakeLinear(const SkPoint pts[2], const GradData& data, SkShader::TileMode tm) { return SkGradientShader::CreateLinear(pts, data.fColors, data.fPos, data.fCount, tm); } static SkShader* MakeRadial(const SkPoint pts[2], const GradData& data, SkShader::TileMode tm) { SkPoint center; center.set(SkScalarAve(pts[0].fX, pts[1].fX), SkScalarAve(pts[0].fY, pts[1].fY)); return SkGradientShader::CreateRadial(center, center.fX, data.fColors, data.fPos, data.fCount, tm); } static SkShader* MakeSweep(const SkPoint pts[2], const GradData& data, SkShader::TileMode) { SkPoint center; center.set(SkScalarAve(pts[0].fX, pts[1].fX), SkScalarAve(pts[0].fY, pts[1].fY)); return SkGradientShader::CreateSweep(center.fX, center.fY, data.fColors, data.fPos, data.fCount); } static SkShader* Make2Radial(const SkPoint pts[2], const GradData& data, SkShader::TileMode tm) { SkPoint center0, center1; center0.set(SkScalarAve(pts[0].fX, pts[1].fX), SkScalarAve(pts[0].fY, pts[1].fY)); center1.set(SkScalarInterp(pts[0].fX, pts[1].fX, SkIntToScalar(3)/5), SkScalarInterp(pts[0].fY, pts[1].fY, SkIntToScalar(1)/4)); return SkGradientShader::CreateTwoPointRadial( center1, (pts[1].fX - pts[0].fX) / 7, center0, (pts[1].fX - pts[0].fX) / 2, data.fColors, data.fPos, data.fCount, tm); } typedef SkShader* (*GradMaker)(const SkPoint pts[2], const GradData& data, SkShader::TileMode tm); static const GradMaker gGradMakers[] = { MakeLinear, MakeRadial, MakeSweep, Make2Radial }; /////////////////////////////////////////////////////////////////////////////// class ShaderTextGM : public GM { public: ShaderTextGM() { this->setBGColor(0xFFDDDDDD); } protected: virtual uint32_t onGetFlags() const SK_OVERRIDE { return kSkipTiled_Flag; } SkString onShortName() { return SkString("shadertext"); } SkISize onISize() { return SkISize::Make(1450, 500); } virtual void onDraw(SkCanvas* canvas) { const char text[] = "Shaded Text"; const int textLen = SK_ARRAY_COUNT(text) - 1; const int pointSize = 36; int w = pointSize * textLen; int h = pointSize; SkPoint pts[2] = { { 0, 0 }, { SkIntToScalar(w), SkIntToScalar(h) } }; SkScalar textBase = SkIntToScalar(h/2); SkShader::TileMode tileModes[] = { SkShader::kClamp_TileMode, SkShader::kRepeat_TileMode, SkShader::kMirror_TileMode }; static const int gradCount = SK_ARRAY_COUNT(gGradData) * SK_ARRAY_COUNT(gGradMakers); static const int bmpCount = SK_ARRAY_COUNT(tileModes) * SK_ARRAY_COUNT(tileModes); SkShader* shaders[gradCount + bmpCount]; int shdIdx = 0; for (size_t d = 0; d < SK_ARRAY_COUNT(gGradData); ++d) { for (size_t m = 0; m < SK_ARRAY_COUNT(gGradMakers); ++m) { shaders[shdIdx++] = gGradMakers[m](pts, gGradData[d], SkShader::kClamp_TileMode); } } for (size_t tx = 0; tx < SK_ARRAY_COUNT(tileModes); ++tx) { for (size_t ty = 0; ty < SK_ARRAY_COUNT(tileModes); ++ty) { shaders[shdIdx++] = MakeBitmapShader(tileModes[tx], tileModes[ty], w/8, h); } } SkPaint paint; paint.setDither(true); paint.setAntiAlias(true); sk_tool_utils::set_portable_typeface(&paint); paint.setTextSize(SkIntToScalar(pointSize)); canvas->save(); canvas->translate(SkIntToScalar(20), SkIntToScalar(10)); SkPath path; path.arcTo(SkRect::MakeXYWH(SkIntToScalar(-40), SkIntToScalar(15), SkIntToScalar(300), SkIntToScalar(90)), SkIntToScalar(225), SkIntToScalar(90), false); path.close(); static const int testsPerCol = 8; static const int rowHeight = 60; static const int colWidth = 300; canvas->save(); for (int s = 0; s < static_cast<int>(SK_ARRAY_COUNT(shaders)); s++) { canvas->save(); int i = 2*s; canvas->translate(SkIntToScalar((i / testsPerCol) * colWidth), SkIntToScalar((i % testsPerCol) * rowHeight)); paint.setShader(shaders[s])->unref(); canvas->drawText(text, textLen, 0, textBase, paint); canvas->restore(); canvas->save(); ++i; canvas->translate(SkIntToScalar((i / testsPerCol) * colWidth), SkIntToScalar((i % testsPerCol) * rowHeight)); canvas->drawTextOnPath(text, textLen, path, NULL, paint); canvas->restore(); } canvas->restore(); } private: typedef GM INHERITED; }; /////////////////////////////////////////////////////////////////////////////// static GM* MyFactory(void*) { return new ShaderTextGM; } static GMRegistry reg(MyFactory); } <commit_msg>don't use local static bitmap -- racy and unnecessary<commit_after>/* * Copyright 2011 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "gm.h" #include "SkCanvas.h" #include "SkGradientShader.h" namespace skiagm { static void makebm(SkBitmap* bm, int w, int h) { bm->allocN32Pixels(w, h); bm->eraseColor(SK_ColorTRANSPARENT); SkCanvas canvas(*bm); SkScalar s = SkIntToScalar(SkMin32(w, h)); SkPoint pts[] = { { 0, 0 }, { s, s } }; SkColor colors[] = { SK_ColorRED, SK_ColorGREEN, SK_ColorBLUE }; SkScalar pos[] = { 0, SK_Scalar1/2, SK_Scalar1 }; SkPaint paint; paint.setDither(true); paint.setShader(SkGradientShader::CreateLinear(pts, colors, pos, SK_ARRAY_COUNT(colors), SkShader::kClamp_TileMode))->unref(); canvas.drawPaint(paint); } /////////////////////////////////////////////////////////////////////////////// struct GradData { int fCount; const SkColor* fColors; const SkScalar* fPos; }; static const SkColor gColors[] = { SK_ColorRED, SK_ColorGREEN, SK_ColorBLUE, SK_ColorWHITE, SK_ColorBLACK }; static const GradData gGradData[] = { { 2, gColors, NULL }, { 5, gColors, NULL }, }; static SkShader* MakeLinear(const SkPoint pts[2], const GradData& data, SkShader::TileMode tm) { return SkGradientShader::CreateLinear(pts, data.fColors, data.fPos, data.fCount, tm); } static SkShader* MakeRadial(const SkPoint pts[2], const GradData& data, SkShader::TileMode tm) { SkPoint center; center.set(SkScalarAve(pts[0].fX, pts[1].fX), SkScalarAve(pts[0].fY, pts[1].fY)); return SkGradientShader::CreateRadial(center, center.fX, data.fColors, data.fPos, data.fCount, tm); } static SkShader* MakeSweep(const SkPoint pts[2], const GradData& data, SkShader::TileMode) { SkPoint center; center.set(SkScalarAve(pts[0].fX, pts[1].fX), SkScalarAve(pts[0].fY, pts[1].fY)); return SkGradientShader::CreateSweep(center.fX, center.fY, data.fColors, data.fPos, data.fCount); } static SkShader* Make2Radial(const SkPoint pts[2], const GradData& data, SkShader::TileMode tm) { SkPoint center0, center1; center0.set(SkScalarAve(pts[0].fX, pts[1].fX), SkScalarAve(pts[0].fY, pts[1].fY)); center1.set(SkScalarInterp(pts[0].fX, pts[1].fX, SkIntToScalar(3)/5), SkScalarInterp(pts[0].fY, pts[1].fY, SkIntToScalar(1)/4)); return SkGradientShader::CreateTwoPointRadial( center1, (pts[1].fX - pts[0].fX) / 7, center0, (pts[1].fX - pts[0].fX) / 2, data.fColors, data.fPos, data.fCount, tm); } typedef SkShader* (*GradMaker)(const SkPoint pts[2], const GradData& data, SkShader::TileMode tm); static const GradMaker gGradMakers[] = { MakeLinear, MakeRadial, MakeSweep, Make2Radial }; /////////////////////////////////////////////////////////////////////////////// class ShaderTextGM : public GM { public: ShaderTextGM() { this->setBGColor(0xFFDDDDDD); } protected: virtual uint32_t onGetFlags() const SK_OVERRIDE { return kSkipTiled_Flag; } SkString onShortName() { return SkString("shadertext"); } SkISize onISize() { return SkISize::Make(1450, 500); } virtual void onDraw(SkCanvas* canvas) { const char text[] = "Shaded Text"; const int textLen = SK_ARRAY_COUNT(text) - 1; const int pointSize = 36; const int w = pointSize * textLen; const int h = pointSize; SkPoint pts[2] = { { 0, 0 }, { SkIntToScalar(w), SkIntToScalar(h) } }; SkScalar textBase = SkIntToScalar(h/2); SkShader::TileMode tileModes[] = { SkShader::kClamp_TileMode, SkShader::kRepeat_TileMode, SkShader::kMirror_TileMode }; static const int gradCount = SK_ARRAY_COUNT(gGradData) * SK_ARRAY_COUNT(gGradMakers); static const int bmpCount = SK_ARRAY_COUNT(tileModes) * SK_ARRAY_COUNT(tileModes); SkShader* shaders[gradCount + bmpCount]; int shdIdx = 0; for (size_t d = 0; d < SK_ARRAY_COUNT(gGradData); ++d) { for (size_t m = 0; m < SK_ARRAY_COUNT(gGradMakers); ++m) { shaders[shdIdx++] = gGradMakers[m](pts, gGradData[d], SkShader::kClamp_TileMode); } } SkBitmap bm; makebm(&bm, w/16, h/4); for (size_t tx = 0; tx < SK_ARRAY_COUNT(tileModes); ++tx) { for (size_t ty = 0; ty < SK_ARRAY_COUNT(tileModes); ++ty) { shaders[shdIdx++] = SkShader::CreateBitmapShader(bm, tileModes[tx], tileModes[ty]); } } SkPaint paint; paint.setDither(true); paint.setAntiAlias(true); sk_tool_utils::set_portable_typeface(&paint); paint.setTextSize(SkIntToScalar(pointSize)); canvas->save(); canvas->translate(SkIntToScalar(20), SkIntToScalar(10)); SkPath path; path.arcTo(SkRect::MakeXYWH(SkIntToScalar(-40), SkIntToScalar(15), SkIntToScalar(300), SkIntToScalar(90)), SkIntToScalar(225), SkIntToScalar(90), false); path.close(); static const int testsPerCol = 8; static const int rowHeight = 60; static const int colWidth = 300; canvas->save(); for (int s = 0; s < static_cast<int>(SK_ARRAY_COUNT(shaders)); s++) { canvas->save(); int i = 2*s; canvas->translate(SkIntToScalar((i / testsPerCol) * colWidth), SkIntToScalar((i % testsPerCol) * rowHeight)); paint.setShader(shaders[s])->unref(); canvas->drawText(text, textLen, 0, textBase, paint); canvas->restore(); canvas->save(); ++i; canvas->translate(SkIntToScalar((i / testsPerCol) * colWidth), SkIntToScalar((i % testsPerCol) * rowHeight)); canvas->drawTextOnPath(text, textLen, path, NULL, paint); canvas->restore(); } canvas->restore(); } private: typedef GM INHERITED; }; /////////////////////////////////////////////////////////////////////////////// static GM* MyFactory(void*) { return new ShaderTextGM; } static GMRegistry reg(MyFactory); } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: dlg_ObjectProperties.hxx,v $ * * $Revision: 1.6 $ * * last change: $Author: vg $ $Date: 2007-05-22 17:59:32 $ * * 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 _CHART2_DLG_OBJECTPROPERTIES_HXX #define _CHART2_DLG_OBJECTPROPERTIES_HXX #include "ObjectIdentifier.hxx" #ifndef _SFXTABDLG_HXX #include <sfx2/tabdlg.hxx> #endif // header for typedef ChangeType #ifndef _SVX_TAB_AREA_HXX #include <svx/tabarea.hxx> #endif #ifndef _COM_SUN_STAR_UTIL_XNUMBERFORMATSSUPPLIER_HPP_ #include <com/sun/star/util/XNumberFormatsSupplier.hpp> #endif //............................................................................. namespace chart { //............................................................................. class ObjectPropertiesDialogParameter { public: ObjectPropertiesDialogParameter( const rtl::OUString& rObjectCID ); virtual ~ObjectPropertiesDialogParameter(); void init( const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XModel >& xModel ); ObjectType getObjectType() const; rtl::OUString getLocalizedName() const; bool HasGeometryProperties() const; bool HasStatisticProperties() const; bool HasRegressionProperties() const; bool ProvidesSecondaryYAxis() const; bool ProvidesOverlapAndGapWidth() const; bool HasAreaProperties() const; bool HasLineProperties() const; bool HasSymbolProperties() const; bool HasScaleProperties() const; bool CanAxisLabelsBeStaggered() const; private: rtl::OUString m_aObjectCID; ObjectType m_eObjectType; bool m_bAffectsMultipleObjects;//is true if more than one object of the given type will be changed (e.g. all axes or all titles) rtl::OUString m_aLocalizedName; bool m_bHasGeometryProperties; bool m_bHasStatisticProperties; bool m_bHasRegressionProperties; bool m_bProvidesSecondaryYAxis; bool m_bProvidesOverlapAndGapWidth; bool m_bHasAreaProperties; bool m_bHasLineProperties; bool m_bHasSymbolProperties; bool m_bHasScaleProperties; bool m_bCanAxisLabelsBeStaggered; }; /************************************************************************* |* |* dialog for properties of different chart object |* \************************************************************************/ class ViewElementListProvider; class SchAttribTabDlg : public SfxTabDialog { private: ObjectType eObjectType; bool bAffectsMultipleObjects;//is true if more than one object of the given type will be changed (e.g. all axes or all titles) USHORT nDlgType; USHORT nPageType; const ObjectPropertiesDialogParameter * const m_pParameter; const ViewElementListProvider* const m_pViewElementListProvider; SvNumberFormatter* m_pNumberFormatter; SfxItemSet* m_pSymbolShapeProperties; Graphic* m_pAutoSymbolGraphic; virtual void PageCreated(USHORT nId, SfxTabPage& rPage); public: SchAttribTabDlg(Window* pParent, const SfxItemSet* pAttr, const ObjectPropertiesDialogParameter* pDialogParameter, const ViewElementListProvider* pViewElementListProvider, const ::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormatsSupplier >& xNumberFormatsSupplier ); virtual ~SchAttribTabDlg(); //pSymbolShapeProperties: Properties to be set on the symbollist shapes //pAutoSymbolGraphic: Graphic to be shown if AutoSymbol gets selected //this class takes ownership over both parameter void setSymbolInformation( SfxItemSet* pSymbolShapeProperties, Graphic* pAutoSymbolGraphic ); }; //............................................................................. } //namespace chart //............................................................................. #endif <commit_msg>INTEGRATION: CWS chart07 (1.6.12); FILE MERGED 2007/07/06 13:29:43 iha 1.6.12.1: #i8877# Error bar values limited to 0.1 and above<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: dlg_ObjectProperties.hxx,v $ * * $Revision: 1.7 $ * * last change: $Author: rt $ $Date: 2007-07-25 08:40:02 $ * * 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 _CHART2_DLG_OBJECTPROPERTIES_HXX #define _CHART2_DLG_OBJECTPROPERTIES_HXX #include "ObjectIdentifier.hxx" #ifndef _SFXTABDLG_HXX #include <sfx2/tabdlg.hxx> #endif // header for typedef ChangeType #ifndef _SVX_TAB_AREA_HXX #include <svx/tabarea.hxx> #endif #ifndef _COM_SUN_STAR_UTIL_XNUMBERFORMATSSUPPLIER_HPP_ #include <com/sun/star/util/XNumberFormatsSupplier.hpp> #endif //............................................................................. namespace chart { //............................................................................. class ObjectPropertiesDialogParameter { public: ObjectPropertiesDialogParameter( const rtl::OUString& rObjectCID ); virtual ~ObjectPropertiesDialogParameter(); void init( const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XModel >& xModel ); ObjectType getObjectType() const; rtl::OUString getLocalizedName() const; bool HasGeometryProperties() const; bool HasStatisticProperties() const; bool HasRegressionProperties() const; bool ProvidesSecondaryYAxis() const; bool ProvidesOverlapAndGapWidth() const; bool HasAreaProperties() const; bool HasLineProperties() const; bool HasSymbolProperties() const; bool HasScaleProperties() const; bool CanAxisLabelsBeStaggered() const; private: rtl::OUString m_aObjectCID; ObjectType m_eObjectType; bool m_bAffectsMultipleObjects;//is true if more than one object of the given type will be changed (e.g. all axes or all titles) rtl::OUString m_aLocalizedName; bool m_bHasGeometryProperties; bool m_bHasStatisticProperties; bool m_bHasRegressionProperties; bool m_bProvidesSecondaryYAxis; bool m_bProvidesOverlapAndGapWidth; bool m_bHasAreaProperties; bool m_bHasLineProperties; bool m_bHasSymbolProperties; bool m_bHasScaleProperties; bool m_bCanAxisLabelsBeStaggered; }; /************************************************************************* |* |* dialog for properties of different chart object |* \************************************************************************/ class ViewElementListProvider; class SchAttribTabDlg : public SfxTabDialog { private: ObjectType eObjectType; bool bAffectsMultipleObjects;//is true if more than one object of the given type will be changed (e.g. all axes or all titles) USHORT nDlgType; USHORT nPageType; const ObjectPropertiesDialogParameter * const m_pParameter; const ViewElementListProvider* const m_pViewElementListProvider; SvNumberFormatter* m_pNumberFormatter; SfxItemSet* m_pSymbolShapeProperties; Graphic* m_pAutoSymbolGraphic; double m_fAxisMinorStepWidthForErrorBarDecimals; virtual void PageCreated(USHORT nId, SfxTabPage& rPage); public: SchAttribTabDlg(Window* pParent, const SfxItemSet* pAttr, const ObjectPropertiesDialogParameter* pDialogParameter, const ViewElementListProvider* pViewElementListProvider, const ::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormatsSupplier >& xNumberFormatsSupplier ); virtual ~SchAttribTabDlg(); //pSymbolShapeProperties: Properties to be set on the symbollist shapes //pAutoSymbolGraphic: Graphic to be shown if AutoSymbol gets selected //this class takes ownership over both parameter void setSymbolInformation( SfxItemSet* pSymbolShapeProperties, Graphic* pAutoSymbolGraphic ); void SetAxisMinorStepWidthForErrorBarDecimals( double fMinorStepWidth ); }; //............................................................................. } //namespace chart //............................................................................. #endif <|endoftext|>
<commit_before>// Copyright (c) 2011 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 "chrome/browser/autocomplete/extension_app_provider.h" #include <algorithm> #include <cmath> #include "base/string16.h" #include "base/utf_string_conversions.h" #include "chrome/browser/extensions/extension_service.h" #include "chrome/browser/history/history.h" #include "chrome/browser/history/url_database.h" #include "chrome/browser/profiles/profile.h" #include "content/common/notification_service.h" #include "ui/base/l10n/l10n_util.h" ExtensionAppProvider::ExtensionAppProvider(ACProviderListener* listener, Profile* profile) : AutocompleteProvider(listener, profile, "ExtensionApps") { RegisterForNotifications(); RefreshAppList(); } void ExtensionAppProvider::AddExtensionAppForTesting( const std::string& app_name, const std::string url) { extension_apps_.push_back(std::make_pair(app_name, url)); } void ExtensionAppProvider::Start(const AutocompleteInput& input, bool minimal_changes) { matches_.clear(); if (input.type() == AutocompleteInput::INVALID) return; if (!input.text().empty()) { std::string input_utf8 = UTF16ToUTF8(input.text()); for (ExtensionApps::const_iterator app = extension_apps_.begin(); app != extension_apps_.end(); ++app) { // See if the input matches this extension application. const std::string& name = app->first; const std::string& url = app->second; std::string::const_iterator name_iter = std::search(name.begin(), name.end(), input_utf8.begin(), input_utf8.end(), base::CaseInsensitiveCompare<char>()); std::string::const_iterator url_iter = std::search(url.begin(), url.end(), input_utf8.begin(), input_utf8.end(), base::CaseInsensitiveCompare<char>()); bool matches_name = name_iter != name.end(); bool matches_url = url_iter != url.end() && input.type() != AutocompleteInput::FORCED_QUERY; if (matches_name || matches_url) { // We have a match, might be a partial match. // TODO(finnur): Figure out what type to return here, might want to have // the extension icon/a generic icon show up in the Omnibox. AutocompleteMatch match(this, 0, false, AutocompleteMatch::EXTENSION_APP); match.fill_into_edit = UTF8ToUTF16(url); match.destination_url = GURL(url); match.inline_autocomplete_offset = string16::npos; match.contents = UTF8ToUTF16(name); HighlightMatch(input, &match.contents_class, name_iter, name); match.description = UTF8ToUTF16(url); HighlightMatch(input, &match.description_class, url_iter, url); match.relevance = CalculateRelevance(input.type(), input.text().length(), matches_name ? name.length() : url.length(), GURL(url)); matches_.push_back(match); } } } } ExtensionAppProvider::~ExtensionAppProvider() { } void ExtensionAppProvider::RefreshAppList() { ExtensionService* extension_service = profile_->GetExtensionService(); if (!extension_service) return; // During testing, there is no extension service. const ExtensionList* extensions = extension_service->extensions(); extension_apps_.clear(); for (ExtensionList::const_iterator app = extensions->begin(); app != extensions->end(); ++app) { if ((*app)->is_app() && !(*app)->launch_web_url().empty()) { extension_apps_.push_back(std::make_pair((*app)->name(), (*app)->launch_web_url())); } } } void ExtensionAppProvider::RegisterForNotifications() { registrar_.Add(this, NotificationType::EXTENSION_LOADED, NotificationService::AllSources()); registrar_.Add(this, NotificationType::EXTENSION_UNINSTALLED, NotificationService::AllSources()); } void ExtensionAppProvider::Observe(NotificationType type, const NotificationSource& source, const NotificationDetails& details) { RefreshAppList(); } void ExtensionAppProvider::HighlightMatch(const AutocompleteInput& input, ACMatchClassifications* match_class, std::string::const_iterator iter, const std::string& match_string) { size_t pos = iter - match_string.begin(); bool match_found = iter != match_string.end(); if (!match_found || pos > 0) { match_class->push_back( ACMatchClassification(0, ACMatchClassification::DIM)); } if (match_found) { match_class->push_back( ACMatchClassification(pos, ACMatchClassification::MATCH)); if (pos + input.text().length() < match_string.length()) { match_class->push_back(ACMatchClassification(pos + input.text().length(), ACMatchClassification::DIM)); } } } int ExtensionAppProvider::CalculateRelevance(AutocompleteInput::Type type, int input_length, int target_length, const GURL& url) { // If you update the algorithm here, please remember to update the tables in // autocomplete.h also. const int kMaxRelevance = 1425; if (input_length == target_length) return kMaxRelevance; // We give a boost proportionally based on how much of the input matches the // app name, up to a maximum close to 200 (we can be close to, but we'll never // reach 200 because the 100% match is taken care of above). double fraction_boost = static_cast<double>(200) * input_length / target_length; // We also give a boost relative to how often the user has previously typed // the Extension App URL/selected the Extension App suggestion from this // provider (boost is between 200-400). double type_count_boost = 0; HistoryService* const history_service = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS); history::URLDatabase* url_db = history_service ? history_service->InMemoryDatabase() : NULL; if (url_db) { history::URLRow info; url_db->GetRowForURL(url, &info); type_count_boost = 400 * (1.0 - (std::pow(static_cast<double>(2), -info.typed_count()))); } int relevance = 575 + static_cast<int>(type_count_boost) + static_cast<int>(fraction_boost); DCHECK_LE(relevance, kMaxRelevance); return relevance; } <commit_msg>Extension App provider should include packaged apps as well. They have no web launch URL (which is why they don't show up right now), but they have a local extension url we can launch.<commit_after>// Copyright (c) 2011 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 "chrome/browser/autocomplete/extension_app_provider.h" #include <algorithm> #include <cmath> #include "base/string16.h" #include "base/utf_string_conversions.h" #include "chrome/browser/extensions/extension_service.h" #include "chrome/browser/history/history.h" #include "chrome/browser/history/url_database.h" #include "chrome/browser/profiles/profile.h" #include "content/common/notification_service.h" #include "ui/base/l10n/l10n_util.h" ExtensionAppProvider::ExtensionAppProvider(ACProviderListener* listener, Profile* profile) : AutocompleteProvider(listener, profile, "ExtensionApps") { RegisterForNotifications(); RefreshAppList(); } void ExtensionAppProvider::AddExtensionAppForTesting( const std::string& app_name, const std::string url) { extension_apps_.push_back(std::make_pair(app_name, url)); } void ExtensionAppProvider::Start(const AutocompleteInput& input, bool minimal_changes) { matches_.clear(); if (input.type() == AutocompleteInput::INVALID) return; if (!input.text().empty()) { std::string input_utf8 = UTF16ToUTF8(input.text()); for (ExtensionApps::const_iterator app = extension_apps_.begin(); app != extension_apps_.end(); ++app) { // See if the input matches this extension application. const std::string& name = app->first; const std::string& url = app->second; std::string::const_iterator name_iter = std::search(name.begin(), name.end(), input_utf8.begin(), input_utf8.end(), base::CaseInsensitiveCompare<char>()); std::string::const_iterator url_iter = std::search(url.begin(), url.end(), input_utf8.begin(), input_utf8.end(), base::CaseInsensitiveCompare<char>()); bool matches_name = name_iter != name.end(); bool matches_url = url_iter != url.end() && input.type() != AutocompleteInput::FORCED_QUERY; if (matches_name || matches_url) { // We have a match, might be a partial match. // TODO(finnur): Figure out what type to return here, might want to have // the extension icon/a generic icon show up in the Omnibox. AutocompleteMatch match(this, 0, false, AutocompleteMatch::EXTENSION_APP); match.fill_into_edit = UTF8ToUTF16(url); match.destination_url = GURL(url); match.inline_autocomplete_offset = string16::npos; match.contents = UTF8ToUTF16(name); HighlightMatch(input, &match.contents_class, name_iter, name); match.description = UTF8ToUTF16(url); HighlightMatch(input, &match.description_class, url_iter, url); match.relevance = CalculateRelevance(input.type(), input.text().length(), matches_name ? name.length() : url.length(), GURL(url)); matches_.push_back(match); } } } } ExtensionAppProvider::~ExtensionAppProvider() { } void ExtensionAppProvider::RefreshAppList() { ExtensionService* extension_service = profile_->GetExtensionService(); if (!extension_service) return; // During testing, there is no extension service. const ExtensionList* extensions = extension_service->extensions(); extension_apps_.clear(); for (ExtensionList::const_iterator app = extensions->begin(); app != extensions->end(); ++app) { if ((*app)->is_app() && (*app)->GetFullLaunchURL().is_valid()) { extension_apps_.push_back( std::make_pair((*app)->name(), (*app)->GetFullLaunchURL().spec())); } } } void ExtensionAppProvider::RegisterForNotifications() { registrar_.Add(this, NotificationType::EXTENSION_LOADED, NotificationService::AllSources()); registrar_.Add(this, NotificationType::EXTENSION_UNINSTALLED, NotificationService::AllSources()); } void ExtensionAppProvider::Observe(NotificationType type, const NotificationSource& source, const NotificationDetails& details) { RefreshAppList(); } void ExtensionAppProvider::HighlightMatch(const AutocompleteInput& input, ACMatchClassifications* match_class, std::string::const_iterator iter, const std::string& match_string) { size_t pos = iter - match_string.begin(); bool match_found = iter != match_string.end(); if (!match_found || pos > 0) { match_class->push_back( ACMatchClassification(0, ACMatchClassification::DIM)); } if (match_found) { match_class->push_back( ACMatchClassification(pos, ACMatchClassification::MATCH)); if (pos + input.text().length() < match_string.length()) { match_class->push_back(ACMatchClassification(pos + input.text().length(), ACMatchClassification::DIM)); } } } int ExtensionAppProvider::CalculateRelevance(AutocompleteInput::Type type, int input_length, int target_length, const GURL& url) { // If you update the algorithm here, please remember to update the tables in // autocomplete.h also. const int kMaxRelevance = 1425; if (input_length == target_length) return kMaxRelevance; // We give a boost proportionally based on how much of the input matches the // app name, up to a maximum close to 200 (we can be close to, but we'll never // reach 200 because the 100% match is taken care of above). double fraction_boost = static_cast<double>(200) * input_length / target_length; // We also give a boost relative to how often the user has previously typed // the Extension App URL/selected the Extension App suggestion from this // provider (boost is between 200-400). double type_count_boost = 0; HistoryService* const history_service = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS); history::URLDatabase* url_db = history_service ? history_service->InMemoryDatabase() : NULL; if (url_db) { history::URLRow info; url_db->GetRowForURL(url, &info); type_count_boost = 400 * (1.0 - (std::pow(static_cast<double>(2), -info.typed_count()))); } int relevance = 575 + static_cast<int>(type_count_boost) + static_cast<int>(fraction_boost); DCHECK_LE(relevance, kMaxRelevance); return relevance; } <|endoftext|>
<commit_before>/* Start edit with Emacs the project is hosted at https://github.com/igoumeninja/Stem-Cell-Orchestra-Project Aris Bezas */ #include <string> //using namespace std; #include "testApp.h" //-------------------------------------------------------------- void testApp::setup(){ //ofSetVerticalSync(true); ofSetFrameRate(30); camera.setDistance(400); ofSetCircleResolution(3); cout << "listening for osc messages on port " << 12345 << "\n"; receiver.setup( 12345 ); current_msg_string = 0; lenna.loadImage("lenna.png"); bDrawLenna = false; bShowHelp = true; myFbo.allocate(1440,900); myGlitch.setup(&myFbo); _mapping = new ofxMtlMapping2D(); _mapping->init(ofGetWidth(), ofGetHeight(), "mapping/xml/shapes.xml", "mapping/controls/mapping.xml"); string path = "video/video_GREY/"; ofDirectory dir(path); //only show png files dir.allowExt("mp4"); //populate the directory object dir.listDir(); //go through and print out all the paths for(int i = 0; i < dir.numFiles(); i++){ ofLogNotice(dir.getPath(i)); video[i].loadMovie(dir.getPath(i)); video[i].setVolume(0); videoPlay[i] = false; } } //-------------------------------------------------------------- void testApp::update(){ _mapping->update(); ofBackground(0, 0, 0); for ( int i=0; i<NUM_MSG_STRINGS; i++ ) { if ( timers[i] < ofGetElapsedTimef() ) msg_strings[i] = ""; } // check for waiting messages while( receiver.hasWaitingMessages() ) { ofxOscMessage m; receiver.getNextMessage( &m ); if ( m.getAddress() == "/projection" ) { //if (m.getArgAsInt32(5) != 666) video[m.getArgAsInt32(5)].setLoopState(OF_LOOP_NONE); video[m.getArgAsInt32(5)].setLoopState(OF_LOOP_NONE); if(mainVideo != m.getArgAsInt32(5)) { mainVideoChanged = true; video[mainVideo].setLoopState(OF_LOOP_NORMAL); video[mainVideo].setPosition(0); mainVideo = m.getArgAsInt32(5); } for (int i = 0; i < NUM_PROJECTION; i++) { videoProjection[i] = false; videoPrevious[i] = videoPlaying[i]; } for (int i = 0; i < NUM_VIDEOS; i++) { videoPlay[i] = false; } for (int i = 0; i < NUM_PROJECTION; i++) { if(m.getArgAsInt32(i) != 666) { videoID[i] = m.getArgAsInt32(i); videoProjection[i] = true; //if (video[mainVideo].getIsMovieDone()) {videoProjection[5] = false; video[mainVideo].stop();} videoPlay[m.getArgAsInt32(i)] = true; //if(i != 5 & m.getArgAsInt32(i) != 666) { if(i != 5 & (m.getArgAsInt32(i) != mainVideo)) { video[m.getArgAsInt32(i)].setPosition(0); } videoPlaying[i] = m.getArgAsInt32(i); } } for (int i = 0; i < NUM_PROJECTION; i++) { if(m.getArgAsInt32(i) != 666) { if(videoPrevious[i] != videoPlaying[i]) { video[videoPrevious[i]].stop(); } } } // PRINT THE MESSAGE cout << "/projection," << m.getArgAsInt32(0) << "," << m.getArgAsInt32(1) << "," << m.getArgAsInt32(2) << "," << m.getArgAsInt32(3) << "," << m.getArgAsInt32(4) << "," << m.getArgAsInt32(5) << "," << m.getArgAsInt32(6) << "," << m.getArgAsInt32(7) << "," << m.getArgAsInt32(8) << "," << m.getArgAsInt32(9) << "," << m.getArgAsInt32(10) << endl; } if ( m.getAddress() == "state" ) { if(m.getArgAsString(0) == "main") { _mapping->init(ofGetWidth(), ofGetHeight(), "mapping/xml/shapes.xml", "mapping/controls/mapping.xml"); } else { string tempVideoDir = "mapping/xml/state_" + m.getArgAsString(0) + ".xml"; _mapping->init(ofGetWidth(), ofGetHeight(), tempVideoDir, "mapping/controls/mapping.xml"); } } if ( m.getAddress() == "videoPos" ) { video[m.getArgAsInt32(0)].setFrame(m.getArgAsInt32(0)); } if ( m.getAddress() == "/videoSec" ) { video[m.getArgAsInt32(0)].setFrame(m.getArgAsInt32(1)*24);} if ( m.getAddress() == "/videoSpeed" ) { video[m.getArgAsInt32(0)].setSpeed(m.getArgAsInt32(1)); } // Send /filter, filterID, milliseconds if ( m.getAddress() == "/filter" ) { endFilterTime = ofGetElapsedTimeMillis() + m.getArgAsInt32(1); //cout << ofGetElapsedTimeMillis() << endl; switch ( m.getArgAsInt32(0) ) { case 1: myGlitch.setFx(OFXPOSTGLITCH_CONVERGENCE, true);break; case 2: myGlitch.setFx(OFXPOSTGLITCH_SHAKER, true);break; case 3: myGlitch.setFx(OFXPOSTGLITCH_CUTSLIDER, true);break; case 4: myGlitch.setFx(OFXPOSTGLITCH_CR_HIGHCONTRAST,true);break; case 5: myGlitch.setFx(OFXPOSTGLITCH_CR_BLUERAISE, true);break; case 6: myGlitch.setFx(OFXPOSTGLITCH_CR_REDRAISE, true);break; default: break; } } } if(endFilterTime < ofGetElapsedTimeMillis()) { myGlitch.setFx(OFXPOSTGLITCH_CONVERGENCE , false); myGlitch.setFx(OFXPOSTGLITCH_SHAKER , false); myGlitch.setFx(OFXPOSTGLITCH_CUTSLIDER , false); myGlitch.setFx(OFXPOSTGLITCH_CR_HIGHCONTRAST , false); myGlitch.setFx(OFXPOSTGLITCH_CR_BLUERAISE , false); myGlitch.setFx(OFXPOSTGLITCH_CR_REDRAISE , false); } for (int i = 0; i < NUM_VIDEOS; i++) { if (i != mainVideo) { if(videoPlay[i]) { video[i].update(); video[i].play(); } } else { if (!video[mainVideo].getIsMovieDone()) { video[i].update(); video[i].play(); } } } //if (mainVideo != 666) if (video[mainVideo].getIsMovieDone()) videoProjection[5] = false; } //-------------------------------------------------------------- void testApp::draw(){ _mapping->bind(); myFbo.begin(); myGlitch.generateFx(); ofBackground(0,0,0); ofSetHexColor(0xFFFFFF); if(videoProjection[0]) video[videoID[0]].draw( 50, 10, 640, 480); if(videoProjection[1]) video[videoID[1]].draw( 50, 500, 256, 144); if(videoProjection[2]) video[videoID[2]].draw( 50, 650, 256, 144); if(videoProjection[3]) video[videoID[3]].draw( 310, 500, 256, 144); if(videoProjection[4]) video[videoID[4]].draw( 310, 650, 256, 144); if(videoProjection[5]) video[videoID[5]].draw( 580, 500, 256, 144); if(videoProjection[6]) video[videoID[6]].draw( 580, 650, 256, 144); if(videoProjection[7]) video[videoID[7]].draw( 850, 50, 256, 144); if(videoProjection[8]) video[videoID[8]].draw( 850, 200, 256, 144); if(videoProjection[9]) video[videoID[9]].draw( 850, 350, 256, 144); if(videoProjection[10]) video[videoID[10]].draw( 850, 500, 256, 144); myFbo.end(); myFbo.draw(0, 0); _mapping->unbind(); _mapping->draw(); } //-------------------------------------------------------------- void testApp::keyPressed(int key){ if(key == 'f' or key == 'F'){ int previousWindowX, previousWindowY; if(ofGetWindowMode() == 0){ ofSetFullscreen(true); ofBackground(0, 0, 0); }else{ ofSetFullscreen(false); ofBackground(0, 0, 0); } } } void testApp::keyReleased(int key){} void testApp::mouseMoved(int x, int y ){} void testApp::mouseDragged(int x, int y, int button){} void testApp::mousePressed(int x, int y, int button){} void testApp::mouseReleased(int x, int y, int button){} void testApp::windowResized(int w, int h){} void testApp::gotMessage(ofMessage msg){} void testApp::dragEvent(ofDragInfo dragInfo){ } <commit_msg>Stem Project saved on: Mon Mar 23 09:28:08 GMT 2015<commit_after>/* Start edit with Emacs the project is hosted at https://github.com/igoumeninja/Stem-Cell-Orchestra-Project Aris Bezas */ #include <string> //using namespace std; #include "testApp.h" //-------------------------------------------------------------- void testApp::setup(){ //ofSetVerticalSync(true); ofSetFrameRate(30); camera.setDistance(400); ofSetCircleResolution(3); cout << "listening for osc messages on port " << 12345 << "\n"; receiver.setup( 12345 ); current_msg_string = 0; lenna.loadImage("lenna.png"); bDrawLenna = false; bShowHelp = true; myFbo.allocate(1440,900); myGlitch.setup(&myFbo); _mapping = new ofxMtlMapping2D(); _mapping->init(ofGetWidth(), ofGetHeight(), "mapping/xml/shapes.xml", "mapping/controls/mapping.xml"); string path = "video/video_GREY/"; ofDirectory dir(path); //only show png files dir.allowExt("mp4"); //populate the directory object dir.listDir(); //go through and print out all the paths for(int i = 0; i < dir.numFiles(); i++){ ofLogNotice(dir.getPath(i)); video[i].loadMovie(dir.getPath(i)); video[i].setVolume(0); videoPlay[i] = false; } } //-------------------------------------------------------------- void testApp::update(){ _mapping->update(); ofBackground(0, 0, 0); for ( int i=0; i<NUM_MSG_STRINGS; i++ ) { if ( timers[i] < ofGetElapsedTimef() ) msg_strings[i] = ""; } // check for waiting messages while( receiver.hasWaitingMessages() ) { ofxOscMessage m; receiver.getNextMessage( &m ); if ( m.getAddress() == "/projection" ) { //if (m.getArgAsInt32(5) != 666) video[m.getArgAsInt32(5)].setLoopState(OF_LOOP_NONE); video[m.getArgAsInt32(5)].setLoopState(OF_LOOP_NONE); if(mainVideo != m.getArgAsInt32(5)) { mainVideoChanged = true; video[mainVideo].setLoopState(OF_LOOP_NORMAL); video[mainVideo].setPosition(0); mainVideo = m.getArgAsInt32(5); } for (int i = 0; i < NUM_PROJECTION; i++) { videoProjection[i] = false; videoPrevious[i] = videoPlaying[i]; } for (int i = 0; i < NUM_VIDEOS; i++) { videoPlay[i] = false; } for (int i = 0; i < NUM_PROJECTION; i++) { if(m.getArgAsInt32(i) != 666) { videoID[i] = m.getArgAsInt32(i); videoProjection[i] = true; //if (video[mainVideo].getIsMovieDone()) {videoProjection[5] = false; video[mainVideo].stop();} videoPlay[m.getArgAsInt32(i)] = true; //if((i != 5) & (m.getArgAsInt32(i) != mainVideo)) { if(m.getArgAsInt32(i) != mainVideo) { video[m.getArgAsInt32(i)].setPosition(0); } videoPlaying[i] = m.getArgAsInt32(i); } } for (int i = 0; i < NUM_PROJECTION; i++) { if(m.getArgAsInt32(i) != 666) { if(videoPrevious[i] != videoPlaying[i]) { video[videoPrevious[i]].stop(); } } } // PRINT THE MESSAGE cout << "/projection," << m.getArgAsInt32(0) << "," << m.getArgAsInt32(1) << "," << m.getArgAsInt32(2) << "," << m.getArgAsInt32(3) << "," << m.getArgAsInt32(4) << "," << m.getArgAsInt32(5) << "," << m.getArgAsInt32(6) << "," << m.getArgAsInt32(7) << "," << m.getArgAsInt32(8) << "," << m.getArgAsInt32(9) << "," << m.getArgAsInt32(10) << endl; } if ( m.getAddress() == "state" ) { if(m.getArgAsString(0) == "main") { _mapping->init(ofGetWidth(), ofGetHeight(), "mapping/xml/shapes.xml", "mapping/controls/mapping.xml"); } else { string tempVideoDir = "mapping/xml/state_" + m.getArgAsString(0) + ".xml"; _mapping->init(ofGetWidth(), ofGetHeight(), tempVideoDir, "mapping/controls/mapping.xml"); } } if ( m.getAddress() == "videoPos" ) { video[m.getArgAsInt32(0)].setFrame(m.getArgAsInt32(0)); } if ( m.getAddress() == "/videoSec" ) { video[m.getArgAsInt32(0)].setFrame(m.getArgAsInt32(1)*24);} if ( m.getAddress() == "/videoSpeed" ) { video[m.getArgAsInt32(0)].setSpeed(m.getArgAsInt32(1)); } // Send /filter, filterID, milliseconds if ( m.getAddress() == "/filter" ) { endFilterTime = ofGetElapsedTimeMillis() + m.getArgAsInt32(1); //cout << ofGetElapsedTimeMillis() << endl; switch ( m.getArgAsInt32(0) ) { case 1: myGlitch.setFx(OFXPOSTGLITCH_CONVERGENCE, true);break; case 2: myGlitch.setFx(OFXPOSTGLITCH_SHAKER, true);break; case 3: myGlitch.setFx(OFXPOSTGLITCH_CUTSLIDER, true);break; case 4: myGlitch.setFx(OFXPOSTGLITCH_CR_HIGHCONTRAST,true);break; case 5: myGlitch.setFx(OFXPOSTGLITCH_CR_BLUERAISE, true);break; case 6: myGlitch.setFx(OFXPOSTGLITCH_CR_REDRAISE, true);break; default: break; } } } if(endFilterTime < ofGetElapsedTimeMillis()) { myGlitch.setFx(OFXPOSTGLITCH_CONVERGENCE , false); myGlitch.setFx(OFXPOSTGLITCH_SHAKER , false); myGlitch.setFx(OFXPOSTGLITCH_CUTSLIDER , false); myGlitch.setFx(OFXPOSTGLITCH_CR_HIGHCONTRAST , false); myGlitch.setFx(OFXPOSTGLITCH_CR_BLUERAISE , false); myGlitch.setFx(OFXPOSTGLITCH_CR_REDRAISE , false); } for (int i = 0; i < NUM_VIDEOS; i++) { if (i != mainVideo) { if(videoPlay[i]) { video[i].update(); video[i].play(); } } else { if (!video[mainVideo].getIsMovieDone()) { video[i].update(); video[i].play(); } } } //if (mainVideo != 666) if (video[mainVideo].getIsMovieDone()) videoProjection[5] = false; } //-------------------------------------------------------------- void testApp::draw(){ _mapping->bind(); myFbo.begin(); myGlitch.generateFx(); ofBackground(0,0,0); ofSetHexColor(0xFFFFFF); if(videoProjection[0]) video[videoID[0]].draw( 50, 10, 640, 480); if(videoProjection[1]) video[videoID[1]].draw( 50, 500, 256, 144); if(videoProjection[2]) video[videoID[2]].draw( 50, 650, 256, 144); if(videoProjection[3]) video[videoID[3]].draw( 310, 500, 256, 144); if(videoProjection[4]) video[videoID[4]].draw( 310, 650, 256, 144); if(videoProjection[5]) video[videoID[5]].draw( 580, 500, 256, 144); if(videoProjection[6]) video[videoID[6]].draw( 580, 650, 256, 144); if(videoProjection[7]) video[videoID[7]].draw( 850, 50, 256, 144); if(videoProjection[8]) video[videoID[8]].draw( 850, 200, 256, 144); if(videoProjection[9]) video[videoID[9]].draw( 850, 350, 256, 144); if(videoProjection[10]) video[videoID[10]].draw( 850, 500, 256, 144); myFbo.end(); myFbo.draw(0, 0); _mapping->unbind(); _mapping->draw(); } //-------------------------------------------------------------- void testApp::keyPressed(int key){ if(key == 'f' or key == 'F'){ int previousWindowX, previousWindowY; if(ofGetWindowMode() == 0){ ofSetFullscreen(true); ofBackground(0, 0, 0); }else{ ofSetFullscreen(false); ofBackground(0, 0, 0); } } } void testApp::keyReleased(int key){} void testApp::mouseMoved(int x, int y ){} void testApp::mouseDragged(int x, int y, int button){} void testApp::mousePressed(int x, int y, int button){} void testApp::mouseReleased(int x, int y, int button){} void testApp::windowResized(int w, int h){} void testApp::gotMessage(ofMessage msg){} void testApp::dragEvent(ofDragInfo dragInfo){ } <|endoftext|>
<commit_before>// Copyright (c) 2011 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 "chrome/browser/dom_ui/print_preview_ui_html_source.h" #include <algorithm> #include <vector> #include "base/message_loop.h" #include "base/shared_memory.h" #include "base/string_piece.h" #include "base/values.h" #include "chrome/common/jstemplate_builder.h" #include "chrome/common/url_constants.h" #include "grit/browser_resources.h" #include "grit/generated_resources.h" #include "ui/base/l10n/l10n_util.h" #include "ui/base/resource/resource_bundle.h" namespace { void SetLocalizedStrings(DictionaryValue* localized_strings) { localized_strings->SetString(std::string("title"), l10n_util::GetStringUTF8(IDS_PRINT_PREVIEW_TITLE)); localized_strings->SetString(std::string("loading"), l10n_util::GetStringUTF8(IDS_PRINT_PREVIEW_LOADING)); localized_strings->SetString(std::string("noPlugin"), l10n_util::GetStringUTF8(IDS_PRINT_PREVIEW_NO_PLUGIN)); localized_strings->SetString(std::string("noPrinter"), l10n_util::GetStringUTF8(IDS_PRINT_PREVIEW_NO_PRINTER)); localized_strings->SetString(std::string("printButton"), l10n_util::GetStringUTF8(IDS_PRINT_PREVIEW_PRINT_BUTTON)); localized_strings->SetString(std::string("cancelButton"), l10n_util::GetStringUTF8(IDS_PRINT_PREVIEW_CANCEL_BUTTON)); localized_strings->SetString(std::string("optionAllPages"), l10n_util::GetStringUTF8(IDS_PRINT_PREVIEW_OPTION_ALL_PAGES)); localized_strings->SetString(std::string("optionBw"), l10n_util::GetStringUTF8(IDS_PRINT_PREVIEW_OPTION_BW)); localized_strings->SetString(std::string("optionCollate"), l10n_util::GetStringUTF8(IDS_PRINT_PREVIEW_OPTION_COLLATE)); localized_strings->SetString(std::string("optionColor"), l10n_util::GetStringUTF8(IDS_PRINT_PREVIEW_OPTION_COLOR)); localized_strings->SetString(std::string("optionLandscape"), l10n_util::GetStringUTF8(IDS_PRINT_PREVIEW_OPTION_LANDSCAPE)); localized_strings->SetString(std::string("optionPortrait"), l10n_util::GetStringUTF8(IDS_PRINT_PREVIEW_OPTION_PORTRAIT)); localized_strings->SetString(std::string("optionTwoSided"), l10n_util::GetStringUTF8(IDS_PRINT_PREVIEW_OPTION_TWO_SIDED)); } } // namespace PrintPreviewUIHTMLSource::PrintPreviewUIHTMLSource() : DataSource(chrome::kChromeUIPrintHost, MessageLoop::current()), data_(std::make_pair(static_cast<base::SharedMemory*>(NULL), 0U)) { } PrintPreviewUIHTMLSource::~PrintPreviewUIHTMLSource() { delete data_.first; } void PrintPreviewUIHTMLSource::GetPrintPreviewData(PrintPreviewData* data) { *data = data_; } void PrintPreviewUIHTMLSource::SetPrintPreviewData( const PrintPreviewData& data) { delete data_.first; data_ = data; } void PrintPreviewUIHTMLSource::StartDataRequest(const std::string& path, bool is_off_the_record, int request_id) { if (path.empty()) { // Print Preview Index page. DictionaryValue localized_strings; SetLocalizedStrings(&localized_strings); SetFontAndTextDirection(&localized_strings); static const base::StringPiece print_html( ResourceBundle::GetSharedInstance().GetRawDataResource( IDR_PRINT_PREVIEW_HTML)); const std::string full_html = jstemplate_builder::GetI18nTemplateHtml( print_html, &localized_strings); scoped_refptr<RefCountedBytes> html_bytes(new RefCountedBytes); html_bytes->data.resize(full_html.size()); std::copy(full_html.begin(), full_html.end(), html_bytes->data.begin()); SendResponse(request_id, html_bytes); return; } else if (path == "print.pdf") { // Print Preview data. char* preview_data = reinterpret_cast<char*>(data_.first->memory()); uint32 preview_data_size = data_.second; scoped_refptr<RefCountedBytes> html_bytes(new RefCountedBytes); html_bytes->data.resize(preview_data_size); std::vector<unsigned char>::iterator it = html_bytes->data.begin(); for (uint32 i = 0; i < preview_data_size; ++i, ++it) *it = *(preview_data + i); SendResponse(request_id, html_bytes); return; } else { // Invalid request. scoped_refptr<RefCountedBytes> empty_bytes(new RefCountedBytes); SendResponse(request_id, empty_bytes); return; } } std::string PrintPreviewUIHTMLSource::GetMimeType( const std::string& path) const { // Print Preview Index page. if (path.empty()) return "text/html"; // Print Preview data. return "application/pdf"; } <commit_msg>Print Preview: Don't crash when there's no preview data.<commit_after>// Copyright (c) 2011 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 "chrome/browser/dom_ui/print_preview_ui_html_source.h" #include <algorithm> #include <vector> #include "base/message_loop.h" #include "base/shared_memory.h" #include "base/string_piece.h" #include "base/values.h" #include "chrome/common/jstemplate_builder.h" #include "chrome/common/url_constants.h" #include "grit/browser_resources.h" #include "grit/generated_resources.h" #include "ui/base/l10n/l10n_util.h" #include "ui/base/resource/resource_bundle.h" namespace { void SetLocalizedStrings(DictionaryValue* localized_strings) { localized_strings->SetString(std::string("title"), l10n_util::GetStringUTF8(IDS_PRINT_PREVIEW_TITLE)); localized_strings->SetString(std::string("loading"), l10n_util::GetStringUTF8(IDS_PRINT_PREVIEW_LOADING)); localized_strings->SetString(std::string("noPlugin"), l10n_util::GetStringUTF8(IDS_PRINT_PREVIEW_NO_PLUGIN)); localized_strings->SetString(std::string("noPrinter"), l10n_util::GetStringUTF8(IDS_PRINT_PREVIEW_NO_PRINTER)); localized_strings->SetString(std::string("printButton"), l10n_util::GetStringUTF8(IDS_PRINT_PREVIEW_PRINT_BUTTON)); localized_strings->SetString(std::string("cancelButton"), l10n_util::GetStringUTF8(IDS_PRINT_PREVIEW_CANCEL_BUTTON)); localized_strings->SetString(std::string("optionAllPages"), l10n_util::GetStringUTF8(IDS_PRINT_PREVIEW_OPTION_ALL_PAGES)); localized_strings->SetString(std::string("optionBw"), l10n_util::GetStringUTF8(IDS_PRINT_PREVIEW_OPTION_BW)); localized_strings->SetString(std::string("optionCollate"), l10n_util::GetStringUTF8(IDS_PRINT_PREVIEW_OPTION_COLLATE)); localized_strings->SetString(std::string("optionColor"), l10n_util::GetStringUTF8(IDS_PRINT_PREVIEW_OPTION_COLOR)); localized_strings->SetString(std::string("optionLandscape"), l10n_util::GetStringUTF8(IDS_PRINT_PREVIEW_OPTION_LANDSCAPE)); localized_strings->SetString(std::string("optionPortrait"), l10n_util::GetStringUTF8(IDS_PRINT_PREVIEW_OPTION_PORTRAIT)); localized_strings->SetString(std::string("optionTwoSided"), l10n_util::GetStringUTF8(IDS_PRINT_PREVIEW_OPTION_TWO_SIDED)); } } // namespace PrintPreviewUIHTMLSource::PrintPreviewUIHTMLSource() : DataSource(chrome::kChromeUIPrintHost, MessageLoop::current()), data_(std::make_pair(static_cast<base::SharedMemory*>(NULL), 0U)) { } PrintPreviewUIHTMLSource::~PrintPreviewUIHTMLSource() { delete data_.first; } void PrintPreviewUIHTMLSource::GetPrintPreviewData(PrintPreviewData* data) { *data = data_; } void PrintPreviewUIHTMLSource::SetPrintPreviewData( const PrintPreviewData& data) { delete data_.first; data_ = data; } void PrintPreviewUIHTMLSource::StartDataRequest(const std::string& path, bool is_off_the_record, int request_id) { if (path.empty()) { // Print Preview Index page. DictionaryValue localized_strings; SetLocalizedStrings(&localized_strings); SetFontAndTextDirection(&localized_strings); static const base::StringPiece print_html( ResourceBundle::GetSharedInstance().GetRawDataResource( IDR_PRINT_PREVIEW_HTML)); const std::string full_html = jstemplate_builder::GetI18nTemplateHtml( print_html, &localized_strings); scoped_refptr<RefCountedBytes> html_bytes(new RefCountedBytes); html_bytes->data.resize(full_html.size()); std::copy(full_html.begin(), full_html.end(), html_bytes->data.begin()); SendResponse(request_id, html_bytes); return; } else if (path == "print.pdf" && data_.first) { // Print Preview data. char* preview_data = reinterpret_cast<char*>(data_.first->memory()); uint32 preview_data_size = data_.second; scoped_refptr<RefCountedBytes> html_bytes(new RefCountedBytes); html_bytes->data.resize(preview_data_size); std::vector<unsigned char>::iterator it = html_bytes->data.begin(); for (uint32 i = 0; i < preview_data_size; ++i, ++it) *it = *(preview_data + i); SendResponse(request_id, html_bytes); return; } else { // Invalid request. scoped_refptr<RefCountedBytes> empty_bytes(new RefCountedBytes); SendResponse(request_id, empty_bytes); return; } } std::string PrintPreviewUIHTMLSource::GetMimeType( const std::string& path) const { // Print Preview Index page. if (path.empty()) return "text/html"; // Print Preview data. return "application/pdf"; } <|endoftext|>
<commit_before>#include <stdio.h> #include <stdlib.h> #include <string.h> #include <texture.h> #include <cmath> #include <glm.hpp> using namespace std; Texture::Texture(int type, int w, int h) { textureType = type; width = w; height = h; data = new float[width*height*4]; for (int i = 0;i<width*height*4;i++) data[i] = i%4<4?0:1; glGenTextures(1,&textureNumber); glBindTexture(GL_TEXTURE_2D,textureNumber); glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR ); glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR ); glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT ); glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT ); } void Texture::toTGA(const char* file) { FILE* fp = fopen(file,"wb"); putc(0,fp); putc(0,fp); putc(2,fp); /* uncompressed RGB */ putc(0,fp); putc(0,fp); putc(0,fp); putc(0,fp); putc(0,fp); putc(0,fp); putc(0,fp); /* X origin */ putc(0,fp); putc(0,fp); /* y origin */ putc((width & 0x00FF),fp); putc((width & 0xFF00) / 256,fp); putc((height & 0x00FF),fp); putc((height & 0xFF00) / 256,fp); putc(32,fp); /* 24 bit bitmap */ putc(0,fp); for (int i = 0;i<width;i++) for (int j = 0;j<height;j++) { float f = abs(data[(i*height+j)*4+0]); if (f<0)f=-f; unsigned char c = (abs(data[(i*height+j)*4+0])*255); putc((unsigned char)(abs(data[(i*height+j)*4+0]*255)),fp); putc((unsigned char)(abs(data[(i*height+j)*4+1]*255)),fp); putc((unsigned char)(abs(data[(i*height+j)*4+2]*255)),fp); putc((unsigned char)(abs(data[(i*height+j)*4+3]*255)),fp); } fclose(fp); } void Texture::loadData(float* inData) { memcpy(data,inData,width*height*4*sizeof(float)); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA16F, width, height, 0, GL_RGBA, GL_FLOAT, data); } void Texture::loadBumpData(float* inData) { for (int i=0;i<width*height;i++) { glm::vec3 no = glm::vec3(1.f); if ((i%width)>0 && (i/width>0) && (i%width<width-1) && (i/width<height-1)) { float a,b,c,d,m; a = inData[i-width]*1000; b = inData[i+1]*1000; c = inData[i+width]*1000; d = inData[i-1]*1000; m = inData[i]*1000; no = -glm::cross(glm::vec3(0.f,a-m,-1.f),glm::vec3(1.f,b-m,0.f)); } no = glm::normalize(no); data[i*4 ] = no.x; data[i*4+1] = no.y; data[i*4+2] = no.z; data[i*4+3] = inData[i]; } glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA16F, width, height, 0, GL_RGBA, GL_FLOAT, data); } void Texture::load() { glActiveTexture(textureType); glBindTexture(GL_TEXTURE_2D,textureNumber); } #ifdef TEST_TEXTURE int main() { Texture texture(HEIGHTMAP_TEXTURE,8,8); texture.toTGA("test.tga"); } #endif <commit_msg>Complete normal calculation<commit_after>#include <stdio.h> #include <stdlib.h> #include <string.h> #include <texture.h> #include <cmath> #include <glm.hpp> using namespace std; Texture::Texture(int type, int w, int h) { textureType = type; width = w; height = h; data = new float[width*height*4]; for (int i = 0;i<width*height*4;i++) data[i] = i%4<4?0:1; glGenTextures(1,&textureNumber); glBindTexture(GL_TEXTURE_2D,textureNumber); glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR ); glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR ); glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT ); glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT ); } void Texture::toTGA(const char* file) { FILE* fp = fopen(file,"wb"); putc(0,fp); putc(0,fp); putc(2,fp); /* uncompressed RGB */ putc(0,fp); putc(0,fp); putc(0,fp); putc(0,fp); putc(0,fp); putc(0,fp); putc(0,fp); /* X origin */ putc(0,fp); putc(0,fp); /* y origin */ putc((width & 0x00FF),fp); putc((width & 0xFF00) / 256,fp); putc((height & 0x00FF),fp); putc((height & 0xFF00) / 256,fp); putc(32,fp); /* 24 bit bitmap */ putc(0,fp); for (int i = 0;i<width;i++) for (int j = 0;j<height;j++) { float f = abs(data[(i*height+j)*4+0]); if (f<0)f=-f; unsigned char c = (abs(data[(i*height+j)*4+0])*255); putc((unsigned char)(abs(data[(i*height+j)*4+0]*255)),fp); putc((unsigned char)(abs(data[(i*height+j)*4+1]*255)),fp); putc((unsigned char)(abs(data[(i*height+j)*4+2]*255)),fp); putc((unsigned char)(abs(data[(i*height+j)*4+3]*255)),fp); } fclose(fp); } void Texture::loadData(float* inData) { memcpy(data,inData,width*height*4*sizeof(float)); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA16F, width, height, 0, GL_RGBA, GL_FLOAT, data); } void Texture::loadBumpData(float* inData) { for (int i=0;i<width*height;i++) { glm::vec3 no = glm::vec3(1.f); if ((i%width)>0 && (i/width>0) && (i%width<width-1) && (i/width<height-1)) { float a,b,c,d,m; a = inData[i-width]*1000; b = inData[i+1]*1000; c = inData[i+width]*1000; d = inData[i-1]*1000; m = inData[i]*1000; no = -glm::cross(glm::vec3(0.f,a-m,-1.f),glm::vec3(1.f,b-m,0.f)) -glm::cross(glm::vec3(1.f,b-m,0.f),glm::vec3(0.f,c-m,1.f)) -glm::cross(glm::vec3(0.f,c-m,1.f),glm::vec3(-1.f,d-m,0.f)) -glm::cross(glm::vec3(-1.f,d-m,0.f),glm::vec3(0.f,a-m,-1.f)); } no = glm::normalize(no); data[i*4 ] = no.x; data[i*4+1] = no.y; data[i*4+2] = no.z; data[i*4+3] = inData[i]; } glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA16F, width, height, 0, GL_RGBA, GL_FLOAT, data); } void Texture::load() { glActiveTexture(textureType); glBindTexture(GL_TEXTURE_2D,textureNumber); } #ifdef TEST_TEXTURE int main() { Texture texture(HEIGHTMAP_TEXTURE,8,8); texture.toTGA("test.tga"); } #endif <|endoftext|>
<commit_before>// ************************************************************************* // // Licensed under the MIT License (see accompanying LICENSE file). // // The author of this code is: Daniel Farrell // // Based on mmtf_python, adapted to c++ standards 2018 // // ************************************************************************* #ifndef MMTF_BINARY_ENCODER_H #define MMTF_BINARY_ENCODER_H #include <math.h> // byteorder functions #ifdef WIN32 #include <Winsock2.h> #else #include <arpa/inet.h> #endif namespace mmtf { /** * @brief Convert floats to ints via multiplier. * @param[in] vec_in vector of floats * @param[in] multiplier multiply float vector by this * @return vec_out vec_in * multiplier and rounded */ inline std::vector<int32_t> convertFloatsToInts(std::vector<float> const & vec_in, int multiplier); /** * @brief mmtf delta encode a vector of ints. * @param[in] vec_in vector of ints * @return vec_out delta encoded int vector */ inline std::vector<int32_t> deltaEncode(std::vector<int32_t> const & vec_in); /** * @brief mmtf run length encode a vector of ints. * @param[in] vec_in vector of ints * @return vec_out run length encoded int vector */ inline std::vector<int32_t> runLengthEncode(std::vector<int32_t> const & vec_in ); /** * @brief mmtf recursive index encode a vector of ints. * @param[in] vec_in vector of ints * @param[in] max maximum value of signed 16bit int * @param[in] min minimum value of signed 16bit int * @return vec_out recursive index encoded vector */ inline std::vector<int32_t> recursiveIndexEncode(std::vector<int32_t> const & vec_in, int max=32767, int min=-32768); /** * @brief mmtf convert char to int * @param[in] vec_in vector of chars * @return vec_out vector of ints */ inline std::vector<int32_t> convertCharsToInts(std::vector<char> const & vec_in); /** * @brief Add mmtf header to a stream * @param[in] ss stringstream to add a header to * @param[in] array_size size of array you're adding * @param[in] codec the codec type number you're using to encode * @param[in] param the param for the codec you're using (default 0) */ inline void add_header(std::stringstream & ss, uint32_t array_size, uint32_t codec, uint32_t param=0); /** * @brief Convert stringstream to CharVector * @param[in] ss ss to convert * @return converted ss */ inline std::vector<char> stringstreamToCharVector(std::stringstream & ss); /** encode 8 bit int to bytes encoding (type 2) * @param[in] vec_in vector of ints to encode * @return cv char vector of encoded bytes */ inline std::vector<char> encodeInt8ToByte(std::vector<int8_t> vec_in); /** encode 4 bytes to int encoding (type 4) * @param[in] vec_in vector of ints to encode * @return cv char vector of encoded bytes */ inline std::vector<char> encodeFourByteInt(std::vector<int32_t> vec_in); /** encode string vector encoding (type 5) * @param[in] in_sv vector of strings * @param[in] CHAIN_LEN maximum length of string * @return cv char vector of encoded bytes */ inline std::vector<char> encodeStringVector(std::vector<std::string> in_sv, int32_t CHAIN_LEN); /** encode Run Length Char encoding (type 6) * @param[in] in_cv vector for chars * @return cv char vector of encoded bytes */ inline std::vector<char> encodeRunLengthChar(std::vector<char> in_cv); /** encode Run Length Delta Int encoding (type 8) * @param[in] int_vec vector of ints * @return cv char vector of encoded bytes */ inline std::vector<char> encodeRunLengthDeltaInt(std::vector<int32_t> int_vec); /** encode Run Length Float encoding (type 9) * @param[in] floats_in vector of ints * @param[in] multiplier float multiplier * @return cv char vector of encoded bytes */ inline std::vector<char> encodeRunLengthFloat(std::vector<float> floats_in, int32_t multiplier); /** encode Delta Recursive Float encoding (type 10) * @param[in] floats_in vector of ints * @param[in] multiplier float multiplier * @return cv char vector of encoded bytes */ inline std::vector<char> encodeDeltaRecursiveFloat(std::vector<float> floats_in, int32_t multiplier); // ************************************************************************* // IMPLEMENTATION // ************************************************************************* inline std::vector<int32_t> convertFloatsToInts(std::vector<float> const & vec_in, int multiplier) { std::vector<int32_t> vec_out; for (size_t i=0; i<vec_in.size(); ++i) { vec_out.push_back(round(vec_in[i]*multiplier)); } return vec_out; } inline std::vector<int32_t> deltaEncode(std::vector<int32_t> const & vec_in) { std::vector<int32_t> vec_out; if (vec_in.size() == 0) return vec_out; vec_out.push_back(vec_in[0]); for (int32_t i=1; i< (int)vec_in.size(); ++i) { vec_out.push_back(vec_in[i]-vec_in[i-1]); } return vec_out; } inline std::vector<int32_t> runLengthEncode(std::vector<int32_t> const & vec_in ) { std::vector<int32_t> ret; if (vec_in.size()==0) return ret; int32_t curr = vec_in[0]; ret.push_back(curr); int32_t counter = 1; for (int32_t i = 1; i < (int)vec_in.size(); ++i) { if ( vec_in[i] == curr ) { ++counter; } else { ret.push_back(counter); ret.push_back(vec_in[i]); curr = vec_in[i]; counter = 1; } } ret.push_back(counter); return ret; } inline std::vector<int32_t> recursiveIndexEncode( std::vector<int32_t> const & vec_in, int max /* =32767 */, int min /*=-32768 */) { std::vector<int32_t> vec_out; for (int32_t i=0; i< (int)vec_in.size(); ++i) { int32_t x = vec_in[i]; if ( x >= 0 ) { while (x >= max) { vec_out.push_back(max); x -= max; } } else { while (x <= min) { vec_out.push_back(min); x += std::abs(min); } } vec_out.push_back(x); } return vec_out; } inline std::vector<int32_t> convertCharsToInts(std::vector<char> const & vec_in) { std::vector<int32_t> vec_out; for (size_t i=0; i<vec_in.size(); ++i) { vec_out.push_back((int)vec_in[i]); } return vec_out; } inline void add_header(std::stringstream & ss, uint32_t array_size, uint32_t codec, uint32_t param /* =0 */) { uint32_t be_codec = htobe32(codec); uint32_t be_array_size = htobe32(array_size); uint32_t be_param = htobe32(param); ss.write(reinterpret_cast< char * >(&be_codec), sizeof(be_codec)); ss.write(reinterpret_cast< char * >(&be_array_size), sizeof(be_array_size)); ss.write(reinterpret_cast< char * >(&be_param), sizeof(be_param)); } inline std::vector<char> stringstreamToCharVector(std::stringstream & ss) { std::string s = ss.str(); std::vector<char> ret(s.begin(), s.end()); return ret; } inline std::vector<char> encodeInt8ToByte(std::vector<int8_t> vec_in) { std::stringstream ss; add_header(ss, vec_in.size(), 2, 0); for (size_t i=0; i<vec_in.size(); ++i) { ss.write(reinterpret_cast< char * >(&vec_in[i]), sizeof(vec_in[i])); } return stringstreamToCharVector(ss); } inline std::vector<char> encodeFourByteInt(std::vector<int32_t> vec_in) { std::stringstream ss; add_header(ss, vec_in.size(), 4, 0); for (size_t i=0; i<vec_in.size(); ++i) { int32_t be_x = htobe32(vec_in[i]); ss.write(reinterpret_cast< char * >(&be_x), sizeof(be_x)); } return stringstreamToCharVector(ss); } inline std::vector<char> encodeStringVector(std::vector<std::string> in_sv, int32_t CHAIN_LEN) { char NULL_BYTE = 0x00; std::stringstream ss; add_header(ss, in_sv.size(), 5, CHAIN_LEN); std::vector<char> char_vec; for (size_t i=0; i<in_sv.size(); ++i) { char_vec.insert(char_vec.end(), in_sv[i].begin(), in_sv[i].end()); for (size_t j=0; j<CHAIN_LEN-in_sv[i].size(); ++j) { char_vec.push_back(NULL_BYTE); } } for (size_t i=0; i<char_vec.size(); ++i) { ss.write(reinterpret_cast< char * >(&char_vec[i]), sizeof(char_vec[i])); } return stringstreamToCharVector(ss); } inline std::vector<char> encodeRunLengthChar(std::vector<char> in_cv) { std::stringstream ss; add_header(ss, in_cv.size(), 6, 0); std::vector<int32_t> int_vec; int_vec = convertCharsToInts(in_cv); int_vec = runLengthEncode(int_vec); for (size_t i=0; i<int_vec.size(); ++i) { int32_t temp = htobe32(int_vec[i]); ss.write(reinterpret_cast< char * >(&temp), sizeof(temp)); } return stringstreamToCharVector(ss); } inline std::vector<char> encodeRunLengthDeltaInt(std::vector<int32_t> int_vec) { std::stringstream ss; add_header(ss, int_vec.size(), 8, 0); int_vec = deltaEncode(int_vec); int_vec = runLengthEncode(int_vec); for (size_t i=0; i<int_vec.size(); ++i) { int32_t temp = htobe32(int_vec[i]); ss.write(reinterpret_cast< char * >(&temp), sizeof(temp)); } return stringstreamToCharVector(ss); } inline std::vector<char> encodeRunLengthFloat(std::vector<float> floats_in, int32_t multiplier) { std::stringstream ss; add_header(ss, floats_in.size(), 9, multiplier); std::vector<int32_t> int_vec = convertFloatsToInts(floats_in, multiplier); int_vec = runLengthEncode(int_vec); for (size_t i=0; i<int_vec.size(); ++i) { int32_t temp = htobe32(int_vec[i]); ss.write(reinterpret_cast< char * >(&temp), sizeof(temp)); } return stringstreamToCharVector(ss); } inline std::vector<char> encodeDeltaRecursiveFloat(std::vector<float> floats_in, int32_t multiplier) { std::stringstream ss; add_header(ss, floats_in.size(), 10, multiplier); std::vector<int32_t> int_vec = convertFloatsToInts(floats_in, multiplier); int_vec = deltaEncode(int_vec); int_vec = recursiveIndexEncode(int_vec); for (size_t i=0; i<int_vec.size(); ++i) { int16_t temp = htobe16(int_vec[i]); ss.write(reinterpret_cast< char * >(&temp), sizeof(temp)); } return stringstreamToCharVector(ss); } } // mmtf namespace #endif <commit_msg>Code cleanup - hide private global functions<commit_after>// ************************************************************************* // // Licensed under the MIT License (see accompanying LICENSE file). // // The author of this code is: Daniel Farrell // // Based on mmtf_python, adapted to c++ standards 2018 // // ************************************************************************* #ifndef MMTF_BINARY_ENCODER_H #define MMTF_BINARY_ENCODER_H #include <math.h> // byteorder functions #ifdef WIN32 #include <Winsock2.h> #else #include <arpa/inet.h> #endif namespace mmtf { // ************************************************************************* // PRIVATE FUNCTIONS (only visible in this header) // ************************************************************************* namespace { // private helpers /** * @brief Convert floats to ints via multiplier. * @param[in] vec_in vector of floats * @param[in] multiplier multiply float vector by this * @return vec_out vec_in * multiplier and rounded */ inline std::vector<int32_t> convertFloatsToInts(std::vector<float> const & vec_in, int multiplier); /** * @brief mmtf delta encode a vector of ints. * @param[in] vec_in vector of ints * @return vec_out delta encoded int vector */ inline std::vector<int32_t> deltaEncode(std::vector<int32_t> const & vec_in); /** * @brief mmtf run length encode a vector of ints. * @param[in] vec_in vector of ints * @return vec_out run length encoded int vector */ inline std::vector<int32_t> runLengthEncode(std::vector<int32_t> const & vec_in ); /** * @brief mmtf recursive index encode a vector of ints. * @param[in] vec_in vector of ints * @param[in] max maximum value of signed 16bit int * @param[in] min minimum value of signed 16bit int * @return vec_out recursive index encoded vector */ inline std::vector<int32_t> recursiveIndexEncode(std::vector<int32_t> const & vec_in, int max=32767, int min=-32768); /** * @brief mmtf convert char to int * @param[in] vec_in vector of chars * @return vec_out vector of ints */ inline std::vector<int32_t> convertCharsToInts(std::vector<char> const & vec_in); /** * @brief Add mmtf header to a stream * @param[in] ss stringstream to add a header to * @param[in] array_size size of array you're adding * @param[in] codec the codec type number you're using to encode * @param[in] param the param for the codec you're using (default 0) */ inline void add_header(std::stringstream & ss, uint32_t array_size, uint32_t codec, uint32_t param=0); /** * @brief Convert stringstream to CharVector * @param[in] ss ss to convert * @return converted ss */ inline std::vector<char> stringstreamToCharVector(std::stringstream & ss); } // anon ns // ************************************************************************* // PUBLIC FUNCTIONS // ************************************************************************* /** encode 8 bit int to bytes encoding (type 2) * @param[in] vec_in vector of ints to encode * @return cv char vector of encoded bytes */ inline std::vector<char> encodeInt8ToByte(std::vector<int8_t> vec_in); /** encode 4 bytes to int encoding (type 4) * @param[in] vec_in vector of ints to encode * @return cv char vector of encoded bytes */ inline std::vector<char> encodeFourByteInt(std::vector<int32_t> vec_in); /** encode string vector encoding (type 5) * @param[in] in_sv vector of strings * @param[in] CHAIN_LEN maximum length of string * @return cv char vector of encoded bytes */ inline std::vector<char> encodeStringVector(std::vector<std::string> in_sv, int32_t CHAIN_LEN); /** encode Run Length Char encoding (type 6) * @param[in] in_cv vector for chars * @return cv char vector of encoded bytes */ inline std::vector<char> encodeRunLengthChar(std::vector<char> in_cv); /** encode Run Length Delta Int encoding (type 8) * @param[in] int_vec vector of ints * @return cv char vector of encoded bytes */ inline std::vector<char> encodeRunLengthDeltaInt(std::vector<int32_t> int_vec); /** encode Run Length Float encoding (type 9) * @param[in] floats_in vector of ints * @param[in] multiplier float multiplier * @return cv char vector of encoded bytes */ inline std::vector<char> encodeRunLengthFloat(std::vector<float> floats_in, int32_t multiplier); /** encode Delta Recursive Float encoding (type 10) * @param[in] floats_in vector of ints * @param[in] multiplier float multiplier * @return cv char vector of encoded bytes */ inline std::vector<char> encodeDeltaRecursiveFloat(std::vector<float> floats_in, int32_t multiplier); // ************************************************************************* // IMPLEMENTATION // ************************************************************************* namespace { // private helpers inline std::vector<int32_t> convertFloatsToInts(std::vector<float> const & vec_in, int multiplier) { std::vector<int32_t> vec_out; for (size_t i=0; i<vec_in.size(); ++i) { vec_out.push_back(round(vec_in[i]*multiplier)); } return vec_out; } inline std::vector<int32_t> deltaEncode(std::vector<int32_t> const & vec_in) { std::vector<int32_t> vec_out; if (vec_in.size() == 0) return vec_out; vec_out.push_back(vec_in[0]); for (int32_t i=1; i< (int)vec_in.size(); ++i) { vec_out.push_back(vec_in[i]-vec_in[i-1]); } return vec_out; } inline std::vector<int32_t> runLengthEncode(std::vector<int32_t> const & vec_in ) { std::vector<int32_t> ret; if (vec_in.size()==0) return ret; int32_t curr = vec_in[0]; ret.push_back(curr); int32_t counter = 1; for (int32_t i = 1; i < (int)vec_in.size(); ++i) { if ( vec_in[i] == curr ) { ++counter; } else { ret.push_back(counter); ret.push_back(vec_in[i]); curr = vec_in[i]; counter = 1; } } ret.push_back(counter); return ret; } inline std::vector<int32_t> recursiveIndexEncode( std::vector<int32_t> const & vec_in, int max /* =32767 */, int min /*=-32768 */) { std::vector<int32_t> vec_out; for (int32_t i=0; i< (int)vec_in.size(); ++i) { int32_t x = vec_in[i]; if ( x >= 0 ) { while (x >= max) { vec_out.push_back(max); x -= max; } } else { while (x <= min) { vec_out.push_back(min); x += std::abs(min); } } vec_out.push_back(x); } return vec_out; } inline std::vector<int32_t> convertCharsToInts(std::vector<char> const & vec_in) { std::vector<int32_t> vec_out; for (size_t i=0; i<vec_in.size(); ++i) { vec_out.push_back((int)vec_in[i]); } return vec_out; } inline void add_header(std::stringstream & ss, uint32_t array_size, uint32_t codec, uint32_t param /* =0 */) { uint32_t be_codec = htobe32(codec); uint32_t be_array_size = htobe32(array_size); uint32_t be_param = htobe32(param); ss.write(reinterpret_cast< char * >(&be_codec), sizeof(be_codec)); ss.write(reinterpret_cast< char * >(&be_array_size), sizeof(be_array_size)); ss.write(reinterpret_cast< char * >(&be_param), sizeof(be_param)); } inline std::vector<char> stringstreamToCharVector(std::stringstream & ss) { std::string s = ss.str(); std::vector<char> ret(s.begin(), s.end()); return ret; } } // anon ns inline std::vector<char> encodeInt8ToByte(std::vector<int8_t> vec_in) { std::stringstream ss; add_header(ss, vec_in.size(), 2, 0); for (size_t i=0; i<vec_in.size(); ++i) { ss.write(reinterpret_cast< char * >(&vec_in[i]), sizeof(vec_in[i])); } return stringstreamToCharVector(ss); } inline std::vector<char> encodeFourByteInt(std::vector<int32_t> vec_in) { std::stringstream ss; add_header(ss, vec_in.size(), 4, 0); for (size_t i=0; i<vec_in.size(); ++i) { int32_t be_x = htobe32(vec_in[i]); ss.write(reinterpret_cast< char * >(&be_x), sizeof(be_x)); } return stringstreamToCharVector(ss); } inline std::vector<char> encodeStringVector(std::vector<std::string> in_sv, int32_t CHAIN_LEN) { char NULL_BYTE = 0x00; std::stringstream ss; add_header(ss, in_sv.size(), 5, CHAIN_LEN); std::vector<char> char_vec; for (size_t i=0; i<in_sv.size(); ++i) { char_vec.insert(char_vec.end(), in_sv[i].begin(), in_sv[i].end()); for (size_t j=0; j<CHAIN_LEN-in_sv[i].size(); ++j) { char_vec.push_back(NULL_BYTE); } } for (size_t i=0; i<char_vec.size(); ++i) { ss.write(reinterpret_cast< char * >(&char_vec[i]), sizeof(char_vec[i])); } return stringstreamToCharVector(ss); } inline std::vector<char> encodeRunLengthChar(std::vector<char> in_cv) { std::stringstream ss; add_header(ss, in_cv.size(), 6, 0); std::vector<int32_t> int_vec; int_vec = convertCharsToInts(in_cv); int_vec = runLengthEncode(int_vec); for (size_t i=0; i<int_vec.size(); ++i) { int32_t temp = htobe32(int_vec[i]); ss.write(reinterpret_cast< char * >(&temp), sizeof(temp)); } return stringstreamToCharVector(ss); } inline std::vector<char> encodeRunLengthDeltaInt(std::vector<int32_t> int_vec) { std::stringstream ss; add_header(ss, int_vec.size(), 8, 0); int_vec = deltaEncode(int_vec); int_vec = runLengthEncode(int_vec); for (size_t i=0; i<int_vec.size(); ++i) { int32_t temp = htobe32(int_vec[i]); ss.write(reinterpret_cast< char * >(&temp), sizeof(temp)); } return stringstreamToCharVector(ss); } inline std::vector<char> encodeRunLengthFloat(std::vector<float> floats_in, int32_t multiplier) { std::stringstream ss; add_header(ss, floats_in.size(), 9, multiplier); std::vector<int32_t> int_vec = convertFloatsToInts(floats_in, multiplier); int_vec = runLengthEncode(int_vec); for (size_t i=0; i<int_vec.size(); ++i) { int32_t temp = htobe32(int_vec[i]); ss.write(reinterpret_cast< char * >(&temp), sizeof(temp)); } return stringstreamToCharVector(ss); } inline std::vector<char> encodeDeltaRecursiveFloat(std::vector<float> floats_in, int32_t multiplier) { std::stringstream ss; add_header(ss, floats_in.size(), 10, multiplier); std::vector<int32_t> int_vec = convertFloatsToInts(floats_in, multiplier); int_vec = deltaEncode(int_vec); int_vec = recursiveIndexEncode(int_vec); for (size_t i=0; i<int_vec.size(); ++i) { int16_t temp = htobe16(int_vec[i]); ss.write(reinterpret_cast< char * >(&temp), sizeof(temp)); } return stringstreamToCharVector(ss); } } // mmtf namespace #endif <|endoftext|>
<commit_before>#include "highlighters.hh" #include "assert.hh" #include "window.hh" #include "highlighter_registry.hh" #include "highlighter_group.hh" #include "regex.hh" namespace Kakoune { using namespace std::placeholders; typedef boost::regex_iterator<BufferIterator> RegexIterator; template<typename T> void highlight_range(DisplayBuffer& display_buffer, BufferIterator begin, BufferIterator end, bool skip_replaced, T func) { if (end <= display_buffer.range().first or begin >= display_buffer.range().second) return; for (auto& line : display_buffer.lines()) { if (line.buffer_line() >= begin.line() and line.buffer_line() <= end.line()) { for (auto atom_it = line.begin(); atom_it != line.end(); ++atom_it) { bool is_replaced = atom_it->content.type() == AtomContent::ReplacedBufferRange; if (not atom_it->content.has_buffer_range() or (skip_replaced and is_replaced)) continue; if (end <= atom_it->content.begin() or begin >= atom_it->content.end()) continue; if (not is_replaced and begin > atom_it->content.begin()) atom_it = ++line.split(atom_it, begin); if (not is_replaced and end < atom_it->content.end()) { atom_it = line.split(atom_it, end); func(*atom_it); ++atom_it; } else func(*atom_it); } } } } void colorize_regex(DisplayBuffer& display_buffer, const Regex& ex, Color fg_color, Color bg_color = Color::Default) { const BufferRange& range = display_buffer.range(); RegexIterator re_it(range.first, range.second, ex, boost::match_nosubs); RegexIterator re_end; for (; re_it != re_end; ++re_it) { highlight_range(display_buffer, (*re_it)[0].first, (*re_it)[0].second, true, [&](DisplayAtom& atom) { atom.fg_color = fg_color; atom.bg_color = bg_color; }); } } Color parse_color(const String& color) { if (color == "default") return Color::Default; if (color == "black") return Color::Black; if (color == "red") return Color::Red; if (color == "green") return Color::Green; if (color == "yellow") return Color::Yellow; if (color == "blue") return Color::Blue; if (color == "magenta") return Color::Magenta; if (color == "cyan") return Color::Cyan; if (color == "white") return Color::White; return Color::Default; } HighlighterAndId colorize_regex_factory(Window& window, const HighlighterParameters params) { if (params.size() != 3) throw runtime_error("wrong parameter count"); Regex ex(params[0].begin(), params[0].end()); Color fg_color = parse_color(params[1]); Color bg_color = parse_color(params[2]); String id = "colre'" + params[0] + "'"; return HighlighterAndId(id, std::bind(colorize_regex, _1, ex, fg_color, bg_color)); } void expand_tabulations(Window& window, DisplayBuffer& display_buffer) { const int tabstop = window.option_manager()["tabstop"].as_int(); for (auto& line : display_buffer.lines()) { for (auto atom_it = line.begin(); atom_it != line.end(); ++atom_it) { if (atom_it->content.type() != AtomContent::BufferRange) continue; auto begin = atom_it->content.begin(); auto end = atom_it->content.end(); for (BufferIterator it = begin; it != end; ++it) { if (*it == '\t') { if (it != begin) atom_it = ++line.split(atom_it, it); if (it+1 != end) atom_it = line.split(atom_it, it+1); BufferCoord pos = it.buffer().line_and_column_at(it); int column = 0; for (auto line_it = it.buffer().iterator_at({pos.line, 0}); line_it != it; ++line_it) { assert(*line_it != '\n'); if (*line_it == '\t') column += tabstop - (column % tabstop); else ++column; } int count = tabstop - (column % tabstop); String padding; for (int i = 0; i < count; ++i) padding += ' '; atom_it->content.replace(padding); break; } } } } } void show_line_numbers(Window& window, DisplayBuffer& display_buffer) { int last_line = window.buffer().line_count(); int digit_count = 0; for (int c = last_line; c > 0; c /= 10) ++digit_count; char format[] = "%?d "; format[1] = '0' + digit_count; for (auto& line : display_buffer.lines()) { char buffer[10]; snprintf(buffer, 10, format, line.buffer_line() + 1); DisplayAtom atom = DisplayAtom(AtomContent(buffer)); atom.fg_color = Color::Black; atom.bg_color = Color::White; line.insert(line.begin(), std::move(atom)); } } void highlight_selections(Window& window, DisplayBuffer& display_buffer) { for (auto& sel : window.selections()) { highlight_range(display_buffer, sel.begin(), sel.end(), false, [](DisplayAtom& atom) { atom.attribute |= Attributes::Underline; }); const BufferIterator& last = sel.last(); highlight_range(display_buffer, last, last+1, false, [](DisplayAtom& atom) { atom.attribute |= Attributes::Reverse; }); } } template<void (*highlighter_func)(DisplayBuffer&)> class SimpleHighlighterFactory { public: SimpleHighlighterFactory(const String& id) : m_id(id) {} HighlighterAndId operator()(Window& window, const HighlighterParameters& params) const { return HighlighterAndId(m_id, HighlighterFunc(highlighter_func)); } private: String m_id; }; template<void (*highlighter_func)(Window&, DisplayBuffer&)> class WindowHighlighterFactory { public: WindowHighlighterFactory(const String& id) : m_id(id) {} HighlighterAndId operator()(Window& window, const HighlighterParameters& params) const { return HighlighterAndId(m_id, std::bind(highlighter_func, std::ref(window), _1)); } private: String m_id; }; HighlighterAndId highlighter_group_factory(Window& window, const HighlighterParameters& params) { if (params.size() != 1) throw runtime_error("wrong parameter count"); return HighlighterAndId(params[0], HighlighterGroup()); } void register_highlighters() { HighlighterRegistry& registry = HighlighterRegistry::instance(); registry.register_factory("highlight_selections", WindowHighlighterFactory<highlight_selections>("highlight_selections")); registry.register_factory("expand_tabs", WindowHighlighterFactory<expand_tabulations>("expand_tabs")); registry.register_factory("number_lines", WindowHighlighterFactory<show_line_numbers>("number_lines")); registry.register_factory("regex", colorize_regex_factory); registry.register_factory("group", highlighter_group_factory); } } <commit_msg>optimize regex highlighter's regex<commit_after>#include "highlighters.hh" #include "assert.hh" #include "window.hh" #include "highlighter_registry.hh" #include "highlighter_group.hh" #include "regex.hh" namespace Kakoune { using namespace std::placeholders; typedef boost::regex_iterator<BufferIterator> RegexIterator; template<typename T> void highlight_range(DisplayBuffer& display_buffer, BufferIterator begin, BufferIterator end, bool skip_replaced, T func) { if (end <= display_buffer.range().first or begin >= display_buffer.range().second) return; for (auto& line : display_buffer.lines()) { if (line.buffer_line() >= begin.line() and line.buffer_line() <= end.line()) { for (auto atom_it = line.begin(); atom_it != line.end(); ++atom_it) { bool is_replaced = atom_it->content.type() == AtomContent::ReplacedBufferRange; if (not atom_it->content.has_buffer_range() or (skip_replaced and is_replaced)) continue; if (end <= atom_it->content.begin() or begin >= atom_it->content.end()) continue; if (not is_replaced and begin > atom_it->content.begin()) atom_it = ++line.split(atom_it, begin); if (not is_replaced and end < atom_it->content.end()) { atom_it = line.split(atom_it, end); func(*atom_it); ++atom_it; } else func(*atom_it); } } } } void colorize_regex(DisplayBuffer& display_buffer, const Regex& ex, Color fg_color, Color bg_color = Color::Default) { const BufferRange& range = display_buffer.range(); RegexIterator re_it(range.first, range.second, ex, boost::match_nosubs); RegexIterator re_end; for (; re_it != re_end; ++re_it) { highlight_range(display_buffer, (*re_it)[0].first, (*re_it)[0].second, true, [&](DisplayAtom& atom) { atom.fg_color = fg_color; atom.bg_color = bg_color; }); } } Color parse_color(const String& color) { if (color == "default") return Color::Default; if (color == "black") return Color::Black; if (color == "red") return Color::Red; if (color == "green") return Color::Green; if (color == "yellow") return Color::Yellow; if (color == "blue") return Color::Blue; if (color == "magenta") return Color::Magenta; if (color == "cyan") return Color::Cyan; if (color == "white") return Color::White; return Color::Default; } HighlighterAndId colorize_regex_factory(Window& window, const HighlighterParameters params) { if (params.size() != 3) throw runtime_error("wrong parameter count"); Regex ex(params[0].begin(), params[0].end(), boost::regex::perl | boost::regex::optimize); Color fg_color = parse_color(params[1]); Color bg_color = parse_color(params[2]); String id = "colre'" + params[0] + "'"; return HighlighterAndId(id, std::bind(colorize_regex, _1, ex, fg_color, bg_color)); } void expand_tabulations(Window& window, DisplayBuffer& display_buffer) { const int tabstop = window.option_manager()["tabstop"].as_int(); for (auto& line : display_buffer.lines()) { for (auto atom_it = line.begin(); atom_it != line.end(); ++atom_it) { if (atom_it->content.type() != AtomContent::BufferRange) continue; auto begin = atom_it->content.begin(); auto end = atom_it->content.end(); for (BufferIterator it = begin; it != end; ++it) { if (*it == '\t') { if (it != begin) atom_it = ++line.split(atom_it, it); if (it+1 != end) atom_it = line.split(atom_it, it+1); BufferCoord pos = it.buffer().line_and_column_at(it); int column = 0; for (auto line_it = it.buffer().iterator_at({pos.line, 0}); line_it != it; ++line_it) { assert(*line_it != '\n'); if (*line_it == '\t') column += tabstop - (column % tabstop); else ++column; } int count = tabstop - (column % tabstop); String padding; for (int i = 0; i < count; ++i) padding += ' '; atom_it->content.replace(padding); break; } } } } } void show_line_numbers(Window& window, DisplayBuffer& display_buffer) { int last_line = window.buffer().line_count(); int digit_count = 0; for (int c = last_line; c > 0; c /= 10) ++digit_count; char format[] = "%?d "; format[1] = '0' + digit_count; for (auto& line : display_buffer.lines()) { char buffer[10]; snprintf(buffer, 10, format, line.buffer_line() + 1); DisplayAtom atom = DisplayAtom(AtomContent(buffer)); atom.fg_color = Color::Black; atom.bg_color = Color::White; line.insert(line.begin(), std::move(atom)); } } void highlight_selections(Window& window, DisplayBuffer& display_buffer) { for (auto& sel : window.selections()) { highlight_range(display_buffer, sel.begin(), sel.end(), false, [](DisplayAtom& atom) { atom.attribute |= Attributes::Underline; }); const BufferIterator& last = sel.last(); highlight_range(display_buffer, last, last+1, false, [](DisplayAtom& atom) { atom.attribute |= Attributes::Reverse; }); } } template<void (*highlighter_func)(DisplayBuffer&)> class SimpleHighlighterFactory { public: SimpleHighlighterFactory(const String& id) : m_id(id) {} HighlighterAndId operator()(Window& window, const HighlighterParameters& params) const { return HighlighterAndId(m_id, HighlighterFunc(highlighter_func)); } private: String m_id; }; template<void (*highlighter_func)(Window&, DisplayBuffer&)> class WindowHighlighterFactory { public: WindowHighlighterFactory(const String& id) : m_id(id) {} HighlighterAndId operator()(Window& window, const HighlighterParameters& params) const { return HighlighterAndId(m_id, std::bind(highlighter_func, std::ref(window), _1)); } private: String m_id; }; HighlighterAndId highlighter_group_factory(Window& window, const HighlighterParameters& params) { if (params.size() != 1) throw runtime_error("wrong parameter count"); return HighlighterAndId(params[0], HighlighterGroup()); } void register_highlighters() { HighlighterRegistry& registry = HighlighterRegistry::instance(); registry.register_factory("highlight_selections", WindowHighlighterFactory<highlight_selections>("highlight_selections")); registry.register_factory("expand_tabs", WindowHighlighterFactory<expand_tabulations>("expand_tabs")); registry.register_factory("number_lines", WindowHighlighterFactory<show_line_numbers>("number_lines")); registry.register_factory("regex", colorize_regex_factory); registry.register_factory("group", highlighter_group_factory); } } <|endoftext|>
<commit_before>/* * runinbg.cpp * PHD Guiding * * Created by Andy Galasso. * Copyright (c) 2014 Andy Galasso * All rights reserved. * * This source code is distributed under the following "BSD" license * 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 Craig Stark, Stark Labs 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 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 "phd.h" #include <wx/progdlg.h> struct ProgressWindow : public wxProgressDialog { ProgressWindow(wxWindow *parent, const wxString& title, const wxString& message) : wxProgressDialog(title, message, 100, parent, wxPD_APP_MODAL | wxPD_AUTO_HIDE | wxPD_SMOOTH | wxPD_CAN_ABORT) { } }; struct RunInBgImpl : public wxTimer, public wxThreadHelper { RunInBg *m_bg; wxWindow *m_parent; wxString m_title; wxString m_message; ProgressWindow *m_win; bool m_shown; volatile bool m_done; volatile bool m_canceled; wxDateTime m_showTime; wxString m_errorMsg; RunInBgImpl(RunInBg *bg, wxWindow *parent, const wxString& title, const wxString& message) : m_bg(bg), m_parent(parent), m_title(title), m_message(message), m_shown(false), m_win(0), m_done(false), m_canceled(false) { } bool Run() { bool err = false; wxBusyCursor busy; if (m_parent) m_parent->SetCursor(wxCURSOR_WAIT); // need to do this too! #ifndef __APPLE__ // this makes the progress window inaccessible on OSX wxWindowDisabler wd; #endif // __APPLE__ CreateThread(); wxThread *thread = GetThread(); thread->Run(); m_showTime = wxDateTime::UNow() + wxTimeSpan(0, 0, 2, 500); Start(250); // start timer while (!m_done && !m_canceled) { wxYield(); wxMilliSleep(20); } Stop(); // stop timer if (m_canceled && !m_done) { // give it a bit of time to respond to cancel before killing it for (int i = 0; i < 50 && !m_done; i++) { wxYield(); wxMilliSleep(20); } if (!m_done) { Debug.AddLine("Background thread did not respond to cancel... kill it"); m_bg->OnKill(); thread->Kill(); thread = 0; err = true; m_errorMsg = _("The operation was canceled"); } } if (m_win) { delete m_win; m_win = 0; } if (thread) err = thread->Wait() ? true : false; if (m_parent) m_parent->SetCursor(wxCURSOR_ARROW); return err; } void Notify() // timer notification { if (!m_shown && wxDateTime::UNow() >= m_showTime) { m_win = new ProgressWindow(m_parent, m_title, m_message); m_shown = true; } if (m_win) { bool cont = m_win->Pulse(); if (!cont) { m_canceled = true; Debug.AddLine("Canceled"); delete m_win; m_win = 0; } } } wxThread::ExitCode Entry() { bool err = m_bg->Entry(); m_done = true; return (wxThread::ExitCode) err; } }; RunInBg::RunInBg(wxWindow *parent, const wxString& title, const wxString& message) : m_impl(new RunInBgImpl(this, parent, title, message)) { } RunInBg::~RunInBg(void) { delete m_impl; } bool RunInBg::Run(void) { return m_impl->Run(); } void RunInBg::SetErrorMsg(const wxString& msg) { m_impl->m_errorMsg = msg; } wxString RunInBg::GetErrorMsg(void) { return m_impl->m_errorMsg; } bool RunInBg::IsCanceled(void) { return m_impl->m_canceled; } void RunInBg::OnKill() { } <commit_msg>fix Linux compile error<commit_after>/* * runinbg.cpp * PHD Guiding * * Created by Andy Galasso. * Copyright (c) 2014 Andy Galasso * All rights reserved. * * This source code is distributed under the following "BSD" license * 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 Craig Stark, Stark Labs 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 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 "phd.h" #include <wx/progdlg.h> struct ProgressWindow : public wxProgressDialog { ProgressWindow(wxWindow *parent, const wxString& title, const wxString& message) : wxProgressDialog(title, message, 100, parent, wxPD_APP_MODAL | wxPD_AUTO_HIDE | wxPD_SMOOTH | wxPD_CAN_ABORT) { } }; struct RunInBgImpl : public wxTimer, public wxThreadHelper { RunInBg *m_bg; wxWindow *m_parent; wxString m_title; wxString m_message; ProgressWindow *m_win; bool m_shown; volatile bool m_done; volatile bool m_canceled; wxDateTime m_showTime; wxString m_errorMsg; RunInBgImpl(RunInBg *bg, wxWindow *parent, const wxString& title, const wxString& message) : m_bg(bg), m_parent(parent), m_title(title), m_message(message), m_win(0), m_shown(false), m_done(false), m_canceled(false) { } bool Run() { bool err = false; wxBusyCursor busy; if (m_parent) m_parent->SetCursor(wxCURSOR_WAIT); // need to do this too! #ifndef __APPLE__ // this makes the progress window inaccessible on OSX wxWindowDisabler wd; #endif // __APPLE__ CreateThread(); wxThread *thread = GetThread(); thread->Run(); m_showTime = wxDateTime::UNow() + wxTimeSpan(0, 0, 2, 500); Start(250); // start timer while (!m_done && !m_canceled) { wxYield(); wxMilliSleep(20); } Stop(); // stop timer if (m_canceled && !m_done) { // give it a bit of time to respond to cancel before killing it for (int i = 0; i < 50 && !m_done; i++) { wxYield(); wxMilliSleep(20); } if (!m_done) { Debug.AddLine("Background thread did not respond to cancel... kill it"); m_bg->OnKill(); thread->Kill(); thread = 0; err = true; m_errorMsg = _("The operation was canceled"); } } if (m_win) { delete m_win; m_win = 0; } if (thread) err = thread->Wait() ? true : false; if (m_parent) m_parent->SetCursor(wxCURSOR_ARROW); return err; } void Notify() // timer notification { if (!m_shown && wxDateTime::UNow() >= m_showTime) { m_win = new ProgressWindow(m_parent, m_title, m_message); m_shown = true; } if (m_win) { bool cont = m_win->Pulse(); if (!cont) { m_canceled = true; Debug.AddLine("Canceled"); delete m_win; m_win = 0; } } } wxThread::ExitCode Entry() { bool err = m_bg->Entry(); m_done = true; return (wxThread::ExitCode) err; } }; RunInBg::RunInBg(wxWindow *parent, const wxString& title, const wxString& message) : m_impl(new RunInBgImpl(this, parent, title, message)) { } RunInBg::~RunInBg(void) { delete m_impl; } bool RunInBg::Run(void) { return m_impl->Run(); } void RunInBg::SetErrorMsg(const wxString& msg) { m_impl->m_errorMsg = msg; } wxString RunInBg::GetErrorMsg(void) { return m_impl->m_errorMsg; } bool RunInBg::IsCanceled(void) { return m_impl->m_canceled; } void RunInBg::OnKill() { } <|endoftext|>
<commit_before>#include "VerifyFormat.h" #include "corelib.h" #include "StringXStream.h" static bool verifyDTvalues(int yyyy, int mon, int dd, int hh, int min, int ss) { const int month_lengths[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; // Built-in obsolesence for pwsafe in 2038? if (yyyy < 1970 || yyyy > 2038) return false; if ((mon < 1 || mon > 12) || (dd < 1)) return false; if (mon == 2 && (yyyy % 4) == 0) { // Feb and a leap year if (dd > 29) return false; } else { // Either (Not Feb) or (Is Feb but not a leap-year) if (dd > month_lengths[mon - 1]) return false; } if ((hh < 0 || hh > 23) || (min < 0 || min > 59) || (ss < 0 || ss > 59)) return false; return true; } bool VerifyImportDateTimeString(const stringT &time_str, time_t &t) { // String format must be "yyyy/mm/dd hh:mm:ss" // "0123456789012345678" const int ndigits = 14; const int idigits[ndigits] = {0, 1, 2, 3, 5, 6, 8, 9, 11, 12, 14, 15, 17, 18}; int yyyy, mon, dd, hh, min, ss; t = (time_t)-1; if (time_str.length() != 19) return false; // Validate time_str if (time_str[4] != TCHAR('/') || time_str[7] != TCHAR('/') || time_str[10] != TCHAR(' ') || time_str[13] != TCHAR(':') || time_str[16] != TCHAR(':')) return false; for (int i = 0; i < ndigits; i++) if (!isdigit(time_str[idigits[i]])) return false; istringstreamT is(time_str); TCHAR dummy; is >> yyyy >> dummy >> mon >> dummy >> dd >> hh >> dummy >> min >> dummy >> ss; if (!verifyDTvalues(yyyy, mon, dd, hh, min, ss)) return false; // Accept 01/01/1970 as a special 'unset' value, otherwise there can be // issues with CTime constructor after apply daylight savings offset. if (yyyy == 1970 && mon == 1 && dd == 1) { t = (time_t)0; return true; } const CTime ct(yyyy, mon, dd, hh, min, ss, -1); t = (time_t)ct.GetTime(); return true; } bool VerifyASCDateTimeString(const stringT &time_str, time_t &t) { // String format must be "ddd MMM dd hh:mm:ss yyyy" // "012345678901234567890123" // e.g., "Wed Oct 06 21:02:38 2008" const stringT str_months = _T("JanFebMarAprMayJunJulAugSepOctNovDec"); const stringT str_days = _T("SunMonTueWedThuFriSat"); const int ndigits = 12; const int idigits[ndigits] = {8, 9, 11, 12, 14, 15, 17, 18, 20, 21, 22, 23}; stringT::size_type iMON, iDOW; int yyyy, mon, dd, hh, min, ss; t = (time_t)-1; if (time_str.length() != 24) return false; // Validate time_str if (time_str[13] != TCHAR(':') || time_str[16] != TCHAR(':')) return false; for (int i = 0; i < ndigits; i++) if (!isdigit(time_str[idigits[i]])) return false; istringstreamT is(time_str); stringT dow, mon_str; TCHAR dummy; is >> dow >> mon_str >> dd >> hh >> dummy >> min >> dummy >> ss >> yyyy; iMON = str_months.find(mon_str); if (iMON == stringT::npos) return false; mon = (iMON / 3) + 1; if (!verifyDTvalues(yyyy, mon, dd, hh, min, ss)) return false; // Accept 01/01/1970 as a special 'unset' value, otherwise there can be // issues with CTime constructor after apply daylight savings offset. if (yyyy == 1970 && mon == 1 && dd == 1) { t = (time_t)0; return true; } const CTime ct(yyyy, mon, dd, hh, min, ss, -1); iDOW = str_days.find(dow); if (iDOW == stringT::npos) return false; iDOW = (iDOW / 3) + 1; if (iDOW != stringT::size_type(ct.GetDayOfWeek())) return false; t = (time_t)ct.GetTime(); return true; } bool VerifyXMLDateTimeString(const stringT &time_str, time_t &t) { // String format must be "yyyy-mm-ddThh:mm:ss" // "0123456789012345678" // e.g., "2008-10-06T21:20:56" stringT xtime_str; const int ndigits = 14; const int idigits[ndigits] = {0, 1, 2, 3, 5, 6, 8, 9, 11, 12, 14, 15, 17, 18}; int yyyy, mon, dd, hh, min, ss; t = (time_t)-1; if (time_str.length() != 19) return false; // Validate time_str if (time_str[4] != TCHAR('-') || time_str[7] != TCHAR('-') || time_str[10] != TCHAR('T') || time_str[13] != TCHAR(':') || time_str[16] != TCHAR(':')) return false; for (int i = 0; i < ndigits; i++) { if (!isdigit(time_str[idigits[i]])) return false; } istringstreamT is(time_str); TCHAR dummy; is >> yyyy >> dummy >> mon >> dummy >> dd >> dummy >> hh >> dummy >> min >> dummy >> ss; if (!verifyDTvalues(yyyy, mon, dd, hh, min, ss)) return false; // Accept 01/01/1970 as a special 'unset' value, otherwise there can be // issues with CTime constructor after apply daylight savings offset. if (yyyy == 1970 && mon == 1 && dd == 1) { t = (time_t)0; return true; } const CTime ct(yyyy, mon, dd, hh, min, ss, -1); t = (time_t)ct.GetTime(); return true; } bool VerifyXMLDateString(const stringT &time_str, time_t &t) { // String format must be "yyyy-mm-dd" // "0123456789" stringT xtime_str; const int ndigits = 8; const int idigits[ndigits] = {0, 1, 2, 3, 5, 6, 8, 9}; int yyyy, mon, dd; t = (time_t)-1; if (time_str.length() != 10) return false; // Validate time_str if (time_str.substr(4,1) != _S("-") || time_str.substr(7,1) != _S("-")) return false; for (int i = 0; i < ndigits; i++) { if (!isdigit(time_str[idigits[i]])) return false; } istringstreamT is(time_str); TCHAR dummy; is >> yyyy >> dummy >> mon >> dummy >> dd; if (!verifyDTvalues(yyyy, mon, dd, 1, 2, 3)) return false; // Accept 01/01/1970 as a special 'unset' value, otherwise there can be // issues with CTime constructor after apply daylight savings offset. if (yyyy == 1970 && mon == 1 && dd == 1) { t = (time_t)0; return true; } const CTime ct(yyyy, mon, dd, 0, 0, 0, -1); t = (time_t)ct.GetTime(); return true; } int VerifyImportPWHistoryString(const StringX &PWHistory, StringX &newPWHistory, stringT &strErrors) { // Format is (! == mandatory blank, unless at the end of the record): // sxx00 // or // sxxnn!yyyy/mm/dd!hh:mm:ss!llll!pppp...pppp!yyyy/mm/dd!hh:mm:ss!llll!pppp...pppp!......... // Note: // !yyyy/mm/dd!hh:mm:ss! may be !1970-01-01 00:00:00! meaning unknown StringX tmp, pwh; stringT buffer; int ipwlen, s = -1, m = -1, n = -1; int rc = PWH_OK; time_t t; newPWHistory = _T(""); strErrors = _T(""); pwh = PWHistory; int len = pwh.length(); int pwleft = len; if (pwleft == 0) return PWH_OK; if (pwleft < 5) { rc = PWH_INVALID_HDR; goto exit; } const TCHAR *lpszPWHistory = pwh.c_str(); { #if _MSC_VER >= 1400 int iread = _stscanf_s(lpszPWHistory, _T("%01d%02x%02x"), &s, &m, &n); #else int iread = _stscanf(lpszPWHistory, _T("%01d%02x%02x"), &s, &m, &n); #endif if (iread != 3) { rc = PWH_INVALID_HDR; goto relbuf; } } if (s != 0 && s != 1) { rc = PWH_INVALID_STATUS; goto relbuf; } if (n > m) { rc = PWH_INVALID_NUM; goto relbuf; } lpszPWHistory += 5; pwleft -= 5; if (pwleft == 0 && s == 0 && m == 0 && n == 0) { rc = PWH_IGNORE; goto relbuf; } Format(buffer, _T("%01d%02x%02x"), s, m, n); newPWHistory = buffer.c_str(); for (int i = 0; i < n; i++) { if (pwleft < 26) { // blank + date(10) + blank + time(8) + blank + pw_length(4) + blank rc = PWH_TOO_SHORT; goto relbuf; } if (lpszPWHistory[0] != _T(' ')) { rc = PWH_INVALID_CHARACTER; goto relbuf; } lpszPWHistory += 1; pwleft -= 1; tmp = StringX(lpszPWHistory, 19); if (tmp.substr(0, 10) == _T("1970-01-01")) t = 0; else { if (!VerifyImportDateTimeString(tmp.c_str(), t)) { rc = PWH_INVALID_DATETIME; goto relbuf; } } lpszPWHistory += 19; pwleft -= 19; if (lpszPWHistory[0] != _T(' ')) { rc = PWH_INVALID_CHARACTER; goto relbuf; } lpszPWHistory += 1; pwleft -= 1; { #if _MSC_VER >= 1400 int iread = _stscanf_s(lpszPWHistory, _T("%04x"), &ipwlen); #else int iread = _stscanf(lpszPWHistory, _T("%04x"), &ipwlen); #endif if (iread != 1) { rc = PWH_INVALID_PSWD_LENGTH; goto relbuf; } } lpszPWHistory += 4; pwleft -= 4; if (lpszPWHistory[0] != _T(' ')) { rc = PWH_INVALID_CHARACTER; goto relbuf; } lpszPWHistory += 1; pwleft -= 1; if (pwleft < ipwlen) { rc = PWH_INVALID_PSWD_LENGTH; goto relbuf; } tmp = StringX(lpszPWHistory, ipwlen); Format(buffer, _T("%08x%04x%s"), (long) t, ipwlen, tmp.c_str()); newPWHistory += buffer.c_str(); buffer.clear(); lpszPWHistory += ipwlen; pwleft -= ipwlen; } if (pwleft > 0) rc = PWH_TOO_LONG; relbuf: // pwh.ReleaseBuffer(); - obsoleted by move to StringX exit: Format(buffer, IDSC_PWHERROR, len - pwleft + 1); stringT temp; switch (rc) { case PWH_OK: case PWH_IGNORE: temp.clear(); buffer.clear(); break; case PWH_INVALID_HDR: Format(temp, IDSC_INVALIDHEADER, PWHistory.c_str()); break; case PWH_INVALID_STATUS: Format(temp, IDSC_INVALIDPWHSTATUS, s); break; case PWH_INVALID_NUM: Format(temp, IDSC_INVALIDNUMOLDPW, n, m); break; case PWH_INVALID_DATETIME: LoadAString(temp, IDSC_INVALIDDATETIME); break; case PWH_INVALID_PSWD_LENGTH: LoadAString(temp, IDSC_INVALIDPWLENGTH); break; case PWH_TOO_SHORT: LoadAString(temp, IDSC_FIELDTOOSHORT); break; case PWH_TOO_LONG: LoadAString(temp, IDSC_FIELDTOOLONG); break; case PWH_INVALID_CHARACTER: LoadAString(temp, IDSC_INVALIDSEPARATER); break; default: ASSERT(0); } strErrors = buffer + temp; if (rc != PWH_OK) newPWHistory = _T(""); return rc; } <commit_msg>port & cleanup of Verify.cpp - part 2 & last.<commit_after>#include "VerifyFormat.h" #include "corelib.h" #include "StringXStream.h" static bool verifyDTvalues(int yyyy, int mon, int dd, int hh, int min, int ss) { const int month_lengths[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; // Built-in obsolesence for pwsafe in 2038? if (yyyy < 1970 || yyyy > 2038) return false; if ((mon < 1 || mon > 12) || (dd < 1)) return false; if (mon == 2 && (yyyy % 4) == 0) { // Feb and a leap year if (dd > 29) return false; } else { // Either (Not Feb) or (Is Feb but not a leap-year) if (dd > month_lengths[mon - 1]) return false; } if ((hh < 0 || hh > 23) || (min < 0 || min > 59) || (ss < 0 || ss > 59)) return false; return true; } bool VerifyImportDateTimeString(const stringT &time_str, time_t &t) { // String format must be "yyyy/mm/dd hh:mm:ss" // "0123456789012345678" const int ndigits = 14; const int idigits[ndigits] = {0, 1, 2, 3, 5, 6, 8, 9, 11, 12, 14, 15, 17, 18}; int yyyy, mon, dd, hh, min, ss; t = (time_t)-1; if (time_str.length() != 19) return false; // Validate time_str if (time_str[4] != TCHAR('/') || time_str[7] != TCHAR('/') || time_str[10] != TCHAR(' ') || time_str[13] != TCHAR(':') || time_str[16] != TCHAR(':')) return false; for (int i = 0; i < ndigits; i++) if (!isdigit(time_str[idigits[i]])) return false; istringstreamT is(time_str); TCHAR dummy; is >> yyyy >> dummy >> mon >> dummy >> dd >> hh >> dummy >> min >> dummy >> ss; if (!verifyDTvalues(yyyy, mon, dd, hh, min, ss)) return false; // Accept 01/01/1970 as a special 'unset' value, otherwise there can be // issues with CTime constructor after apply daylight savings offset. if (yyyy == 1970 && mon == 1 && dd == 1) { t = (time_t)0; return true; } const CTime ct(yyyy, mon, dd, hh, min, ss, -1); t = (time_t)ct.GetTime(); return true; } bool VerifyASCDateTimeString(const stringT &time_str, time_t &t) { // String format must be "ddd MMM dd hh:mm:ss yyyy" // "012345678901234567890123" // e.g., "Wed Oct 06 21:02:38 2008" const stringT str_months = _T("JanFebMarAprMayJunJulAugSepOctNovDec"); const stringT str_days = _T("SunMonTueWedThuFriSat"); const int ndigits = 12; const int idigits[ndigits] = {8, 9, 11, 12, 14, 15, 17, 18, 20, 21, 22, 23}; stringT::size_type iMON, iDOW; int yyyy, mon, dd, hh, min, ss; t = (time_t)-1; if (time_str.length() != 24) return false; // Validate time_str if (time_str[13] != TCHAR(':') || time_str[16] != TCHAR(':')) return false; for (int i = 0; i < ndigits; i++) if (!isdigit(time_str[idigits[i]])) return false; istringstreamT is(time_str); stringT dow, mon_str; TCHAR dummy; is >> dow >> mon_str >> dd >> hh >> dummy >> min >> dummy >> ss >> yyyy; iMON = str_months.find(mon_str); if (iMON == stringT::npos) return false; mon = (iMON / 3) + 1; if (!verifyDTvalues(yyyy, mon, dd, hh, min, ss)) return false; // Accept 01/01/1970 as a special 'unset' value, otherwise there can be // issues with CTime constructor after apply daylight savings offset. if (yyyy == 1970 && mon == 1 && dd == 1) { t = (time_t)0; return true; } const CTime ct(yyyy, mon, dd, hh, min, ss, -1); iDOW = str_days.find(dow); if (iDOW == stringT::npos) return false; iDOW = (iDOW / 3) + 1; if (iDOW != stringT::size_type(ct.GetDayOfWeek())) return false; t = (time_t)ct.GetTime(); return true; } bool VerifyXMLDateTimeString(const stringT &time_str, time_t &t) { // String format must be "yyyy-mm-ddThh:mm:ss" // "0123456789012345678" // e.g., "2008-10-06T21:20:56" stringT xtime_str; const int ndigits = 14; const int idigits[ndigits] = {0, 1, 2, 3, 5, 6, 8, 9, 11, 12, 14, 15, 17, 18}; int yyyy, mon, dd, hh, min, ss; t = (time_t)-1; if (time_str.length() != 19) return false; // Validate time_str if (time_str[4] != TCHAR('-') || time_str[7] != TCHAR('-') || time_str[10] != TCHAR('T') || time_str[13] != TCHAR(':') || time_str[16] != TCHAR(':')) return false; for (int i = 0; i < ndigits; i++) { if (!isdigit(time_str[idigits[i]])) return false; } istringstreamT is(time_str); TCHAR dummy; is >> yyyy >> dummy >> mon >> dummy >> dd >> dummy >> hh >> dummy >> min >> dummy >> ss; if (!verifyDTvalues(yyyy, mon, dd, hh, min, ss)) return false; // Accept 01/01/1970 as a special 'unset' value, otherwise there can be // issues with CTime constructor after apply daylight savings offset. if (yyyy == 1970 && mon == 1 && dd == 1) { t = (time_t)0; return true; } const CTime ct(yyyy, mon, dd, hh, min, ss, -1); t = (time_t)ct.GetTime(); return true; } bool VerifyXMLDateString(const stringT &time_str, time_t &t) { // String format must be "yyyy-mm-dd" // "0123456789" stringT xtime_str; const int ndigits = 8; const int idigits[ndigits] = {0, 1, 2, 3, 5, 6, 8, 9}; int yyyy, mon, dd; t = (time_t)-1; if (time_str.length() != 10) return false; // Validate time_str if (time_str.substr(4,1) != _S("-") || time_str.substr(7,1) != _S("-")) return false; for (int i = 0; i < ndigits; i++) { if (!isdigit(time_str[idigits[i]])) return false; } istringstreamT is(time_str); TCHAR dummy; is >> yyyy >> dummy >> mon >> dummy >> dd; if (!verifyDTvalues(yyyy, mon, dd, 1, 2, 3)) return false; // Accept 01/01/1970 as a special 'unset' value, otherwise there can be // issues with CTime constructor after apply daylight savings offset. if (yyyy == 1970 && mon == 1 && dd == 1) { t = (time_t)0; return true; } const CTime ct(yyyy, mon, dd, 0, 0, 0, -1); t = (time_t)ct.GetTime(); return true; } int VerifyImportPWHistoryString(const StringX &PWHistory, StringX &newPWHistory, stringT &strErrors) { // Format is (! == mandatory blank, unless at the end of the record): // sxx00 // or // sxxnn!yyyy/mm/dd!hh:mm:ss!llll!pppp...pppp!yyyy/mm/dd!hh:mm:ss!llll!pppp...pppp!......... // Note: // !yyyy/mm/dd!hh:mm:ss! may be !1970-01-01 00:00:00! meaning unknown stringT buffer; int ipwlen, pwleft = 0, s = -1, m = -1, n = -1; int rc = PWH_OK; time_t t; newPWHistory = _T(""); strErrors = _T(""); if (PWHistory.empty()) return PWH_OK; StringX pwh(PWHistory); StringX tmp; int len = pwh.length(); if (len < 5) { rc = PWH_INVALID_HDR; goto exit; } if (pwh[0] == TCHAR('0')) s = 0; else if (pwh[0] == TCHAR('1')) s = 1; else { rc = PWH_INVALID_STATUS; goto exit; } { StringX s1 (pwh.substr(1, 2)); StringX s2 (pwh.substr(3, 4)); iStringXStream is1(s1), is2(s2); is1 >> std::hex >> m; is2 >> std::hex >> n; } if (n > m) { rc = PWH_INVALID_NUM; goto exit; } const TCHAR *lpszPWHistory = pwh.c_str() + 5; pwleft = len - 5; if (pwleft == 0 && s == 0 && m == 0 && n == 0) { rc = PWH_IGNORE; goto exit; } Format(buffer, _T("%01d%02x%02x"), s, m, n); newPWHistory = buffer.c_str(); for (int i = 0; i < n; i++) { if (pwleft < 26) { // blank + date(10) + blank + time(8) + blank + pw_length(4) + blank rc = PWH_TOO_SHORT; goto exit; } if (lpszPWHistory[0] != _T(' ')) { rc = PWH_INVALID_CHARACTER; goto exit; } lpszPWHistory++; pwleft--; tmp = StringX(lpszPWHistory, 19); if (tmp.substr(0, 10) == _T("1970-01-01")) t = 0; else { if (!VerifyImportDateTimeString(tmp.c_str(), t)) { rc = PWH_INVALID_DATETIME; goto exit; } } lpszPWHistory += 19; pwleft -= 19; if (lpszPWHistory[0] != _T(' ')) { rc = PWH_INVALID_CHARACTER; goto exit; } lpszPWHistory++; pwleft--; { StringX s3(lpszPWHistory, 4); iStringXStream is3(s3); is3 >> std::hex >> ipwlen; } lpszPWHistory += 4; pwleft -= 4; if (lpszPWHistory[0] != _T(' ')) { rc = PWH_INVALID_CHARACTER; goto exit; } lpszPWHistory += 1; pwleft -= 1; if (pwleft < ipwlen) { rc = PWH_INVALID_PSWD_LENGTH; goto exit; } tmp = StringX(lpszPWHistory, ipwlen); Format(buffer, _T("%08x%04x%s"), (long) t, ipwlen, tmp.c_str()); newPWHistory += buffer.c_str(); buffer.clear(); lpszPWHistory += ipwlen; pwleft -= ipwlen; } if (pwleft > 0) rc = PWH_TOO_LONG; exit: Format(buffer, IDSC_PWHERROR, len - pwleft + 1); stringT temp; switch (rc) { case PWH_OK: case PWH_IGNORE: temp.clear(); buffer.clear(); break; case PWH_INVALID_HDR: Format(temp, IDSC_INVALIDHEADER, PWHistory.c_str()); break; case PWH_INVALID_STATUS: Format(temp, IDSC_INVALIDPWHSTATUS, s); break; case PWH_INVALID_NUM: Format(temp, IDSC_INVALIDNUMOLDPW, n, m); break; case PWH_INVALID_DATETIME: LoadAString(temp, IDSC_INVALIDDATETIME); break; case PWH_INVALID_PSWD_LENGTH: LoadAString(temp, IDSC_INVALIDPWLENGTH); break; case PWH_TOO_SHORT: LoadAString(temp, IDSC_FIELDTOOSHORT); break; case PWH_TOO_LONG: LoadAString(temp, IDSC_FIELDTOOLONG); break; case PWH_INVALID_CHARACTER: LoadAString(temp, IDSC_INVALIDSEPARATER); break; default: ASSERT(0); } strErrors = buffer + temp; if (rc != PWH_OK) newPWHistory = _T(""); return rc; } <|endoftext|>
<commit_before>#include "game.hpp" #include <fstream> #include <sstream> #include <SFML/Graphics/RenderWindow.hpp> #include <SFML/Window/Event.hpp> #include "../../messageBus/messageBus.hpp" //Global Function void initGui(aw::GuiController &gui); namespace aw { Game::Game(StateMachine &statemachine, MessageBus &messageBus): m_active(false), State(statemachine), m_messageBus(messageBus), m_gameState(GameState::STOPPED) { m_messageBus.addReceiver(this); m_gui.loadFont("data/fonts/visitor1.ttf"); initGui(m_gui); //Global Function } void Game::update(const sf::Time &frameTime) { m_active = true; if (m_music.getStatus() == sf::Music::Stopped) { m_music.play(); } if (m_gameState == GameState::RUNNING) { //check for collision or finish auto result = m_collisionSystem.checkCollision(m_player); if (result == CollisionType::WALL) { m_gameState = GameState::CRASHED; m_gui.setActiveLayer(1); return; } else if (result == CollisionType::FINISH) { m_gameState = GameState::FINISHED; m_gui.setActiveLayer(2); return; } //Check for Scriptactions m_scriptManager.update(m_player, m_camera); //Update the position later, so the user see the crash //Update player position m_player.upate(frameTime); //update the camera position m_camera.update(m_player.getPosition()); } } void Game::render(sf::RenderWindow &window) { //Set game view window.setView(m_camera.getGameView()); //Render the map m_mapRenderer.render(window); //Draw script notification m_scriptManager.render(window); //Player m_player.render(window); //Set gui view window.setView(m_camera.getDefaultView()); //Draw different screens if (m_gameState != GameState::RUNNING) { sf::RectangleShape overlay(sf::Vector2f(800, 450)); overlay.setFillColor(sf::Color(0, 0, 0, 180)); window.draw(overlay); m_gui.render(window); } } void Game::receiveMessage(const Message &msg) { //Loading the map if (msg.ID == std::hash<std::string>()("start game")) { //Set the name of the level m_levelName = *msg.getValue<std::string>(0); //Check if the Level is a tutorial if (m_levelName == "Tutorial2") { m_active = false; m_music.stop(); changeActiveState("menu"); Message msg(std::hash<std::string>()("Tutorial2")); m_messageBus.sendMessage(msg); } //Set the gametype if (*msg.getValue<std::string>(1) == "official arcade") { m_gameType = GameType::OFFICIAL_ARCADE; } //Load the level loadLevel(); } //Set the volume of the music else if (msg.ID == std::hash<std::string>()("sound settings")) { m_music.setVolume(*msg.getValue<float>(1)); } //Handling focus if lost = pause else if (msg.ID == std::hash<std::string>()("lost focus")) { //Pause the game if it is running.. //In Start, Finish, Crash screen it's not needed to pause the game... if (m_gameState == GameState::RUNNING) { m_gameState = GameState::PAUSED; m_gui.setActiveLayer(3); } } //Starting the game else if (msg.ID == std::hash<std::string>()("event") && m_active) { sf::Event event = *msg.getValue<sf::Event>(0); //Give the event to gui m_gui.handleEvent(event); //Check for respawn etc. if (event.type == sf::Event::KeyReleased) { if (event.key.code == sf::Keyboard::Return) { if (m_gameState == GameState::STOPPED) { m_gameState = GameState::RUNNING; resetToStart(); } else if (m_gameState == GameState::CRASHED) { m_gameState = GameState::RUNNING; resetToLastCheckpoint(); } else if (m_gameState == GameState::FINISHED) { if (m_gui.getSelectedElement()->getID() == "next") { //To inform the settings... unlock new/save progress + start next level sendInformationLevelFinished(true); } else if (m_gui.getSelectedElement()->getID() == "replay") { resetToStart(); m_gameState = GameState::STOPPED; m_gui.setActiveLayer(0); //To inform the settings... unlock new/save progress sendInformationLevelFinished(false); } else if (m_gui.getSelectedElement()->getID() == "back") { changeActiveState("menu"); m_music.stop(); m_active = false; //To inform the settings... unlock new/save progress sendInformationLevelFinished(false); } } else if (m_gameState == GameState::PAUSED) { if (m_gui.getSelectedElement()->getID() == "resume") { m_gameState = GameState::RUNNING; } else if (m_gui.getSelectedElement()->getID() == "back") { changeActiveState("menu"); m_music.stop(); m_active = false; } } } else if (event.key.code == sf::Keyboard::BackSpace) { if (m_gameState == GameState::CRASHED) { m_gameState = GameState::RUNNING; resetToStart(); } } else if (event.key.code == sf::Keyboard::Escape) { //What happens when pressing ESC depends on the current gamestate //Stopped or Crashed = back to menu if (m_gameState == GameState::STOPPED || m_gameState == GameState::CRASHED) { changeActiveState("menu"); m_music.stop(); m_active = false; } //Running = pause the game else if (m_gameState == GameState::RUNNING) { m_gameState = GameState::PAUSED; m_gui.setActiveLayer(3); } //Finish screen do nothing... } } } } ////////// PRIVATE FUNCS //////////// void Game::initMusic() { if (m_gameType == GameType::OFFICIAL_ARCADE) { int levelnumber; std::size_t pos = m_levelName.find_last_of('l'); std::string strlvlnumber = m_levelName.substr(pos + 1); std::stringstream sstr(strlvlnumber); sstr >> levelnumber; static int openMusic = -1; // 0 = level 1-5 // 2 = level 6-10 // 3 = level 11-15 if (levelnumber < 6) { if (openMusic != 0) m_music.openFromFile("data/music/Galaxy - New Electro House Techno by MafiaFLairBeatz.ogg"); openMusic = 0; } else if (levelnumber < 11) { if (openMusic != 1) m_music.openFromFile("data/music/MachinimaSound.com_-_After_Dark.ogg"); openMusic = 1; } } } void Game::loadLevel() { //Reset all members first m_gameState = GameState::STOPPED; m_mapRenderer = MapRenderer(); m_collisionSystem = CollisionSystem(); m_player = Player(); m_camera = Camera(); m_scriptManager.deleteScripts(); //Setup gamestate m_gameState = GameState::STOPPED; m_gui.setActiveLayer(0); //Setup the path for the level modules std::string path; if (m_gameType == GameType::OFFICIAL_ARCADE || m_gameType == GameType::OFFICIAL_TIMECHALLENGE) { path = "data/levels/official/" + m_levelName + ".cfg"; } else { path = "data/levels/custom/" + m_levelName + ".cfg"; } //Load all modules //Load the optical part of the map m_mapRenderer.load(path); //Load the collision map (Walls and Finish) m_collisionSystem.loadMap(path); //Load player information (speed, gravity, spawn) m_player.loadInformation(path); //Call player update with 0 frametime to prevent a instant death. m_player.upate(sf::Time()); //Update Camera position m_camera.update(m_player.getPosition()); //Load all the scripts m_scriptManager.load(path); //Open the right Music initMusic(); } void Game::resetToLastCheckpoint() { auto ptr = m_scriptManager.getLastCheckPoint(); if (ptr) { //Triggered checkpoint found -> reset to it m_player = ptr->savedPlayer; m_camera = ptr->savedCamera; //Reset scripts except checkpoint = parameter(false) m_scriptManager.resetScriptStates(false); } else { //No checkpoint triggered -> reset to start resetToStart(); } } void Game::resetToStart() { //Reset player m_player.resetToStartSettings(); //Reset Camera m_camera = Camera(); //Reset scripts m_scriptManager.resetScriptStates();; } void Game::sendInformationLevelFinished(bool startNextLevel) { Message msg; msg.ID = std::hash<std::string>()("level complete"); msg.push_back(m_levelName); msg.push_back(startNextLevel); m_messageBus.sendMessage(msg); } } //GLOBAL FUNCTION void initGui(aw::GuiController &gui) { //Stopped Layer //How to start the game gui.addLayer(); //The gui needs at least one selectable object for each layer ->placeholder gui.addButton(0, "placeholder", sf::Vector2f(-100, -100), ""); //////////////////////////////////////////////////////////////// gui.addButton(0, "msg", sf::Vector2f(227, 135), "Enter: Start the Game"); gui.getElement(0, 1)->setCharacterSize(30); gui.getElement(0, 1)->setSelectable(false); gui.addButton(0, "msg2", sf::Vector2f(275, 250), "Escape: Return to menu"); gui.getElement(0, 2)->setCharacterSize(20); gui.getElement(0, 2)->setSelectable(false); gui.setActiveLayer(0); //Layer after crashing into a wall gui.addLayer(); //The gui needs at least one selectable object for each layer ->placeholder gui.addButton(1, "placeholder", sf::Vector2f(-100, -100), ""); //////////////////////////////////////////////////////////////// gui.addButton(1, "msg", sf::Vector2f(75, 135), "Enter: Start the Game from checkpoint"); gui.getElement(1, 1)->setCharacterSize(30); gui.getElement(1, 1)->setSelectable(false); gui.getElement(1, 1)->setSelected(false); gui.addButton(1, "msg2", sf::Vector2f(150, 250), "Back space: Start the game from Start"); gui.getElement(1, 2)->setCharacterSize(20); gui.getElement(1, 2)->setSelectable(false); //Layer finish official_Arcade gui.addLayer(); gui.addButton(2, "next", sf::Vector2f(250, 180), "Start next level"); gui.addButton(2, "replay", sf::Vector2f(250, 210), "Replay this level"); gui.addButton(2, "back", sf::Vector2f(250, 240), "Return to menu"); gui.addLabel(2, "headline", sf::Vector2f(40, 80), "Great you have completed this level!"); gui.getElement(2, 3)->setCharacterSize(35); gui.addLabel(2, "question", sf::Vector2f(80, 180), "What to do: "); //Pause Layer gui.addLayer(); gui.addButton(3, "resume", sf::Vector2f(250, 200), "Continue"); gui.addButton(3, "back", sf::Vector2f(250, 250), "Back to menu"); gui.addLabel(3, "", sf::Vector2f(250, 100), "Game is paused"); }<commit_msg>Fixed the layout of the pause menu<commit_after>#include "game.hpp" #include <fstream> #include <sstream> #include <SFML/Graphics/RenderWindow.hpp> #include <SFML/Window/Event.hpp> #include "../../messageBus/messageBus.hpp" //Global Function void initGui(aw::GuiController &gui); namespace aw { Game::Game(StateMachine &statemachine, MessageBus &messageBus): m_active(false), State(statemachine), m_messageBus(messageBus), m_gameState(GameState::STOPPED) { m_messageBus.addReceiver(this); m_gui.loadFont("data/fonts/visitor1.ttf"); initGui(m_gui); //Global Function } void Game::update(const sf::Time &frameTime) { m_active = true; if (m_music.getStatus() == sf::Music::Stopped) { m_music.play(); } if (m_gameState == GameState::RUNNING) { //check for collision or finish auto result = m_collisionSystem.checkCollision(m_player); if (result == CollisionType::WALL) { m_gameState = GameState::CRASHED; m_gui.setActiveLayer(1); return; } else if (result == CollisionType::FINISH) { m_gameState = GameState::FINISHED; m_gui.setActiveLayer(2); return; } //Check for Scriptactions m_scriptManager.update(m_player, m_camera); //Update the position later, so the user see the crash //Update player position m_player.upate(frameTime); //update the camera position m_camera.update(m_player.getPosition()); } } void Game::render(sf::RenderWindow &window) { //Set game view window.setView(m_camera.getGameView()); //Render the map m_mapRenderer.render(window); //Draw script notification m_scriptManager.render(window); //Player m_player.render(window); //Set gui view window.setView(m_camera.getDefaultView()); //Draw different screens if (m_gameState != GameState::RUNNING) { sf::RectangleShape overlay(sf::Vector2f(800, 450)); overlay.setFillColor(sf::Color(0, 0, 0, 180)); window.draw(overlay); m_gui.render(window); } } void Game::receiveMessage(const Message &msg) { //Loading the map if (msg.ID == std::hash<std::string>()("start game")) { //Set the name of the level m_levelName = *msg.getValue<std::string>(0); //Check if the Level is a tutorial if (m_levelName == "Tutorial2") { m_active = false; m_music.stop(); changeActiveState("menu"); Message msg(std::hash<std::string>()("Tutorial2")); m_messageBus.sendMessage(msg); } //Set the gametype if (*msg.getValue<std::string>(1) == "official arcade") { m_gameType = GameType::OFFICIAL_ARCADE; } //Load the level loadLevel(); } //Set the volume of the music else if (msg.ID == std::hash<std::string>()("sound settings")) { m_music.setVolume(*msg.getValue<float>(1)); } //Handling focus if lost = pause else if (msg.ID == std::hash<std::string>()("lost focus")) { //Pause the game if it is running.. //In Start, Finish, Crash screen it's not needed to pause the game... if (m_gameState == GameState::RUNNING) { m_gameState = GameState::PAUSED; m_gui.setActiveLayer(3); } } //Starting the game else if (msg.ID == std::hash<std::string>()("event") && m_active) { sf::Event event = *msg.getValue<sf::Event>(0); //Give the event to gui m_gui.handleEvent(event); //Check for respawn etc. if (event.type == sf::Event::KeyReleased) { if (event.key.code == sf::Keyboard::Return) { if (m_gameState == GameState::STOPPED) { m_gameState = GameState::RUNNING; resetToStart(); } else if (m_gameState == GameState::CRASHED) { m_gameState = GameState::RUNNING; resetToLastCheckpoint(); } else if (m_gameState == GameState::FINISHED) { if (m_gui.getSelectedElement()->getID() == "next") { //To inform the settings... unlock new/save progress + start next level sendInformationLevelFinished(true); } else if (m_gui.getSelectedElement()->getID() == "replay") { resetToStart(); m_gameState = GameState::STOPPED; m_gui.setActiveLayer(0); //To inform the settings... unlock new/save progress sendInformationLevelFinished(false); } else if (m_gui.getSelectedElement()->getID() == "back") { changeActiveState("menu"); m_music.stop(); m_active = false; //To inform the settings... unlock new/save progress sendInformationLevelFinished(false); } } else if (m_gameState == GameState::PAUSED) { if (m_gui.getSelectedElement()->getID() == "resume") { m_gameState = GameState::RUNNING; } else if (m_gui.getSelectedElement()->getID() == "back") { changeActiveState("menu"); m_music.stop(); m_active = false; } } } else if (event.key.code == sf::Keyboard::BackSpace) { if (m_gameState == GameState::CRASHED) { m_gameState = GameState::RUNNING; resetToStart(); } } else if (event.key.code == sf::Keyboard::Escape) { //What happens when pressing ESC depends on the current gamestate //Stopped or Crashed = back to menu if (m_gameState == GameState::STOPPED || m_gameState == GameState::CRASHED) { changeActiveState("menu"); m_music.stop(); m_active = false; } //Running = pause the game else if (m_gameState == GameState::RUNNING) { m_gameState = GameState::PAUSED; m_gui.setActiveLayer(3); } //Finish screen do nothing... } } } } ////////// PRIVATE FUNCS //////////// void Game::initMusic() { if (m_gameType == GameType::OFFICIAL_ARCADE) { int levelnumber; std::size_t pos = m_levelName.find_last_of('l'); std::string strlvlnumber = m_levelName.substr(pos + 1); std::stringstream sstr(strlvlnumber); sstr >> levelnumber; static int openMusic = -1; // 0 = level 1-5 // 2 = level 6-10 // 3 = level 11-15 if (levelnumber < 6) { if (openMusic != 0) m_music.openFromFile("data/music/Galaxy - New Electro House Techno by MafiaFLairBeatz.ogg"); openMusic = 0; } else if (levelnumber < 11) { if (openMusic != 1) m_music.openFromFile("data/music/MachinimaSound.com_-_After_Dark.ogg"); openMusic = 1; } } } void Game::loadLevel() { //Reset all members first m_gameState = GameState::STOPPED; m_mapRenderer = MapRenderer(); m_collisionSystem = CollisionSystem(); m_player = Player(); m_camera = Camera(); m_scriptManager.deleteScripts(); //Setup gamestate m_gameState = GameState::STOPPED; m_gui.setActiveLayer(0); //Setup the path for the level modules std::string path; if (m_gameType == GameType::OFFICIAL_ARCADE || m_gameType == GameType::OFFICIAL_TIMECHALLENGE) { path = "data/levels/official/" + m_levelName + ".cfg"; } else { path = "data/levels/custom/" + m_levelName + ".cfg"; } //Load all modules //Load the optical part of the map m_mapRenderer.load(path); //Load the collision map (Walls and Finish) m_collisionSystem.loadMap(path); //Load player information (speed, gravity, spawn) m_player.loadInformation(path); //Call player update with 0 frametime to prevent a instant death. m_player.upate(sf::Time()); //Update Camera position m_camera.update(m_player.getPosition()); //Load all the scripts m_scriptManager.load(path); //Open the right Music initMusic(); } void Game::resetToLastCheckpoint() { auto ptr = m_scriptManager.getLastCheckPoint(); if (ptr) { //Triggered checkpoint found -> reset to it m_player = ptr->savedPlayer; m_camera = ptr->savedCamera; //Reset scripts except checkpoint = parameter(false) m_scriptManager.resetScriptStates(false); } else { //No checkpoint triggered -> reset to start resetToStart(); } } void Game::resetToStart() { //Reset player m_player.resetToStartSettings(); //Reset Camera m_camera = Camera(); //Reset scripts m_scriptManager.resetScriptStates();; } void Game::sendInformationLevelFinished(bool startNextLevel) { Message msg; msg.ID = std::hash<std::string>()("level complete"); msg.push_back(m_levelName); msg.push_back(startNextLevel); m_messageBus.sendMessage(msg); } } //GLOBAL FUNCTION void initGui(aw::GuiController &gui) { //Stopped Layer //How to start the game gui.addLayer(); //The gui needs at least one selectable object for each layer ->placeholder gui.addButton(0, "placeholder", sf::Vector2f(-100, -100), ""); //////////////////////////////////////////////////////////////// gui.addButton(0, "msg", sf::Vector2f(227, 135), "Enter: Start the Game"); gui.getElement(0, 1)->setCharacterSize(30); gui.getElement(0, 1)->setSelectable(false); gui.addButton(0, "msg2", sf::Vector2f(275, 250), "Escape: Return to menu"); gui.getElement(0, 2)->setCharacterSize(20); gui.getElement(0, 2)->setSelectable(false); gui.setActiveLayer(0); //Layer after crashing into a wall gui.addLayer(); //The gui needs at least one selectable object for each layer ->placeholder gui.addButton(1, "placeholder", sf::Vector2f(-100, -100), ""); //////////////////////////////////////////////////////////////// gui.addButton(1, "msg", sf::Vector2f(75, 135), "Enter: Start the Game from checkpoint"); gui.getElement(1, 1)->setCharacterSize(30); gui.getElement(1, 1)->setSelectable(false); gui.getElement(1, 1)->setSelected(false); gui.addButton(1, "msg2", sf::Vector2f(150, 250), "Back space: Start the game from Start"); gui.getElement(1, 2)->setCharacterSize(20); gui.getElement(1, 2)->setSelectable(false); //Layer finish official_Arcade gui.addLayer(); gui.addButton(2, "next", sf::Vector2f(250, 180), "Start next level"); gui.addButton(2, "replay", sf::Vector2f(250, 210), "Replay this level"); gui.addButton(2, "back", sf::Vector2f(250, 240), "Return to menu"); gui.addLabel(2, "headline", sf::Vector2f(40, 80), "Great you have completed this level!"); gui.getElement(2, 3)->setCharacterSize(35); gui.addLabel(2, "question", sf::Vector2f(80, 180), "What to do: "); //Pause Layer gui.addLayer(); gui.addButton(3, "resume", sf::Vector2f(250, 200), "Continue"); gui.addButton(3, "back", sf::Vector2f(250, 250), "Back to menu"); gui.addLabel(3, "", sf::Vector2f(250, 100), "Game is paused"); gui.getElement(3, 2)->setCharacterSize(35); }<|endoftext|>
<commit_before>/* * Copyright (c) 2016 Alex Spataru <[email protected]> * * This file is part of qMDNS, which is released under the MIT license. * For more information, please read the LICENSE file in the root directory * of this project. */ #include "Console.h" #include <QTimer> #include <QDebug> #include <QTextStream> #include <QCoreApplication> #include <qMDNS.h> #include <iostream> Console::Console() { enableUserInput(); connect (qMDNS::getInstance(), &qMDNS::hostFound, this, &Console::onDeviceDiscovered); } /** * Queries for user input and reacts to the user input */ void Console::run() { if (m_enabled) { std::cout << "\r> "; QTextStream in (stdin); QString input = in.readLine(); if (input == "name" || input == "n") showHostName(); else if (input == "set" || input == "s") promptSetHost(); else if (input == "lookup" || input == "l") promptLookup(); else if (input == "quit" || input == "q") exit (EXIT_SUCCESS); else showHelp(); } QTimer::singleShot (50, Qt::PreciseTimer, this, SLOT (run())); } /** * Shows the available commands to the user */ void Console::showHelp() { qDebug() << "Available commands are: \n" << " h help show this menu \n" << " n name display your host name \n" << " s set change your mDNS host name \n" << " l lookup lookup for a given host \n" << " q quit exit this application"; } /** * Displays the local computer's host name to the user */ void Console::showHostName() { QString name = qMDNS::getInstance()->hostName(); if (name.isEmpty()) qDebug() << "You have not set a host name yet, " "type \"set\" to set your host name."; else qDebug() << "Your host name is" << name.toStdString().c_str(); } /** * Asks the user to input a mDNS/DNS address for the * qMDNS library to lookup */ void Console::promptLookup() { std::cout << "Host to lookup: "; QTextStream input (stdin); QString host = input.readLine(); if (!host.isEmpty()) lookup (host); else { qDebug() << "Invalid user input"; promptLookup(); } disableUserInput(); } /** * Asks the user to input the host name to use to identify * the local computer in the mDNS network group */ void Console::promptSetHost() { std::cout << "Set host name: "; QTextStream input (stdin); QString host = input.readLine(); if (!host.isEmpty()) setHostName (host); else { qDebug() << "Invalid user input"; promptSetHost(); return; } } /** * Instructs the qMDNS to lookup for the given host \a name */ void Console::lookup (QString name) { disableUserInput(); qMDNS::getInstance()->lookup (name); } /** * Instructs the qMDNS to change the local computer's host \a name */ void Console::setHostName (QString name) { qMDNS::getInstance()->setHostName (name); } void Console::onDeviceDiscovered (const QHostInfo& info) { qDebug() << ""; qDebug() << info.hostName().toStdString().c_str() << "has the following IPs:"; foreach (QHostAddress address, info.addresses()) qDebug() << " -" << address.toString().toStdString().c_str(); qDebug() << ""; enableUserInput(); } /** * Allows the user to input different commands */ void Console::enableUserInput() { m_enabled = true; } /** * Disallows the user to input different commands for a short period * of time (5 seconds). */ void Console::disableUserInput() { if (m_enabled) { m_enabled = false; QTimer::singleShot (5000, Qt::PreciseTimer, this, SLOT (enableUserInput())); } } <commit_msg>Fix qMDNS example<commit_after>/* * Copyright (c) 2016 Alex Spataru <[email protected]> * * This file is part of qMDNS, which is released under the MIT license. * For more information, please read the LICENSE file in the root directory * of this project. */ #include "Console.h" #include <QTimer> #include <QDebug> #include <QTextStream> #include <QCoreApplication> #include <qMDNS.h> #include <iostream> Console::Console() { enableUserInput(); connect (qMDNS::getInstance(), &qMDNS::hostFound, this, &Console::onDeviceDiscovered); } /** * Queries for user input and reacts to the user input */ void Console::run() { if (m_enabled) { std::cout << "\r> "; QTextStream in (stdin); QString input = in.readLine(); if (input == "name" || input == "n") showHostName(); else if (input == "set" || input == "s") promptSetHost(); else if (input == "lookup" || input == "l") promptLookup(); else if (input == "quit" || input == "q") { m_enabled = false; qApp->quit(); } else showHelp(); } QTimer::singleShot (50, Qt::PreciseTimer, this, SLOT (run())); } /** * Shows the available commands to the user */ void Console::showHelp() { qDebug() << "Available commands are: \n" << " h help show this menu \n" << " n name display your host name \n" << " s set change your mDNS host name \n" << " l lookup lookup for a given host \n" << " q quit exit this application"; } /** * Displays the local computer's host name to the user */ void Console::showHostName() { QString name = qMDNS::getInstance()->hostName(); if (name.isEmpty()) qDebug() << "You have not set a host name yet, " "type \"set\" to set your host name."; else qDebug() << "Your host name is" << name.toStdString().c_str(); } /** * Asks the user to input a mDNS/DNS address for the * qMDNS library to lookup */ void Console::promptLookup() { std::cout << "Host to lookup: "; QTextStream input (stdin); QString host = input.readLine(); if (!host.isEmpty()) lookup (host); else { qDebug() << "Invalid user input"; promptLookup(); } disableUserInput(); } /** * Asks the user to input the host name to use to identify * the local computer in the mDNS network group */ void Console::promptSetHost() { std::cout << "Set host name: "; QTextStream input (stdin); QString host = input.readLine(); if (!host.isEmpty()) setHostName (host); else { qDebug() << "Invalid user input"; promptSetHost(); return; } } /** * Instructs the qMDNS to lookup for the given host \a name */ void Console::lookup (QString name) { disableUserInput(); qMDNS::getInstance()->lookup (name); } /** * Instructs the qMDNS to change the local computer's host \a name */ void Console::setHostName (QString name) { qMDNS::getInstance()->setHostName (name); } void Console::onDeviceDiscovered (const QHostInfo& info) { qDebug() << ""; qDebug() << info.hostName().toStdString().c_str() << "has the following IPs:"; foreach (QHostAddress address, info.addresses()) qDebug() << " -" << address.toString().toStdString().c_str(); qDebug() << ""; enableUserInput(); } /** * Allows the user to input different commands */ void Console::enableUserInput() { m_enabled = true; } /** * Disallows the user to input different commands for a short period * of time (5 seconds). */ void Console::disableUserInput() { if (m_enabled) { m_enabled = false; QTimer::singleShot (5000, Qt::PreciseTimer, this, SLOT (enableUserInput())); } } <|endoftext|>
<commit_before>#include "async_web_server_cpp/http_server.hpp" #include "async_web_server_cpp/http_reply.hpp" namespace async_web_server_cpp { HttpServer::HttpServer(const std::string &address, const std::string &port, HttpServerRequestHandler request_handler, std::size_t thread_pool_size) : acceptor_(io_service_), thread_pool_size_(thread_pool_size), request_handler_(request_handler) { boost::asio::ip::tcp::resolver resolver(io_service_); boost::asio::ip::tcp::resolver::query query(address, port); boost::asio::ip::tcp::endpoint endpoint = *resolver.resolve(query); acceptor_.open(endpoint.protocol()); acceptor_.set_option(boost::asio::ip::tcp::acceptor::reuse_address(true)); acceptor_.bind(endpoint); acceptor_.listen(); } void HttpServer::run() { start_accept(); for (std::size_t i = 0; i < thread_pool_size_; ++i) { boost::shared_ptr<boost::thread> thread(new boost::thread( boost::bind(&boost::asio::io_service::run, &io_service_))); threads_.push_back(thread); } } void HttpServer::start_accept() { new_connection_.reset(new HttpConnection(io_service_, request_handler_)); acceptor_.async_accept(new_connection_->socket(), boost::bind(&HttpServer::handle_accept, this, boost::asio::placeholders::error)); } void HttpServer::handle_accept(const boost::system::error_code &e) { if (!e) { new_connection_->start(); } start_accept(); } void HttpServer::stop() { acceptor_.cancel(); acceptor_.close(); io_service_.stop(); // Wait for all threads in the pool to exit. for (std::size_t i = 0; i < threads_.size(); ++i) threads_[i]->join(); } } <commit_msg>Allow for a server to be created even if the system has no non-local IP<commit_after>#include "async_web_server_cpp/http_server.hpp" #include "async_web_server_cpp/http_reply.hpp" namespace async_web_server_cpp { HttpServer::HttpServer(const std::string &address, const std::string &port, HttpServerRequestHandler request_handler, std::size_t thread_pool_size) : acceptor_(io_service_), thread_pool_size_(thread_pool_size), request_handler_(request_handler) { boost::asio::ip::tcp::resolver resolver(io_service_); boost::asio::ip::tcp::resolver::query query(address, port, boost::asio::ip::resolver_query_base::flags()); boost::asio::ip::tcp::endpoint endpoint = *resolver.resolve(query); acceptor_.open(endpoint.protocol()); acceptor_.set_option(boost::asio::ip::tcp::acceptor::reuse_address(true)); acceptor_.bind(endpoint); acceptor_.listen(); } void HttpServer::run() { start_accept(); for (std::size_t i = 0; i < thread_pool_size_; ++i) { boost::shared_ptr<boost::thread> thread(new boost::thread( boost::bind(&boost::asio::io_service::run, &io_service_))); threads_.push_back(thread); } } void HttpServer::start_accept() { new_connection_.reset(new HttpConnection(io_service_, request_handler_)); acceptor_.async_accept(new_connection_->socket(), boost::bind(&HttpServer::handle_accept, this, boost::asio::placeholders::error)); } void HttpServer::handle_accept(const boost::system::error_code &e) { if (!e) { new_connection_->start(); } start_accept(); } void HttpServer::stop() { acceptor_.cancel(); acceptor_.close(); io_service_.stop(); // Wait for all threads in the pool to exit. for (std::size_t i = 0; i < threads_.size(); ++i) threads_[i]->join(); } } <|endoftext|>
<commit_before>#ifndef INCLUDEGUARD_palgo_static_kdtree_hpp #define INCLUDEGUARD_palgo_static_kdtree_hpp /** @file * @brief A test of specifying the paritioners statically using the template arguments. * * Still in alpha. */ #include <array> #include <vector> // TODO - Remove this include once fully tested #include <iostream> // // Unnamed namespace for things only used in this file // namespace { /** @brief Info struct to get the type of the containers elements. * * Required because cl::sycl::accessor doesn't have a value_type. This is the default for * normal STL containers, the SYCL accessor special case will be in a specialisation. */ template<class T_container> struct ContainerTypeInfo { typedef typename T_container::value_type value_type; }; // If ComputeCpp is being used, add template specialisations #ifdef RUNTIME_INCLUDE_SYCL_ACCESSOR_H_ // This is the include guard for SYCL/accessor.h /** @brief Template specialisation to retrieve the type of a SYCL accessor's elements. */ template<class T_dataType,int dimensions,cl::sycl::access::mode accessMode,cl::sycl::access::target target> struct ContainerTypeInfo<cl::sycl::accessor<T_dataType,dimensions,accessMode,target> > { typedef T_dataType value_type; }; #endif } // end of the unnamed namespace namespace palgo { template<typename T_data, float (*... V_partitioners)(const T_data&)> class test_tree { public: template<typename T_iterator> test_tree( T_iterator iBegin, T_iterator iEnd ) { for( ; iBegin!=iEnd; ++iBegin ) items_.emplace_back( *iBegin ); } std::vector<float> testMethod() { std::vector<float> returnValue; for( size_t index=0; index<items_.size(); ++index ) { returnValue.push_back( partitioners_[index%partitioners_.size()](items_[index]) ); } return returnValue; } private: std::vector<T_data> items_; static const std::array<float (*)(const T_data&),sizeof...(V_partitioners)> partitioners_; // std::tuple<T_partitioners...> partitioners_; }; template<typename T_data, float (*... V_partitioners)(const T_data&)> const std::array<float (*)(const T_data&),sizeof...(V_partitioners)> test_tree<T_data,V_partitioners...>::partitioners_={V_partitioners...}; //template<typename T_data, float (*... Vs_function)(const T_data&)> struct FunctionList {}; // //template<typename T_data, float (*V_function)(const T_data&), float (*... Vs_function)(const T_data&)> //struct FunctionList : FunctionList<T_data,Vs_function> //{ // FunctionList( float (*V_function)(const T_data&), float (*... Vs_function)(const T_data&) ) // : FunctionList<T_data,Vs_function>(Vs_function), tail(V_function) // { // } // float (*V_function)(const T_data&) tail; //}; template<typename T_data, typename T_sort, float (*... V_functions)(const T_data&)> class test_tree2 { public: template<typename T_iterator> test_tree2( T_iterator iBegin, T_iterator iEnd ) { for( ; iBegin!=iEnd; ++iBegin ) items_.emplace_back( *iBegin ); } bool testMethod() { return true; } private: std::vector<T_data> items_; static const std::array<float (*)(const T_data&),sizeof...(V_functions)> partitioners_; }; template<typename T_data, typename T_sort, float (*... V_functions)(const T_data&)> const std::array<float (*)(const T_data&),sizeof...(V_functions)> test_tree2<T_data,T_sort,V_functions...>::partitioners_={V_functions...}; template<typename... T_functions> struct FunctionList { // intentionally empty base class }; template<typename T,typename... Ts> struct FunctionList<T,Ts...> : public FunctionList<Ts...> { typedef T func; }; //------------------------------------------- template <size_t,class T, class... Ts> struct TypeHolder; template <class T, class... Ts> struct TypeHolder<0, FunctionList<T, Ts...> > { typedef T type; }; template <size_t k, class T, class... Ts> struct TypeHolder<k, FunctionList<T, Ts...> > { typedef typename TypeHolder<k - 1, FunctionList<Ts...>>::type type; }; //------------------------------------------- template <size_t,class T, class... Ts> struct ListCycle; template <class T, class... Ts> struct ListCycle<0, FunctionList<T, Ts...> > { typedef T type; static constexpr size_t next=1; static constexpr size_t previous=sizeof...(Ts); }; template <class T> struct ListCycle<0, FunctionList<T> > // Special case of a single element list { typedef T type; static constexpr size_t next=0; static constexpr size_t previous=0; }; template <size_t k, class T, class... Ts> struct ListCycle<k, FunctionList<T, Ts...> > { typedef typename TypeHolder<k - 1, FunctionList<Ts...>>::type type; static constexpr size_t next=k+1; static constexpr size_t previous=k-1; }; template <class T, class... Ts> struct ListCycle<sizeof...(Ts), FunctionList<T, Ts...> > { typedef typename TypeHolder<sizeof...(Ts)-1, FunctionList<Ts...>>::type type; static constexpr size_t next=0; static constexpr size_t previous=sizeof...(Ts)-1; }; //------------------------------------------- /** @brief Helper template that can statically cycle through a list of types. * @author Mark Grimes * @date 18/Oct/2015 */ template <size_t k,class T> struct CyclicList { typedef typename ListCycle<k%3,T>::type type; }; /** @brief A kd tree where the partitioning functor is calculated statically. * * SYCL does not allow function pointers, so the partitioning functor for a given * level of the tree has to be known at compile time. * * @author Mark Grimes * @date 18/Oct/2015 */ template<class T_datastore,class T_functionList> class static_kdtree { public: class Iterator { public: typedef typename ContainerTypeInfo<T_datastore>::value_type value_type; public: Iterator( size_t index, const T_datastore& store ) : index_(index), pStore_(&store) {} bool operator==( const Iterator& otherIterator ) { return index_==otherIterator.index_; } bool operator!=( const Iterator& otherIterator ) { return !(*this==otherIterator); } value_type operator*() { return (*pStore_)[index_]; } const value_type* operator->() const { return &((*pStore_)[index_]); } private: size_t index_; const T_datastore* pStore_; }; public: typedef typename ContainerTypeInfo<T_datastore>::value_type value_type; // Can't use T_datastore::value_type because sycl::accessor doesn't have it typedef Iterator const_iterator; public: static_kdtree( T_datastore data, bool presorted=false ) : data_(data) { if( presorted ) return; // If the data is already in the correct order, no need to do anything else // SYCL doesn't allow exceptions, but while I'm testing in host code I'll put this in for now. throw std::logic_error( "Construction of static_kdtrees where the input is not already sorted has not been implemented yet" ); } Iterator nearest_neighbour( const value_type& query ) const { return Iterator(0,data_); } protected: T_datastore data_; }; } #endif <commit_msg>Change iterator to work on subtree range rather than single index<commit_after>#ifndef INCLUDEGUARD_palgo_static_kdtree_hpp #define INCLUDEGUARD_palgo_static_kdtree_hpp /** @file * @brief A test of specifying the paritioners statically using the template arguments. * * Still in alpha. */ #include <array> #include <vector> // TODO - Remove this include once fully tested #include <iostream> // // Unnamed namespace for things only used in this file // namespace { /** @brief Function to return the number of elements in a container. * * Required because cl::sycl::accessor doesn't have a "size" method; it has a "get_count" * method instead ("get_size" is get_count*sizeof(T)). This is the default for normal STL * containers, the SYCL accessor special case will be in a specialisation. */ template<class T> inline size_t dataSize( const T& container ) { return container.size(); } /** @brief Info struct to get the type of the containers elements. * * Required because cl::sycl::accessor doesn't have a value_type. This is the default for * normal STL containers, the SYCL accessor special case will be in a specialisation. */ template<class T_container> struct ContainerTypeInfo { typedef typename T_container::value_type value_type; }; // If ComputeCpp is being used, add template specialisations #ifdef RUNTIME_INCLUDE_SYCL_ACCESSOR_H_ // This is the include guard for SYCL/accessor.h template<class T_dataType,int dimensions,cl::sycl::access::mode accessMode,cl::sycl::access::target target> inline size_t dataSize( const cl::sycl::accessor<T_dataType,dimensions,accessMode,target>& container ) { return container.get_count(); } /** @brief Template specialisation to retrieve the type of a SYCL accessor's elements. */ template<class T_dataType,int dimensions,cl::sycl::access::mode accessMode,cl::sycl::access::target target> struct ContainerTypeInfo<cl::sycl::accessor<T_dataType,dimensions,accessMode,target> > { typedef T_dataType value_type; }; #endif } // end of the unnamed namespace namespace palgo { template<typename T_data, float (*... V_partitioners)(const T_data&)> class test_tree { public: template<typename T_iterator> test_tree( T_iterator iBegin, T_iterator iEnd ) { for( ; iBegin!=iEnd; ++iBegin ) items_.emplace_back( *iBegin ); } std::vector<float> testMethod() { std::vector<float> returnValue; for( size_t index=0; index<items_.size(); ++index ) { returnValue.push_back( partitioners_[index%partitioners_.size()](items_[index]) ); } return returnValue; } private: std::vector<T_data> items_; static const std::array<float (*)(const T_data&),sizeof...(V_partitioners)> partitioners_; // std::tuple<T_partitioners...> partitioners_; }; template<typename T_data, float (*... V_partitioners)(const T_data&)> const std::array<float (*)(const T_data&),sizeof...(V_partitioners)> test_tree<T_data,V_partitioners...>::partitioners_={V_partitioners...}; //template<typename T_data, float (*... Vs_function)(const T_data&)> struct FunctionList {}; // //template<typename T_data, float (*V_function)(const T_data&), float (*... Vs_function)(const T_data&)> //struct FunctionList : FunctionList<T_data,Vs_function> //{ // FunctionList( float (*V_function)(const T_data&), float (*... Vs_function)(const T_data&) ) // : FunctionList<T_data,Vs_function>(Vs_function), tail(V_function) // { // } // float (*V_function)(const T_data&) tail; //}; template<typename T_data, typename T_sort, float (*... V_functions)(const T_data&)> class test_tree2 { public: template<typename T_iterator> test_tree2( T_iterator iBegin, T_iterator iEnd ) { for( ; iBegin!=iEnd; ++iBegin ) items_.emplace_back( *iBegin ); } bool testMethod() { return true; } private: std::vector<T_data> items_; static const std::array<float (*)(const T_data&),sizeof...(V_functions)> partitioners_; }; template<typename T_data, typename T_sort, float (*... V_functions)(const T_data&)> const std::array<float (*)(const T_data&),sizeof...(V_functions)> test_tree2<T_data,T_sort,V_functions...>::partitioners_={V_functions...}; template<typename... T_functions> struct FunctionList { // intentionally empty base class }; template<typename T,typename... Ts> struct FunctionList<T,Ts...> : public FunctionList<Ts...> { typedef T func; }; //------------------------------------------- template <size_t,class T, class... Ts> struct TypeHolder; template <class T, class... Ts> struct TypeHolder<0, FunctionList<T, Ts...> > { typedef T type; }; template <size_t k, class T, class... Ts> struct TypeHolder<k, FunctionList<T, Ts...> > { typedef typename TypeHolder<k - 1, FunctionList<Ts...>>::type type; }; //------------------------------------------- template <size_t,class T, class... Ts> struct ListCycle; template <class T, class... Ts> struct ListCycle<0, FunctionList<T, Ts...> > { typedef T type; static constexpr size_t next=1; static constexpr size_t previous=sizeof...(Ts); }; template <class T> struct ListCycle<0, FunctionList<T> > // Special case of a single element list { typedef T type; static constexpr size_t next=0; static constexpr size_t previous=0; }; template <size_t k, class T, class... Ts> struct ListCycle<k, FunctionList<T, Ts...> > { typedef typename TypeHolder<k - 1, FunctionList<Ts...>>::type type; static constexpr size_t next=k+1; static constexpr size_t previous=k-1; }; template <class T, class... Ts> struct ListCycle<sizeof...(Ts), FunctionList<T, Ts...> > { typedef typename TypeHolder<sizeof...(Ts)-1, FunctionList<Ts...>>::type type; static constexpr size_t next=0; static constexpr size_t previous=sizeof...(Ts)-1; }; //------------------------------------------- /** @brief Helper template that can statically cycle through a list of types. * @author Mark Grimes * @date 18/Oct/2015 */ template <size_t k,class T> struct CyclicList { typedef typename ListCycle<k%3,T>::type type; }; /** @brief A kd tree where the partitioning functor is calculated statically. * * SYCL does not allow function pointers, so the partitioning functor for a given * level of the tree has to be known at compile time. * * @author Mark Grimes * @date 18/Oct/2015 */ template<class T_datastore,class T_functionList> class static_kdtree { public: class Iterator { public: typedef typename ContainerTypeInfo<T_datastore>::value_type value_type; public: Iterator( size_t leftLimit, size_t rightLimit, const T_datastore& store ) : subTreeFarLeft_(leftLimit), subTreeFarRight_(rightLimit), pStore_(&store) {} bool operator==( const Iterator& otherIterator ) { return subTreeFarLeft_==otherIterator.subTreeFarLeft_ && subTreeFarRight_==otherIterator.subTreeFarRight_; } bool operator!=( const Iterator& otherIterator ) { return !(*this==otherIterator); } value_type operator*() { return (*pStore_)[currentIndex()]; } const value_type* operator->() const { return &((*pStore_)[currentIndex()]); } Iterator& goto_parent() { // Pretty poor algorithm, but I just want to get something working. I'll look at // optimisations later. Start with a root Iterator and traverse down until the step // before the current state, then copy that position. // TODO - optimise with a decent algorithm size_t current=currentIndex(); Iterator stepBefore( 0, pStore_->size(), *pStore_ ); // start with an iterator to the root node while( stepBefore.currentIndex()!=current ) { subTreeFarLeft_=stepBefore.subTreeFarLeft_; subTreeFarRight_=stepBefore.subTreeFarRight_; if( stepBefore.currentIndex()<current ) stepBefore.goto_right_child(); else stepBefore.goto_left_child(); } return *this; } Iterator& goto_left_child() { subTreeFarRight_=currentIndex(); return *this; } Iterator& goto_right_child() { subTreeFarLeft_=currentIndex()+1; return *this; } bool has_parent() const { if( subTreeFarLeft_==0 && subTreeFarRight_==pStore_->size() ) return false; else return true; } bool has_left_child() const { return currentIndex()!=subTreeFarLeft_; } bool has_right_child() const { return currentIndex()+1!=subTreeFarRight_; } private: size_t subTreeFarLeft_,subTreeFarRight_; inline size_t currentIndex() const { return (subTreeFarLeft_+subTreeFarRight_)/2; } const T_datastore* pStore_; }; public: typedef typename ContainerTypeInfo<T_datastore>::value_type value_type; // Can't use T_datastore::value_type because sycl::accessor doesn't have it typedef Iterator const_iterator; public: static_kdtree( T_datastore data, bool presorted=false ) : data_(data), size_( ::dataSize(data_) ) { if( presorted ) return; // If the data is already in the correct order, no need to do anything else // SYCL doesn't allow exceptions, but while I'm testing in host code I'll put this in for now. throw std::logic_error( "Construction of static_kdtrees where the input is not already sorted has not been implemented yet" ); } Iterator root() const { return Iterator( 0, size_, data_ ); }//{ return Iterator( 0, ::dataSize(data_), data_ ); } Iterator end() const { return Iterator( size_, size_, data_ ); } Iterator nearest_neighbour( const value_type& query ) const { return end(); } protected: T_datastore data_; size_t size_; // Need to store this because ComputeCpp currently segfaults if accessor size is queried in the kernel. ToDo - remove this once ComputeCpp is fixed. }; } #endif <|endoftext|>
<commit_before>#include <set> #include <vector> #include <map> #include <cmath> #include "util.hpp" #include "tatum_error.hpp" #include "TimingGraph.hpp" #include "TimingConstraints.hpp" using tatum::TimingGraph; using tatum::TimingConstraints; using tatum::NodeId; using tatum::EdgeId; using tatum::NodeType; template<typename Range> size_t num_valid(Range range) { size_t count = 0; for(auto val : range) { if(val) ++count; } return count; } template<typename Range> typename Range::iterator ith_valid(Range range, size_t i) { size_t j = 0; for(auto iter = range.begin(); iter != range.end(); ++iter) { if(*iter && ++j == i) return iter; } throw tatum::Error("No valid ith value"); } void rebuild_timing_graph(TimingGraph& tg, TimingConstraints& tc, const VprFfInfo& ff_info, std::vector<float>& edge_delays, VprArrReqTimes& arr_req_times) { TimingConstraints new_tc; //Rebuild the graph to elminate redundant nodes (e.g. IPIN/OPINs in front of SOURCES/SINKS) std::map<NodeId,NodeId> arr_req_remap; for(NodeId node : tg.nodes()) { if(tg.node_type(node) == NodeType::SOURCE) { for(EdgeId out_edge : tg.node_out_edges(node)) { NodeId sink_node = tg.edge_sink_node(out_edge); TATUM_ASSERT(tg.node_type(sink_node) == NodeType::OPIN); if(tg.node_in_edges(node).size() == 0) { //Primary Input source node NodeId opin_src_node = node; NodeId opin_node = sink_node; float constraint = edge_delays[size_t(out_edge)]; std::map<NodeId,float> new_edges; for(EdgeId opin_out_edge : tg.node_out_edges(opin_node)) { NodeId opin_sink_node = tg.edge_sink_node(opin_out_edge); float opin_out_delay = edge_delays[size_t(opin_out_edge)]; new_edges[opin_sink_node] = opin_out_delay; } //Remove the node (and it's connected edges) tg.remove_node(opin_node); //Add the new edges for(auto kv : new_edges) { NodeId opin_sink_node = kv.first; float delay = kv.second; EdgeId new_edge = tg.add_edge(opin_src_node, opin_sink_node); //Set the edge delay edge_delays.resize(size_t(new_edge) + 1); //Make space edge_delays[size_t(new_edge)] = delay; } //Set the constraint tc.set_input_constraint(opin_src_node, tc.node_clock_domain(opin_src_node), constraint); std::cout << "Remove PI OPIN " << sink_node << " Input Constraint on " << node << " " << constraint << "\n"; } else { //FF source TATUM_ASSERT_MSG(tg.node_in_edges(node).size() == 1, "Single clock input"); NodeId opin_src_node = node; NodeId opin_node = sink_node; auto opin_out_edges = tg.node_out_edges(opin_node); TATUM_ASSERT(num_valid(opin_out_edges) == 1); EdgeId opin_out_edge = *ith_valid(opin_out_edges, 1); NodeId opin_sink_node = tg.edge_sink_node(opin_out_edge); float tcq = edge_delays[size_t(out_edge)]; float opin_out_delay = edge_delays[size_t(opin_out_edge)]; EdgeId source_in_edge = *tg.node_in_edges(node).begin(); NodeId clock_sink = tg.edge_src_node(source_in_edge); //Remove the node (and it's edges) tg.remove_node(opin_node); //Add the new edge EdgeId new_edge = tg.add_edge(opin_src_node, opin_sink_node); //Set the edge delay edge_delays.resize(size_t(new_edge) + 1); //Make space edge_delays[size_t(new_edge)] = opin_out_delay; //Move the SOURCE->OPIN delay (tcq) to the CLOCK->SOURCE edge edge_delays[size_t(source_in_edge)] = tcq; //Since we've moved around the tcq delay we need to note which original node it should be compared with //(i.e. when we verify correctness we need to check the golden result for the OPIN's data arr/req at the //SOURCE node arr_req_remap[opin_src_node] = opin_node; std::cout << "Remove FF OPIN " << sink_node << " Tcq " << tcq << " " << clock_sink << " -> " << node << "\n"; } } } else if(tg.node_type(node) == NodeType::SINK) { if (tg.node_out_edges(node).size() > 0) { //Pass, a clock sink } else { TATUM_ASSERT(tg.node_out_edges(node).size() == 0); if(tg.node_in_edges(node).size() == 1) { //Primary Output sink node EdgeId in_edge = *tg.node_in_edges(node).begin(); NodeId ipin_node = tg.edge_src_node(in_edge); TATUM_ASSERT(tg.node_type(ipin_node) == NodeType::IPIN); float output_constraint = edge_delays[size_t(in_edge)]; NodeId ipin_sink_node = node; TATUM_ASSERT(tg.node_in_edges(ipin_node).size() == 1); EdgeId ipin_in_edge = *tg.node_in_edges(ipin_node).begin(); NodeId ipin_src_node = tg.edge_src_node(ipin_in_edge); float ipin_in_delay = edge_delays[size_t(ipin_in_edge)]; std::cout << "Remove PO IPIN " << ipin_node << " Output Constraint on " << node << " " << output_constraint << "\n"; //Remove the pin (also removes it's connected edges) tg.remove_node(ipin_node); //Add in the replacement edge EdgeId new_edge_id = tg.add_edge(ipin_src_node, ipin_sink_node); //Specify the delay edge_delays.resize(size_t(new_edge_id) + 1); //Make space edge_delays[size_t(new_edge_id)] = ipin_in_delay; //Specify the constraint tc.set_output_constraint(node, tc.node_clock_domain(node), output_constraint); } else { //FF sink TATUM_ASSERT_MSG(tg.node_in_edges(node).size() == 2, "FF Sinks have at most two edges (data and clock)"); NodeId ff_ipin_sink = node; NodeId ff_clock; EdgeId ff_clock_edge; NodeId ff_ipin; float tsu = NAN; for(EdgeId in_edge : tg.node_in_edges(ff_ipin_sink)) { if(!in_edge) continue; NodeId src_node = tg.edge_src_node(in_edge); if(tg.node_type(src_node) == NodeType::SINK) { ff_clock = src_node; ff_clock_edge = in_edge; } else { TATUM_ASSERT(tg.node_type(src_node) == NodeType::IPIN); ff_ipin = src_node; tsu = edge_delays[size_t(in_edge)]; } } TATUM_ASSERT(ff_clock); TATUM_ASSERT(ff_ipin); TATUM_ASSERT(!isnan(tsu)); auto ff_ipin_in_edges = tg.node_in_edges(ff_ipin); TATUM_ASSERT(num_valid(ff_ipin_in_edges) == 1); EdgeId ff_ipin_in_edge = *ith_valid(ff_ipin_in_edges, 1); NodeId ff_ipin_src = tg.edge_src_node(ff_ipin_in_edge); float ff_ipin_in_delay = edge_delays[size_t(ff_ipin_in_edge)]; //Remove the pin (and it's edges) tg.remove_node(ff_ipin); //Add the replacement edge EdgeId new_edge_id = tg.add_edge(ff_ipin_src, ff_ipin_sink); //Specify the new edge's delay edge_delays.resize(size_t(new_edge_id) + 1); //Make space edge_delays[size_t(new_edge_id)] = ff_ipin_in_delay; //Move the IPIN->SINK delay (tsu) to the CLOCK->SINK edge //Note that since we are 'moving' the tsu to the other side of the //arrival/required time inequality, we must make it negative! edge_delays[size_t(ff_clock_edge)] = -tsu; //Since we've moved around the tcq delay we need to note which original node it should be compared with //(i.e. when we verify correctness we need to check the golden result for the OPIN's data arr/req at the //SOURCE node arr_req_remap[ff_ipin_sink] = ff_ipin; std::cout << "Remove FF IPIN " << ff_ipin << " Tsu " << tsu << " " << ff_clock << " -> " << node << "\n"; } } } } auto id_maps = tg.compress(); tg.levelize(); //Remap the delays std::vector<float> new_edge_delays(edge_delays.size(), NAN); //Ensure there is space for(size_t i = 0; i < edge_delays.size(); ++i) { EdgeId new_id = id_maps.edge_id_map[EdgeId(i)]; if(new_id) { std::cout << "Edge delay " << i << " " << edge_delays[i] << " new id " << new_id << "\n"; new_edge_delays[size_t(new_id)] = edge_delays[i]; } } edge_delays = new_edge_delays; //Update //Remap the arr/req times VprArrReqTimes new_arr_req_times; new_arr_req_times.set_num_nodes(tg.nodes().size()); for(auto src_domain : arr_req_times.domains()) { //For every clock domain pair for(int i = 0; i < arr_req_times.get_num_nodes(); i++) { NodeId old_id = NodeId(i); if(arr_req_remap.count(old_id)) { //Remap the arr/req to compare with old_id = arr_req_remap[old_id]; } //Now remap the the new node ids NodeId new_id = id_maps.node_id_map[NodeId(i)]; if(new_id) { new_arr_req_times.add_arr_time(src_domain, new_id, arr_req_times.get_arr_time(src_domain, old_id)); new_arr_req_times.add_req_time(src_domain, new_id, arr_req_times.get_req_time(src_domain, old_id)); } } } arr_req_times = new_arr_req_times; //Update //Remap the constraints tc.remap_nodes(id_maps.node_id_map); } void add_ff_clock_to_source_sink_edges(TimingGraph& tg, const VprFfInfo& ff_info, std::vector<float>& edge_delays) { //We represent the dependancies between the clock and data paths //As edges in the graph from FF_CLOCK pins to FF_SOURCES (launch path) //and FF_SINKS (capture path) // //We use the information about the logical blocks associated with each //timing node to infer these edges. That is, we look for FF_SINKs and FF_SOURCEs //that share the same logical block as an FF_CLOCK. // //TODO: Currently this just works for VPR's timing graph where only one FF_CLOCK exists // per basic logic block. This will need to be generalized. //Build a map from logical block id to the tnodes we care about std::cout << "FF_CLOCK: " << ff_info.logical_block_FF_clocks.size() << "\n"; std::cout << "FF_SOURCE: " << ff_info.logical_block_FF_clocks.size() << "\n"; std::cout << "FF_SINK: " << ff_info.logical_block_FF_clocks.size() << "\n"; size_t num_edges_added = 0; //Loop through each FF_CLOCK and add edges to FF_SINKs and FF_SOURCEs for(const auto clock_kv : ff_info.logical_block_FF_clocks) { BlockId logical_block_id = clock_kv.first; NodeId ff_clock_node_id = clock_kv.second; //Check for FF_SOURCEs associated with this FF_CLOCK pin auto src_range = ff_info.logical_block_FF_sources.equal_range(logical_block_id); //Go through each assoicated source and add an edge to it for(auto kv : tatum::util::make_range(src_range.first, src_range.second)) { NodeId ff_src_node_id = kv.second; tg.add_edge(ff_clock_node_id, ff_src_node_id); //Mark edge as having zero delay edge_delays.push_back(0.); ++num_edges_added; } //Check for FF_SINKs associated with this FF_CLOCK pin auto sink_range = ff_info.logical_block_FF_sinks.equal_range(logical_block_id); //Go through each assoicated source and add an edge to it for(auto kv : tatum::util::make_range(sink_range.first, sink_range.second)) { NodeId ff_sink_node_id = kv.second; tg.add_edge(ff_clock_node_id, ff_sink_node_id); //Mark edge as having zero delay edge_delays.push_back(0.); ++num_edges_added; } } std::cout << "FF related Edges added: " << num_edges_added << "\n"; } float relative_error(float A, float B) { if (A == B) { return 0.; } if (fabs(B) > fabs(A)) { return fabs((A - B) / B); } else { return fabs((A - B) / A); } } <commit_msg>Add support for multi-output FF OPINs<commit_after>#include <set> #include <vector> #include <map> #include <cmath> #include "util.hpp" #include "tatum_error.hpp" #include "TimingGraph.hpp" #include "TimingConstraints.hpp" using tatum::TimingGraph; using tatum::TimingConstraints; using tatum::NodeId; using tatum::EdgeId; using tatum::NodeType; template<typename Range> size_t num_valid(Range range) { size_t count = 0; for(auto val : range) { if(val) ++count; } return count; } template<typename Range> typename Range::iterator ith_valid(Range range, size_t i) { size_t j = 0; for(auto iter = range.begin(); iter != range.end(); ++iter) { if(*iter && ++j == i) return iter; } throw tatum::Error("No valid ith value"); } void rebuild_timing_graph(TimingGraph& tg, TimingConstraints& tc, const VprFfInfo& ff_info, std::vector<float>& edge_delays, VprArrReqTimes& arr_req_times) { TimingConstraints new_tc; //Rebuild the graph to elminate redundant nodes (e.g. IPIN/OPINs in front of SOURCES/SINKS) std::map<NodeId,NodeId> arr_req_remap; for(NodeId node : tg.nodes()) { if(tg.node_type(node) == NodeType::SOURCE) { for(EdgeId out_edge : tg.node_out_edges(node)) { NodeId sink_node = tg.edge_sink_node(out_edge); TATUM_ASSERT(tg.node_type(sink_node) == NodeType::OPIN); if(tg.node_in_edges(node).size() == 0) { //Primary Input source node NodeId opin_src_node = node; NodeId opin_node = sink_node; float constraint = edge_delays[size_t(out_edge)]; std::map<NodeId,float> new_edges; for(EdgeId opin_out_edge : tg.node_out_edges(opin_node)) { NodeId opin_sink_node = tg.edge_sink_node(opin_out_edge); float opin_out_delay = edge_delays[size_t(opin_out_edge)]; new_edges[opin_sink_node] = opin_out_delay; } //Remove the node (and it's connected edges) tg.remove_node(opin_node); //Add the new edges for(auto kv : new_edges) { NodeId opin_sink_node = kv.first; float delay = kv.second; EdgeId new_edge = tg.add_edge(opin_src_node, opin_sink_node); //Set the edge delay edge_delays.resize(size_t(new_edge) + 1); //Make space edge_delays[size_t(new_edge)] = delay; } //Set the constraint tc.set_input_constraint(opin_src_node, tc.node_clock_domain(opin_src_node), constraint); std::cout << "Remove PI OPIN " << sink_node << " Input Constraint on " << node << " " << constraint << "\n"; } else { //FF source TATUM_ASSERT_MSG(tg.node_in_edges(node).size() == 1, "Single clock input"); NodeId opin_src_node = node; NodeId opin_node = sink_node; float tcq = edge_delays[size_t(out_edge)]; EdgeId source_in_edge = *tg.node_in_edges(node).begin(); NodeId clock_sink = tg.edge_src_node(source_in_edge); std::map<NodeId,float> new_edges; for(EdgeId opin_out_edge : tg.node_out_edges(opin_node)) { NodeId opin_sink_node = tg.edge_sink_node(opin_out_edge); float opin_out_delay = edge_delays[size_t(opin_out_edge)]; new_edges[opin_sink_node] = opin_out_delay; } //Remove the node (and it's edges) tg.remove_node(opin_node); //Add the new edges for(auto kv : new_edges) { NodeId opin_sink_node = kv.first; float delay = kv.second; EdgeId new_edge = tg.add_edge(opin_src_node, opin_sink_node); //Set the edge delay edge_delays.resize(size_t(new_edge) + 1); //Make space edge_delays[size_t(new_edge)] = delay; } //Move the SOURCE->OPIN delay (tcq) to the CLOCK->SOURCE edge edge_delays[size_t(source_in_edge)] = tcq; //Since we've moved around the tcq delay we need to note which original node it should be compared with //(i.e. when we verify correctness we need to check the golden result for the OPIN's data arr/req at the //SOURCE node arr_req_remap[opin_src_node] = opin_node; std::cout << "Remove FF OPIN " << sink_node << " Tcq " << tcq << " " << clock_sink << " -> " << node << "\n"; } } } else if(tg.node_type(node) == NodeType::SINK) { if (tg.node_out_edges(node).size() > 0) { //Pass, a clock sink } else { TATUM_ASSERT(tg.node_out_edges(node).size() == 0); if(tg.node_in_edges(node).size() == 1) { //Primary Output sink node EdgeId in_edge = *tg.node_in_edges(node).begin(); NodeId ipin_node = tg.edge_src_node(in_edge); TATUM_ASSERT(tg.node_type(ipin_node) == NodeType::IPIN); float output_constraint = edge_delays[size_t(in_edge)]; NodeId ipin_sink_node = node; TATUM_ASSERT(tg.node_in_edges(ipin_node).size() == 1); EdgeId ipin_in_edge = *tg.node_in_edges(ipin_node).begin(); NodeId ipin_src_node = tg.edge_src_node(ipin_in_edge); float ipin_in_delay = edge_delays[size_t(ipin_in_edge)]; std::cout << "Remove PO IPIN " << ipin_node << " Output Constraint on " << node << " " << output_constraint << "\n"; //Remove the pin (also removes it's connected edges) tg.remove_node(ipin_node); //Add in the replacement edge EdgeId new_edge_id = tg.add_edge(ipin_src_node, ipin_sink_node); //Specify the delay edge_delays.resize(size_t(new_edge_id) + 1); //Make space edge_delays[size_t(new_edge_id)] = ipin_in_delay; //Specify the constraint tc.set_output_constraint(node, tc.node_clock_domain(node), output_constraint); } else { //FF sink TATUM_ASSERT_MSG(tg.node_in_edges(node).size() == 2, "FF Sinks have at most two edges (data and clock)"); NodeId ff_ipin_sink = node; NodeId ff_clock; EdgeId ff_clock_edge; NodeId ff_ipin; float tsu = NAN; for(EdgeId in_edge : tg.node_in_edges(ff_ipin_sink)) { if(!in_edge) continue; NodeId src_node = tg.edge_src_node(in_edge); if(tg.node_type(src_node) == NodeType::SINK) { ff_clock = src_node; ff_clock_edge = in_edge; } else { TATUM_ASSERT(tg.node_type(src_node) == NodeType::IPIN); ff_ipin = src_node; tsu = edge_delays[size_t(in_edge)]; } } TATUM_ASSERT(ff_clock); TATUM_ASSERT(ff_ipin); TATUM_ASSERT(!isnan(tsu)); auto ff_ipin_in_edges = tg.node_in_edges(ff_ipin); TATUM_ASSERT(num_valid(ff_ipin_in_edges) == 1); EdgeId ff_ipin_in_edge = *ith_valid(ff_ipin_in_edges, 1); NodeId ff_ipin_src = tg.edge_src_node(ff_ipin_in_edge); float ff_ipin_in_delay = edge_delays[size_t(ff_ipin_in_edge)]; //Remove the pin (and it's edges) tg.remove_node(ff_ipin); //Add the replacement edge EdgeId new_edge_id = tg.add_edge(ff_ipin_src, ff_ipin_sink); //Specify the new edge's delay edge_delays.resize(size_t(new_edge_id) + 1); //Make space edge_delays[size_t(new_edge_id)] = ff_ipin_in_delay; //Move the IPIN->SINK delay (tsu) to the CLOCK->SINK edge //Note that since we are 'moving' the tsu to the other side of the //arrival/required time inequality, we must make it negative! edge_delays[size_t(ff_clock_edge)] = -tsu; //Since we've moved around the tcq delay we need to note which original node it should be compared with //(i.e. when we verify correctness we need to check the golden result for the OPIN's data arr/req at the //SOURCE node arr_req_remap[ff_ipin_sink] = ff_ipin; std::cout << "Remove FF IPIN " << ff_ipin << " Tsu " << tsu << " " << ff_clock << " -> " << node << "\n"; } } } } auto id_maps = tg.compress(); tg.levelize(); //Remap the delays std::vector<float> new_edge_delays(edge_delays.size(), NAN); //Ensure there is space for(size_t i = 0; i < edge_delays.size(); ++i) { EdgeId new_id = id_maps.edge_id_map[EdgeId(i)]; if(new_id) { std::cout << "Edge delay " << i << " " << edge_delays[i] << " new id " << new_id << "\n"; new_edge_delays[size_t(new_id)] = edge_delays[i]; } } edge_delays = new_edge_delays; //Update //Remap the arr/req times VprArrReqTimes new_arr_req_times; new_arr_req_times.set_num_nodes(tg.nodes().size()); for(auto src_domain : arr_req_times.domains()) { //For every clock domain pair for(int i = 0; i < arr_req_times.get_num_nodes(); i++) { NodeId old_id = NodeId(i); if(arr_req_remap.count(old_id)) { //Remap the arr/req to compare with old_id = arr_req_remap[old_id]; } //Now remap the the new node ids NodeId new_id = id_maps.node_id_map[NodeId(i)]; if(new_id) { new_arr_req_times.add_arr_time(src_domain, new_id, arr_req_times.get_arr_time(src_domain, old_id)); new_arr_req_times.add_req_time(src_domain, new_id, arr_req_times.get_req_time(src_domain, old_id)); } } } arr_req_times = new_arr_req_times; //Update //Remap the constraints tc.remap_nodes(id_maps.node_id_map); } void add_ff_clock_to_source_sink_edges(TimingGraph& tg, const VprFfInfo& ff_info, std::vector<float>& edge_delays) { //We represent the dependancies between the clock and data paths //As edges in the graph from FF_CLOCK pins to FF_SOURCES (launch path) //and FF_SINKS (capture path) // //We use the information about the logical blocks associated with each //timing node to infer these edges. That is, we look for FF_SINKs and FF_SOURCEs //that share the same logical block as an FF_CLOCK. // //TODO: Currently this just works for VPR's timing graph where only one FF_CLOCK exists // per basic logic block. This will need to be generalized. //Build a map from logical block id to the tnodes we care about std::cout << "FF_CLOCK: " << ff_info.logical_block_FF_clocks.size() << "\n"; std::cout << "FF_SOURCE: " << ff_info.logical_block_FF_clocks.size() << "\n"; std::cout << "FF_SINK: " << ff_info.logical_block_FF_clocks.size() << "\n"; size_t num_edges_added = 0; //Loop through each FF_CLOCK and add edges to FF_SINKs and FF_SOURCEs for(const auto clock_kv : ff_info.logical_block_FF_clocks) { BlockId logical_block_id = clock_kv.first; NodeId ff_clock_node_id = clock_kv.second; //Check for FF_SOURCEs associated with this FF_CLOCK pin auto src_range = ff_info.logical_block_FF_sources.equal_range(logical_block_id); //Go through each assoicated source and add an edge to it for(auto kv : tatum::util::make_range(src_range.first, src_range.second)) { NodeId ff_src_node_id = kv.second; tg.add_edge(ff_clock_node_id, ff_src_node_id); //Mark edge as having zero delay edge_delays.push_back(0.); ++num_edges_added; } //Check for FF_SINKs associated with this FF_CLOCK pin auto sink_range = ff_info.logical_block_FF_sinks.equal_range(logical_block_id); //Go through each assoicated source and add an edge to it for(auto kv : tatum::util::make_range(sink_range.first, sink_range.second)) { NodeId ff_sink_node_id = kv.second; tg.add_edge(ff_clock_node_id, ff_sink_node_id); //Mark edge as having zero delay edge_delays.push_back(0.); ++num_edges_added; } } std::cout << "FF related Edges added: " << num_edges_added << "\n"; } float relative_error(float A, float B) { if (A == B) { return 0.; } if (fabs(B) > fabs(A)) { return fabs((A - B) / B); } else { return fabs((A - B) / A); } } <|endoftext|>
<commit_before>/* * http_server.cpp * * Created on: Oct 26, 2014 * Author: liao */ #include <stdio.h> #include <stdlib.h> #include <errno.h> #include <string.h> #include <sys/types.h> #include <netinet/in.h> #include <arpa/inet.h> #include <sys/socket.h> #include <sys/time.h> #include <sys/epoll.h> #include <sys/fcntl.h> #include <unistd.h> #include <sstream> #include "simple_log.h" #include "http_parser.h" #include "http_server.h" int HttpServer::start(int port, int backlog) { EpollSocket epoll_socket; epoll_socket.start_epoll(port, http_handler, backlog); return 0; } void HttpServer::add_mapping(std::string path, method_handler_ptr handler, HttpMethod method) { http_handler.add_mapping(path, handler, method); } void HttpEpollWatcher::add_mapping(std::string path, method_handler_ptr handler, HttpMethod method) { Resource resource = {method, handler}; resource_map[path] = resource; } int HttpEpollWatcher::handle_request(Request &req, Response &res) { std::string uri = req.get_request_uri(); if(this->resource_map.find(uri) == this->resource_map.end()) { // not found res.code_msg = STATUS_NOT_FOUND; res.body = STATUS_NOT_FOUND.msg; LOG_INFO("page not found which uri:%s", uri.c_str()); return 0; } Resource resource = this->resource_map[req.get_request_uri()]; // check method HttpMethod method = resource.method; if(method.code != ALL_METHOD.code && method.name != req.line.method) { res.code_msg = STATUS_METHOD_NOT_ALLOWED; res.set_head("Allow", method.name); res.body.clear(); LOG_INFO("not allow method, allowed:%s, request method:%s", method.name.c_str(), req.line.method.c_str()); return 0; } method_handler_ptr handle = resource.handler_ptr; if(handle != NULL) { handle(req, res); } LOG_DEBUG("handle response success which code:%d, msg:%s", res.code_msg.status_code, res.code_msg.msg.c_str()); return 0; } int HttpEpollWatcher::on_accept(EpollContext &epoll_context) { int conn_sock = epoll_context.fd; epoll_context.ptr = new HttpContext(conn_sock); return 0; } int HttpEpollWatcher::on_readable(EpollContext &epoll_context, char *read_buffer, int buffer_size, int read_size) { HttpContext *http_context = (HttpContext *) epoll_context.ptr; http_context->record_start_time(); if(read_size == buffer_size) { LOG_WARN("NOT VALID DATA! single line max size is %d", buffer_size); return -1; } int ret = http_context->req.parse_request(read_buffer, read_size); if(ret != 0) { LOG_WARN("parse_request error which ret:%d", ret); return -1; } this->handle_request(http_context->req, http_context->get_res()); return 0; } int HttpEpollWatcher::on_writeable(EpollContext &epoll_context) { int fd = epoll_context.fd; HttpContext *hc = (HttpContext *) epoll_context.ptr; Response &res = hc->get_res(); bool is_keepalive = (strcasecmp(hc->req.get_header("Connection").c_str(), "keep-alive") == 0); if (!res.is_writed) { res.gen_response(hc->req.line.http_version, is_keepalive); res.is_writed = true; } char buffer[SS_WRITE_BUFFER_SIZE]; bzero(buffer, SS_WRITE_BUFFER_SIZE); int read_size = 0; // 1. read some response bytes int ret = res.readsome(buffer, SS_WRITE_BUFFER_SIZE, read_size); // 2. write bytes to socket int nwrite = send(fd, buffer, read_size, 0); if(nwrite < 0) { perror("send fail!"); return WRITE_CONN_CLOSE; } // 3. when ont write all buffer, we will rollback write index if (nwrite < read_size) { res.rollback(read_size - nwrite); } LOG_DEBUG("send complete which write_num:%d, read_size:%d", nwrite, read_size); bool print_access_log = true; if (ret == 1) {/* not send over*/ print_access_log = false; LOG_DEBUG("has big response, we will send part first and send other part later ..."); return WRITE_CONN_CONTINUE; } if (print_access_log) { hc->print_access_log(); } if(is_keepalive && nwrite > 0) { hc->clear(); return WRITE_CONN_ALIVE; } return WRITE_CONN_CLOSE; } int HttpEpollWatcher::on_close(EpollContext &epoll_context) { if(epoll_context.ptr == NULL) { return 0; } HttpContext *hc = (HttpContext *) epoll_context.ptr; if(hc != NULL) { delete hc; hc = NULL; } return 0; } <commit_msg>read req only once<commit_after>/* * http_server.cpp * * Created on: Oct 26, 2014 * Author: liao */ #include <stdio.h> #include <stdlib.h> #include <errno.h> #include <string.h> #include <sys/types.h> #include <netinet/in.h> #include <arpa/inet.h> #include <sys/socket.h> #include <sys/time.h> #include <sys/epoll.h> #include <sys/fcntl.h> #include <unistd.h> #include <sstream> #include "simple_log.h" #include "http_parser.h" #include "http_server.h" int HttpServer::start(int port, int backlog) { EpollSocket epoll_socket; epoll_socket.start_epoll(port, http_handler, backlog); return 0; } void HttpServer::add_mapping(std::string path, method_handler_ptr handler, HttpMethod method) { http_handler.add_mapping(path, handler, method); } void HttpEpollWatcher::add_mapping(std::string path, method_handler_ptr handler, HttpMethod method) { Resource resource = {method, handler}; resource_map[path] = resource; } int HttpEpollWatcher::handle_request(Request &req, Response &res) { std::string uri = req.get_request_uri(); if(this->resource_map.find(uri) == this->resource_map.end()) { // not found res.code_msg = STATUS_NOT_FOUND; res.body = STATUS_NOT_FOUND.msg; LOG_INFO("page not found which uri:%s", uri.c_str()); return 0; } Resource resource = this->resource_map[req.get_request_uri()]; // check method HttpMethod method = resource.method; if(method.code != ALL_METHOD.code && method.name != req.line.method) { res.code_msg = STATUS_METHOD_NOT_ALLOWED; res.set_head("Allow", method.name); res.body.clear(); LOG_INFO("not allow method, allowed:%s, request method:%s", method.name.c_str(), req.line.method.c_str()); return 0; } method_handler_ptr handle = resource.handler_ptr; if(handle != NULL) { handle(req, res); } LOG_DEBUG("handle response success which code:%d, msg:%s", res.code_msg.status_code, res.code_msg.msg.c_str()); return 0; } int HttpEpollWatcher::on_accept(EpollContext &epoll_context) { int conn_sock = epoll_context.fd; epoll_context.ptr = new HttpContext(conn_sock); return 0; } int HttpEpollWatcher::on_readable(EpollContext &epoll_context, char *read_buffer, int buffer_size, int read_size) { HttpContext *http_context = (HttpContext *) epoll_context.ptr; http_context->record_start_time(); if(read_size == buffer_size) { LOG_WARN("NOT VALID DATA! single request max size is %d", buffer_size); return -1; } int ret = http_context->req.parse_request(read_buffer, read_size); if(ret != 0) { LOG_WARN("parse_request error which ret:%d", ret); return -1; } this->handle_request(http_context->req, http_context->get_res()); return 0; } int HttpEpollWatcher::on_writeable(EpollContext &epoll_context) { int fd = epoll_context.fd; HttpContext *hc = (HttpContext *) epoll_context.ptr; Response &res = hc->get_res(); bool is_keepalive = (strcasecmp(hc->req.get_header("Connection").c_str(), "keep-alive") == 0); if (!res.is_writed) { res.gen_response(hc->req.line.http_version, is_keepalive); res.is_writed = true; } char buffer[SS_WRITE_BUFFER_SIZE]; bzero(buffer, SS_WRITE_BUFFER_SIZE); int read_size = 0; // 1. read some response bytes int ret = res.readsome(buffer, SS_WRITE_BUFFER_SIZE, read_size); // 2. write bytes to socket int nwrite = send(fd, buffer, read_size, 0); if(nwrite < 0) { perror("send fail!"); return WRITE_CONN_CLOSE; } // 3. when ont write all buffer, we will rollback write index if (nwrite < read_size) { res.rollback(read_size - nwrite); } LOG_DEBUG("send complete which write_num:%d, read_size:%d", nwrite, read_size); bool print_access_log = true; if (ret == 1) {/* not send over*/ print_access_log = false; LOG_DEBUG("has big response, we will send part first and send other part later ..."); return WRITE_CONN_CONTINUE; } if (print_access_log) { hc->print_access_log(); } if(is_keepalive && nwrite > 0) { hc->clear(); return WRITE_CONN_ALIVE; } return WRITE_CONN_CLOSE; } int HttpEpollWatcher::on_close(EpollContext &epoll_context) { if(epoll_context.ptr == NULL) { return 0; } HttpContext *hc = (HttpContext *) epoll_context.ptr; if(hc != NULL) { delete hc; hc = NULL; } return 0; } <|endoftext|>
<commit_before>#include <gtest/gtest.h> #include <arrayfire.h> #include <af/dim4.hpp> #include <af/traits.hpp> #include <string> #include <vector> #include <iostream> #include <testHelpers.hpp> using std::string; using std::cout; using std::endl; using std::vector; using af::af_cfloat; using af::af_cdouble; template<typename T> class Transpose : public ::testing::Test { public: virtual void SetUp() { subMat2D.push_back({2,7,1}); subMat2D.push_back({2,7,1}); subMat3D.push_back({2,7,1}); subMat3D.push_back({2,7,1}); subMat3D.push_back(span); } vector<af_seq> subMat2D; vector<af_seq> subMat3D; }; // create a list of types to be tested typedef ::testing::Types<float, af_cfloat, double, af_cdouble, int, unsigned, char, unsigned char> TestTypes; // register the type list TYPED_TEST_CASE(Transpose, TestTypes); template<typename T> void trsTest(string pTestFile, bool isSubRef=false, const vector<af_seq> *seqv=nullptr) { af::dim4 dims(1); vector<T> in; vector<vector<T>> tests; ReadTests<int, T>(pTestFile,dims,in,tests); af_array outArray = 0; af_array inArray = 0; T *outData; ASSERT_EQ(AF_SUCCESS, af_create_array(&inArray, &in.front(), dims.ndims(), dims.get(), (af_dtype) af::dtype_traits<T>::af_type)); // check if the test is for indexed Array if (isSubRef) { af::dim4 newDims(dims[1]-4,dims[0]-4,dims[2],dims[3]); af_array subArray = 0; ASSERT_EQ(AF_SUCCESS, af_index(&subArray,inArray,seqv->size(),&seqv->front())); ASSERT_EQ(AF_SUCCESS, af_transpose(&outArray,subArray)); // destroy the temporary indexed Array ASSERT_EQ(AF_SUCCESS, af_destroy_array(subArray)); dim_type nElems; ASSERT_EQ(AF_SUCCESS, af_get_elements(&nElems,outArray)); outData = new T[nElems]; } else { ASSERT_EQ(AF_SUCCESS, af_transpose(&outArray,inArray)); outData = new T[dims.elements()]; } ASSERT_EQ(AF_SUCCESS, af_get_data_ptr((void*)outData, outArray)); for (int testIter=0; testIter<tests.size(); ++testIter) { vector<T> currGoldBar = tests[testIter]; size_t nElems = currGoldBar.size(); for (size_t elIter=0; elIter<nElems; ++elIter) { ASSERT_EQ(currGoldBar[elIter],outData[elIter])<< "at: " << elIter<< std::endl; } } // cleanup delete[] outData; ASSERT_EQ(AF_SUCCESS, af_destroy_array(inArray)); ASSERT_EQ(AF_SUCCESS, af_destroy_array(outArray)); } TYPED_TEST(Transpose,Vector) { trsTest<TypeParam>(string(TEST_DIR"/transpose/vector.test")); } TYPED_TEST(Transpose,VectorBatch) { trsTest<TypeParam>(string(TEST_DIR"/transpose/vector_batch.test")); } TYPED_TEST(Transpose,Square) { trsTest<TypeParam>(string(TEST_DIR"/transpose/square.test")); } TYPED_TEST(Transpose,SquareBatch) { trsTest<TypeParam>(string(TEST_DIR"/transpose/square_batch.test")); } TYPED_TEST(Transpose,Rectangle) { trsTest<TypeParam>(string(TEST_DIR"/transpose/rectangle.test")); } TYPED_TEST(Transpose,RectangleBatch) { trsTest<TypeParam>(string(TEST_DIR"/transpose/rectangle_batch.test")); } TYPED_TEST(Transpose,SubRef) { trsTest<TypeParam>(string(TEST_DIR"/transpose/offset.test"),true,&(this->subMat2D)); } TYPED_TEST(Transpose,SubRefBatch) { trsTest<TypeParam>(string(TEST_DIR"/transpose/offset_batch.test"),true,&(this->subMat3D)); } <commit_msg>Invalid arguments unit test for transpose<commit_after>#include <gtest/gtest.h> #include <arrayfire.h> #include <af/dim4.hpp> #include <af/traits.hpp> #include <string> #include <vector> #include <iostream> #include <testHelpers.hpp> using std::string; using std::cout; using std::endl; using std::vector; using af::af_cfloat; using af::af_cdouble; template<typename T> class Transpose : public ::testing::Test { public: virtual void SetUp() { subMat2D.push_back({2,7,1}); subMat2D.push_back({2,7,1}); subMat3D.push_back({2,7,1}); subMat3D.push_back({2,7,1}); subMat3D.push_back(span); } vector<af_seq> subMat2D; vector<af_seq> subMat3D; }; // create a list of types to be tested typedef ::testing::Types<float, af_cfloat, double, af_cdouble, int, unsigned, char, unsigned char> TestTypes; // register the type list TYPED_TEST_CASE(Transpose, TestTypes); template<typename T> void trsTest(string pTestFile, bool isSubRef=false, const vector<af_seq> *seqv=nullptr) { af::dim4 dims(1); vector<T> in; vector<vector<T>> tests; ReadTests<int, T>(pTestFile,dims,in,tests); af_array outArray = 0; af_array inArray = 0; T *outData; ASSERT_EQ(AF_SUCCESS, af_create_array(&inArray, &in.front(), dims.ndims(), dims.get(), (af_dtype) af::dtype_traits<T>::af_type)); // check if the test is for indexed Array if (isSubRef) { af::dim4 newDims(dims[1]-4,dims[0]-4,dims[2],dims[3]); af_array subArray = 0; ASSERT_EQ(AF_SUCCESS, af_index(&subArray,inArray,seqv->size(),&seqv->front())); ASSERT_EQ(AF_SUCCESS, af_transpose(&outArray,subArray)); // destroy the temporary indexed Array ASSERT_EQ(AF_SUCCESS, af_destroy_array(subArray)); dim_type nElems; ASSERT_EQ(AF_SUCCESS, af_get_elements(&nElems,outArray)); outData = new T[nElems]; } else { ASSERT_EQ(AF_SUCCESS, af_transpose(&outArray,inArray)); outData = new T[dims.elements()]; } ASSERT_EQ(AF_SUCCESS, af_get_data_ptr((void*)outData, outArray)); for (int testIter=0; testIter<tests.size(); ++testIter) { vector<T> currGoldBar = tests[testIter]; size_t nElems = currGoldBar.size(); for (size_t elIter=0; elIter<nElems; ++elIter) { ASSERT_EQ(currGoldBar[elIter],outData[elIter])<< "at: " << elIter<< std::endl; } } // cleanup delete[] outData; ASSERT_EQ(AF_SUCCESS, af_destroy_array(inArray)); ASSERT_EQ(AF_SUCCESS, af_destroy_array(outArray)); } TYPED_TEST(Transpose,Vector) { trsTest<TypeParam>(string(TEST_DIR"/transpose/vector.test")); } TYPED_TEST(Transpose,VectorBatch) { trsTest<TypeParam>(string(TEST_DIR"/transpose/vector_batch.test")); } TYPED_TEST(Transpose,Square) { trsTest<TypeParam>(string(TEST_DIR"/transpose/square.test")); } TYPED_TEST(Transpose,SquareBatch) { trsTest<TypeParam>(string(TEST_DIR"/transpose/square_batch.test")); } TYPED_TEST(Transpose,Rectangle) { trsTest<TypeParam>(string(TEST_DIR"/transpose/rectangle.test")); } TYPED_TEST(Transpose,RectangleBatch) { trsTest<TypeParam>(string(TEST_DIR"/transpose/rectangle_batch.test")); } TYPED_TEST(Transpose,SubRef) { trsTest<TypeParam>(string(TEST_DIR"/transpose/offset.test"),true,&(this->subMat2D)); } TYPED_TEST(Transpose,SubRefBatch) { trsTest<TypeParam>(string(TEST_DIR"/transpose/offset_batch.test"),true,&(this->subMat3D)); } TYPED_TEST(Transpose,InvalidArgs) { af::dim4 dims(1); vector<TypeParam> in; vector<vector<TypeParam>> tests; ReadTests<int, TypeParam>(string(TEST_DIR"/transpose/square.test"),dims,in,tests); af_array inArray = 0; af_array outArray = 0; // square test file is 100x100 originally // usee new dimensions for this argument // unit test af::dim4 newDims(5,5,2,2); ASSERT_EQ(AF_SUCCESS, af_create_array(&inArray, &in.front(), newDims.ndims(), newDims.get(), (af_dtype) af::dtype_traits<TypeParam>::af_type)); ASSERT_EQ(AF_ERR_ARG, af_transpose(&outArray,inArray)); } <|endoftext|>
<commit_before>/* * Copyright 2012-2013 BrewPi/Elco Jacobs. * Copyright 2013 Matthew McGowan. * * This file is part of BrewPi. * * BrewPi 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. * * BrewPi 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 BrewPi. If not, see <http://www.gnu.org/licenses/>. */ #include "temperatureFormats.h" #include "OneWireTempSensor.h" #include "OneWireAddress.h" #include "DallasTemperature.h" #include "OneWire.h" #include "Ticks.h" #include "Logger.h" OneWireTempSensor::~OneWireTempSensor() { delete sensor; }; /** * Initializes the temperature sensor. * This method is called when the sensor is first created and also any time the sensor reports it's disconnected. * If the result is TEMP_SENSOR_DISCONNECTED then subsequent calls to read() will also return TEMP_SENSOR_DISCONNECTED. * Clients should attempt to re-initialize the sensor by calling init() again. */ bool OneWireTempSensor::init() { // save address and pinNr for log messages char addressString[17]; printBytes(sensorAddress, 8, addressString); #if BREWPI_DEBUG uint8_t pinNr = oneWire->pinNr(); #endif bool success = false; if (sensor == NULL) { sensor = new DallasTemperature(oneWire); if (sensor == NULL) { logErrorString(ERROR_SRAM_SENSOR, addressString); } } logDebug("init onewire sensor"); // This quickly tests if the sensor is connected and initializes the reset detection if necessary. if (sensor){ // If this is the first conversion after power on, the device will return DEVICE_DISCONNECTED_RAW // Because HIGH_ALARM_TEMP will be copied from EEPROM int16_t temp = sensor->getTempRaw(sensorAddress); if(temp == DEVICE_DISCONNECTED_RAW){ // Device was just powered on and should be initialized if(sensor->initConnection(sensorAddress)){ requestConversion(); waitForConversion(); temp = sensor->getTempRaw(sensorAddress); } } DEBUG_ONLY(logInfoIntStringTemp(INFO_TEMP_SENSOR_INITIALIZED, pinNr, addressString, temp)); success = temp != DEVICE_DISCONNECTED_RAW; if(success){ requestConversion(); // piggyback request for a new conversion } } setConnected(success); logDebug("init onewire sensor complete %d", success); return success; } void OneWireTempSensor::requestConversion() { sensor->requestTemperaturesByAddress(sensorAddress); } void OneWireTempSensor::setConnected(bool connected) { if (this->connected == connected) return; // state is stays the same char addressString[17]; printBytes(sensorAddress, 8, addressString); this->connected = connected; if (connected) { logInfoIntString(INFO_TEMP_SENSOR_CONNECTED, this->oneWire->pinNr(), addressString); } else { logWarningIntString(WARNING_TEMP_SENSOR_DISCONNECTED, this->oneWire->pinNr(), addressString); } } temp_t OneWireTempSensor::read() const { if (!connected) return TEMP_SENSOR_DISCONNECTED; return cachedValue; } void OneWireTempSensor::update(){ cachedValue = readAndConstrainTemp(); if(cachedValue.isDisabledOrInvalid()){ // Try to reconnect once if (init()){ // successfully re-initialized cachedValue = readAndConstrainTemp(); } } requestConversion(); } temp_t OneWireTempSensor::readAndConstrainTemp() { int16_t tempRaw = sensor->getTempRaw(sensorAddress); if (tempRaw == DEVICE_DISCONNECTED_RAW) { setConnected(false); return temp_t::invalid(); } const uint8_t shift = temp_t::fractional_bit_count - ONEWIRE_TEMP_SENSOR_PRECISION; // difference in precision between DS18B20 format and temperature adt temp_t temp; temp.setRaw(tempRaw << shift); return temp + calibrationOffset; } <commit_msg>fix for temp sensor connected state not always being set to true after a successful read<commit_after>/* * Copyright 2012-2013 BrewPi/Elco Jacobs. * Copyright 2013 Matthew McGowan. * * This file is part of BrewPi. * * BrewPi 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. * * BrewPi 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 BrewPi. If not, see <http://www.gnu.org/licenses/>. */ #include "temperatureFormats.h" #include "OneWireTempSensor.h" #include "OneWireAddress.h" #include "DallasTemperature.h" #include "OneWire.h" #include "Ticks.h" #include "Logger.h" OneWireTempSensor::~OneWireTempSensor() { delete sensor; }; /** * Initializes the temperature sensor. * This method is called when the sensor is first created and also any time the sensor reports it's disconnected. * If the result is TEMP_SENSOR_DISCONNECTED then subsequent calls to read() will also return TEMP_SENSOR_DISCONNECTED. * Clients should attempt to re-initialize the sensor by calling init() again. */ bool OneWireTempSensor::init() { // save address and pinNr for log messages char addressString[17]; printBytes(sensorAddress, 8, addressString); #if BREWPI_DEBUG uint8_t pinNr = oneWire->pinNr(); #endif bool success = false; if (sensor == NULL) { sensor = new DallasTemperature(oneWire); if (sensor == NULL) { logErrorString(ERROR_SRAM_SENSOR, addressString); } } logDebug("init onewire sensor"); // This quickly tests if the sensor is connected and initializes the reset detection if necessary. if (sensor){ // If this is the first conversion after power on, the device will return DEVICE_DISCONNECTED_RAW // Because HIGH_ALARM_TEMP will be copied from EEPROM int16_t temp = sensor->getTempRaw(sensorAddress); if(temp == DEVICE_DISCONNECTED_RAW){ // Device was just powered on and should be initialized if(sensor->initConnection(sensorAddress)){ requestConversion(); waitForConversion(); temp = sensor->getTempRaw(sensorAddress); } } DEBUG_ONLY(logInfoIntStringTemp(INFO_TEMP_SENSOR_INITIALIZED, pinNr, addressString, temp)); success = temp != DEVICE_DISCONNECTED_RAW; if(success){ requestConversion(); // piggyback request for a new conversion } } setConnected(success); logDebug("init onewire sensor complete %d", success); return success; } void OneWireTempSensor::requestConversion() { sensor->requestTemperaturesByAddress(sensorAddress); } void OneWireTempSensor::setConnected(bool connected) { if (this->connected == connected) return; // state is stays the same char addressString[17]; printBytes(sensorAddress, 8, addressString); this->connected = connected; if (connected) { logInfoIntString(INFO_TEMP_SENSOR_CONNECTED, this->oneWire->pinNr(), addressString); } else { logWarningIntString(WARNING_TEMP_SENSOR_DISCONNECTED, this->oneWire->pinNr(), addressString); } } temp_t OneWireTempSensor::read() const { if (!connected) return TEMP_SENSOR_DISCONNECTED; return cachedValue; } void OneWireTempSensor::update(){ cachedValue = readAndConstrainTemp(); requestConversion(); } temp_t OneWireTempSensor::readAndConstrainTemp() { int16_t tempRaw; bool success; tempRaw = sensor->getTempRaw(sensorAddress); success = tempRaw != DEVICE_DISCONNECTED_RAW; if (!success){ // retry re-init once if(init()){ tempRaw = sensor->getTempRaw(sensorAddress); success = tempRaw != DEVICE_DISCONNECTED_RAW; } } setConnected(success); if(!success){ return temp_t::invalid(); } const uint8_t shift = temp_t::fractional_bit_count - ONEWIRE_TEMP_SENSOR_PRECISION; // difference in precision between DS18B20 format and temperature adt temp_t temp; temp.setRaw(tempRaw << shift); return temp + calibrationOffset; } <|endoftext|>
<commit_before><commit_msg>Clean up includes<commit_after><|endoftext|>
<commit_before>#ifndef PYTHONIC_TYPES_NUMPY_IEXPR_HPP #define PYTHONIC_TYPES_NUMPY_IEXPR_HPP #include "pythonic/types/nditerator.hpp" #include "pythonic/types/tuple.hpp" #include <numeric> namespace pythonic { namespace types { template<class Arg, class... S> struct numpy_gexpr; template<class Arg, class F> struct numpy_fexpr; /* Expression template for numpy expressions - indexing */ template<class T, size_t N> struct numpy_iexpr_helper; template<class Arg> struct numpy_iexpr { // wrapper around another numpy expression to skip first dimension using a given value. static constexpr size_t value = std::remove_reference<Arg>::type::value - 1; typedef typename std::remove_reference<Arg>::type::dtype dtype; typedef typename std::remove_reference<decltype(numpy_iexpr_helper<numpy_iexpr, value>::get(std::declval<numpy_iexpr>(), 0L))>::type value_type; typedef nditerator<numpy_iexpr> iterator; typedef const_nditerator<numpy_iexpr> const_iterator; Arg arg; dtype* buffer; array<long, value> shape; numpy_iexpr() {} numpy_iexpr(numpy_iexpr const &) = default; numpy_iexpr(numpy_iexpr&&) = default; template<class Argp> // not using the default one, to make it possible to accept reference and non reference version of Argp numpy_iexpr(numpy_iexpr<Argp> const & other) : arg(other.arg), buffer(other.buffer), shape(other.shape) { } void init_buffer(long index) { auto siter = shape.begin(); //accumulate the shape to jump to index position. Not done with std::accumulate //as we want to copy the shape at the same time. for(auto iter = arg.shape.begin() + 1, end = arg.shape.end(); iter != end; ++iter, ++siter) index *= *siter = *iter; buffer += index; } numpy_iexpr(Arg const & arg, long index) : arg(arg), buffer(arg.buffer) { init_buffer(index); } // force the move. Using universal reference here does not work (because of reference collapsing ?) numpy_iexpr(typename std::remove_reference<Arg>::type &&arg, long index) : arg(std::move(arg)), buffer(arg.buffer) { init_buffer(index); } template<class E> numpy_iexpr& operator=(E const& expr) { return utils::broadcast_copy(*this, expr, utils::int_<value - utils::dim_of<E>::value>()); } numpy_iexpr& operator=(numpy_iexpr const& expr) { return utils::broadcast_copy(*this, expr, utils::int_<value - utils::dim_of<numpy_iexpr>::value>()); } template<class E> numpy_iexpr& operator+=(E const& expr) { return (*this) = (*this) + expr; } numpy_iexpr& operator+=(numpy_iexpr const& expr) { return (*this) = (*this) + expr; } template<class E> numpy_iexpr& operator-=(E const& expr) { return (*this) = (*this) - expr; } numpy_iexpr& operator-=(numpy_iexpr const& expr) { return (*this) = (*this) - expr; } template<class E> numpy_iexpr& operator*=(E const& expr) { return (*this) = (*this) * expr; } numpy_iexpr& operator*=(numpy_iexpr const& expr) { return (*this) = (*this) * expr; } template<class E> numpy_iexpr& operator/=(E const& expr) { return (*this) = (*this) / expr; } numpy_iexpr& operator/=(numpy_iexpr const& expr) { return (*this) = (*this) / expr; } const_iterator begin() const { return const_iterator(*this, 0); } const_iterator end() const { return const_iterator(*this, shape[0]); } iterator begin() { return iterator(*this, 0); } iterator end() { return iterator(*this, shape[0]); } dtype const * fbegin() const { return buffer; } dtype const * fend() const { return buffer + size(); } dtype * fbegin() { return buffer; } dtype const * fend() { return buffer + size(); } /* There are three kind of indexing operator: fast(long), [long] and (long): * - fast does not perform automatic bound wrapping * - [] performs automatic bound wrapping, hen forwards to fast * - () is an alias to [] and directly forwards to [] * * For each indexing operator, we have three variant: &, const& and &&: * - & means the numpy_iexpr has been bound to a non-const value, as in ``b=a[i] ; print b[j]`` * in that case the return type if the dim of a is 2 is a reference, to allow ``b[j] = 1`` * - const & means the numpy_iexpr has been bound to a const value, as in ``np.copy(a[i])`` * in that case the return type if the dim of a is 2 is a value (or const ref) * - && means the numpy_iexpr is a r-value, which happens a lot, as in ``a[i][j]`` * in that case the return type if the dim of a is 2 is a reference. * It is a bit weird because we return a refrence from a rvalue, but the reference is bound to * the buffer of ``a`` that is not temp. */ auto fast(long i) const &-> decltype(numpy_iexpr_helper<numpy_iexpr, value>::get(*this, i)) { return numpy_iexpr_helper<numpy_iexpr, value>::get(*this, i); } auto fast(long i) &-> decltype(numpy_iexpr_helper<numpy_iexpr, value>::get(*this, i)) { return numpy_iexpr_helper<numpy_iexpr, value>::get(*this, i); } auto fast(long i) &&-> decltype(numpy_iexpr_helper<numpy_iexpr, value>::get(std::move(*this), i)) { return numpy_iexpr_helper<numpy_iexpr, value>::get(std::move(*this), i); } auto operator[](long i) const &-> decltype(this->fast(i)) { if(i<0) i += shape[0]; return fast(i); } auto operator[](long i) &-> decltype(this->fast(i)) { if(i<0) i += shape[0]; return fast(i); } auto operator[](long i) && -> decltype(std::move(*this).fast(i)) { if(i<0) i += shape[0]; return std::move(*this).fast(i); } auto operator()(long i) const &-> decltype((*this)[i]) { return (*this)[i]; } auto operator()(long i) &-> decltype((*this)[i]) { return (*this)[i]; } auto operator()(long i) &&-> decltype(std::move(*this)[i]) { return std::move(*this)[i]; } numpy_gexpr<numpy_iexpr, slice> operator()(slice const& s0) const { return numpy_gexpr<numpy_iexpr, slice>(*this, s0); } numpy_gexpr<numpy_iexpr, slice> operator[](slice const& s0) const { return numpy_gexpr<numpy_iexpr, slice>(*this, s0); } numpy_gexpr<numpy_iexpr, contiguous_slice> operator()(contiguous_slice const& s0) const { return numpy_gexpr<numpy_iexpr, contiguous_slice>(*this, s0); } numpy_gexpr<numpy_iexpr, contiguous_slice> operator[](contiguous_slice const& s0) const { return numpy_gexpr<numpy_iexpr, contiguous_slice>(*this, s0); } template<class ...S> numpy_gexpr<numpy_iexpr, slice, S...> operator()(slice const& s0, S const&... s) const { return numpy_gexpr<numpy_iexpr, slice, S...>(*this, s0, s...); } template<class ...S> numpy_gexpr<numpy_iexpr, contiguous_slice, S...> operator()(contiguous_slice const& s0, S const&... s) const { return numpy_gexpr<numpy_iexpr, contiguous_slice, S...>(*this, s0, s...); } template<class ...S> auto operator()(long s0, S const&... s) const -> decltype(std::declval<numpy_iexpr<numpy_iexpr>>()(s...)) { return (*this)[s0](s...); } template<class F> typename std::enable_if<is_numexpr_arg<F>::value, numpy_fexpr<numpy_iexpr, F>>::type operator[](F const& filter) const { return numpy_fexpr<numpy_iexpr, F>(*this, filter); } long size() const { return /*arg.size()*/ std::accumulate(shape.begin() + 1, shape.end(), *shape.begin(), std::multiplies<long>()); } }; // Indexing an numpy_iexpr that has a dimension greater than one yields a new numpy_iexpr template <class T, size_t N> struct numpy_iexpr_helper { static numpy_iexpr<T> get(T const& e, long i) { return numpy_iexpr<T>(e, i); } }; // Indexing an iexpr that has a dimension of one yields a qualified scalar. The qualifier is either: // - a reference if the numpy_iexpr is a ref itself, as in ``b = a[i] ; b[i] = 1`` // - a reference if the numpy_iexpr is a r-value, as in ``a[i][j] = 1`` // - a value if the numpy_iexpr is a const ref, as in ``b = a[i] ; c = b[i]`` template <class T> struct numpy_iexpr_helper<T, 1> { static typename T::dtype get(T const & e, long i) { return e.buffer[i]; } static typename T::dtype & get(T && e, long i) { return e.buffer[i]; } static typename T::dtype & get(T & e, long i) { return e.buffer[i]; } }; } template<class Arg> struct assignable<types::numpy_iexpr<Arg>> { typedef types::numpy_iexpr<typename assignable<Arg>::type> type; }; template<class Arg> struct lazy<types::numpy_iexpr<Arg>> { typedef types::numpy_iexpr<typename lazy<Arg>::type> type; }; template<class Arg> struct lazy<types::numpy_iexpr<Arg const &>> { typedef types::numpy_iexpr<typename lazy<Arg>::type const &> type; }; } /* type inference stuff {*/ #include "pythonic/types/combined.hpp" template<class E, class K> struct __combined<pythonic::types::numpy_iexpr<E>, K> { typedef pythonic::types::numpy_iexpr<E> type; }; #endif <commit_msg>loop unrolling of one of the core numpy_iexpr loop<commit_after>#ifndef PYTHONIC_TYPES_NUMPY_IEXPR_HPP #define PYTHONIC_TYPES_NUMPY_IEXPR_HPP #include "pythonic/types/nditerator.hpp" #include "pythonic/types/tuple.hpp" #include <numeric> namespace pythonic { namespace types { template<class Arg, class... S> struct numpy_gexpr; template<class Arg, class F> struct numpy_fexpr; /* Expression template for numpy expressions - indexing */ template<class T, size_t N> struct numpy_iexpr_helper; template<class Arg> struct numpy_iexpr { // wrapper around another numpy expression to skip first dimension using a given value. static constexpr size_t value = std::remove_reference<Arg>::type::value - 1; typedef typename std::remove_reference<Arg>::type::dtype dtype; typedef typename std::remove_reference<decltype(numpy_iexpr_helper<numpy_iexpr, value>::get(std::declval<numpy_iexpr>(), 0L))>::type value_type; typedef nditerator<numpy_iexpr> iterator; typedef const_nditerator<numpy_iexpr> const_iterator; Arg arg; dtype* buffer; array<long, value> shape; numpy_iexpr() {} numpy_iexpr(numpy_iexpr const &) = default; numpy_iexpr(numpy_iexpr&&) = default; template<class Argp> // not using the default one, to make it possible to accept reference and non reference version of Argp numpy_iexpr(numpy_iexpr<Argp> const & other) : arg(other.arg), buffer(other.buffer), shape(other.shape) { } numpy_iexpr(Arg const & arg, long index) : arg(arg), buffer(arg.buffer) { buffer += buffer_offset(index, utils::int_<value>()); } // force the move. Using universal reference here does not work (because of reference collapsing ?) numpy_iexpr(typename std::remove_reference<Arg>::type &&arg, long index) : arg(std::move(arg)), buffer(arg.buffer) { buffer += buffer_offset(index, utils::int_<value>()); } template<class E> numpy_iexpr& operator=(E const& expr) { return utils::broadcast_copy(*this, expr, utils::int_<value - utils::dim_of<E>::value>()); } numpy_iexpr& operator=(numpy_iexpr const& expr) { return utils::broadcast_copy(*this, expr, utils::int_<value - utils::dim_of<numpy_iexpr>::value>()); } template<class E> numpy_iexpr& operator+=(E const& expr) { return (*this) = (*this) + expr; } numpy_iexpr& operator+=(numpy_iexpr const& expr) { return (*this) = (*this) + expr; } template<class E> numpy_iexpr& operator-=(E const& expr) { return (*this) = (*this) - expr; } numpy_iexpr& operator-=(numpy_iexpr const& expr) { return (*this) = (*this) - expr; } template<class E> numpy_iexpr& operator*=(E const& expr) { return (*this) = (*this) * expr; } numpy_iexpr& operator*=(numpy_iexpr const& expr) { return (*this) = (*this) * expr; } template<class E> numpy_iexpr& operator/=(E const& expr) { return (*this) = (*this) / expr; } numpy_iexpr& operator/=(numpy_iexpr const& expr) { return (*this) = (*this) / expr; } const_iterator begin() const { return const_iterator(*this, 0); } const_iterator end() const { return const_iterator(*this, shape[0]); } iterator begin() { return iterator(*this, 0); } iterator end() { return iterator(*this, shape[0]); } dtype const * fbegin() const { return buffer; } dtype const * fend() const { return buffer + size(); } dtype * fbegin() { return buffer; } dtype const * fend() { return buffer + size(); } /* There are three kind of indexing operator: fast(long), [long] and (long): * - fast does not perform automatic bound wrapping * - [] performs automatic bound wrapping, hen forwards to fast * - () is an alias to [] and directly forwards to [] * * For each indexing operator, we have three variant: &, const& and &&: * - & means the numpy_iexpr has been bound to a non-const value, as in ``b=a[i] ; print b[j]`` * in that case the return type if the dim of a is 2 is a reference, to allow ``b[j] = 1`` * - const & means the numpy_iexpr has been bound to a const value, as in ``np.copy(a[i])`` * in that case the return type if the dim of a is 2 is a value (or const ref) * - && means the numpy_iexpr is a r-value, which happens a lot, as in ``a[i][j]`` * in that case the return type if the dim of a is 2 is a reference. * It is a bit weird because we return a refrence from a rvalue, but the reference is bound to * the buffer of ``a`` that is not temp. */ auto fast(long i) const &-> decltype(numpy_iexpr_helper<numpy_iexpr, value>::get(*this, i)) { return numpy_iexpr_helper<numpy_iexpr, value>::get(*this, i); } auto fast(long i) &-> decltype(numpy_iexpr_helper<numpy_iexpr, value>::get(*this, i)) { return numpy_iexpr_helper<numpy_iexpr, value>::get(*this, i); } auto fast(long i) &&-> decltype(numpy_iexpr_helper<numpy_iexpr, value>::get(std::move(*this), i)) { return numpy_iexpr_helper<numpy_iexpr, value>::get(std::move(*this), i); } auto operator[](long i) const &-> decltype(this->fast(i)) { if(i<0) i += shape[0]; return fast(i); } auto operator[](long i) &-> decltype(this->fast(i)) { if(i<0) i += shape[0]; return fast(i); } auto operator[](long i) && -> decltype(std::move(*this).fast(i)) { if(i<0) i += shape[0]; return std::move(*this).fast(i); } auto operator()(long i) const &-> decltype((*this)[i]) { return (*this)[i]; } auto operator()(long i) &-> decltype((*this)[i]) { return (*this)[i]; } auto operator()(long i) &&-> decltype(std::move(*this)[i]) { return std::move(*this)[i]; } numpy_gexpr<numpy_iexpr, slice> operator()(slice const& s0) const { return numpy_gexpr<numpy_iexpr, slice>(*this, s0); } numpy_gexpr<numpy_iexpr, slice> operator[](slice const& s0) const { return numpy_gexpr<numpy_iexpr, slice>(*this, s0); } numpy_gexpr<numpy_iexpr, contiguous_slice> operator()(contiguous_slice const& s0) const { return numpy_gexpr<numpy_iexpr, contiguous_slice>(*this, s0); } numpy_gexpr<numpy_iexpr, contiguous_slice> operator[](contiguous_slice const& s0) const { return numpy_gexpr<numpy_iexpr, contiguous_slice>(*this, s0); } template<class ...S> numpy_gexpr<numpy_iexpr, slice, S...> operator()(slice const& s0, S const&... s) const { return numpy_gexpr<numpy_iexpr, slice, S...>(*this, s0, s...); } template<class ...S> numpy_gexpr<numpy_iexpr, contiguous_slice, S...> operator()(contiguous_slice const& s0, S const&... s) const { return numpy_gexpr<numpy_iexpr, contiguous_slice, S...>(*this, s0, s...); } template<class ...S> auto operator()(long s0, S const&... s) const -> decltype(std::declval<numpy_iexpr<numpy_iexpr>>()(s...)) { return (*this)[s0](s...); } template<class F> typename std::enable_if<is_numexpr_arg<F>::value, numpy_fexpr<numpy_iexpr, F>>::type operator[](F const& filter) const { return numpy_fexpr<numpy_iexpr, F>(*this, filter); } long size() const { return /*arg.size()*/ std::accumulate(shape.begin() + 1, shape.end(), *shape.begin(), std::multiplies<long>()); } private: /* compute the buffer offset, returning the offset between the * first element of the iexpr and the start of the buffer. * This used to be a plain loop, but g++ fails to unroll it, while it unrolls it with the template version... */ long buffer_offset(long index, utils::int_<0>) { return index; } template<size_t N> long buffer_offset(long index, utils::int_<N>) { shape[value - N] = arg.shape[value - N + 1]; return buffer_offset(index * arg.shape[value - N + 1], utils::int_<N - 1>()); } }; // Indexing an numpy_iexpr that has a dimension greater than one yields a new numpy_iexpr template <class T, size_t N> struct numpy_iexpr_helper { static numpy_iexpr<T> get(T const& e, long i) { return numpy_iexpr<T>(e, i); } }; // Indexing an iexpr that has a dimension of one yields a qualified scalar. The qualifier is either: // - a reference if the numpy_iexpr is a ref itself, as in ``b = a[i] ; b[i] = 1`` // - a reference if the numpy_iexpr is a r-value, as in ``a[i][j] = 1`` // - a value if the numpy_iexpr is a const ref, as in ``b = a[i] ; c = b[i]`` template <class T> struct numpy_iexpr_helper<T, 1> { static typename T::dtype get(T const & e, long i) { return e.buffer[i]; } static typename T::dtype & get(T && e, long i) { return e.buffer[i]; } static typename T::dtype & get(T & e, long i) { return e.buffer[i]; } }; } template<class Arg> struct assignable<types::numpy_iexpr<Arg>> { typedef types::numpy_iexpr<typename assignable<Arg>::type> type; }; template<class Arg> struct lazy<types::numpy_iexpr<Arg>> { typedef types::numpy_iexpr<typename lazy<Arg>::type> type; }; template<class Arg> struct lazy<types::numpy_iexpr<Arg const &>> { typedef types::numpy_iexpr<typename lazy<Arg>::type const &> type; }; } /* type inference stuff {*/ #include "pythonic/types/combined.hpp" template<class E, class K> struct __combined<pythonic::types::numpy_iexpr<E>, K> { typedef pythonic::types::numpy_iexpr<E> type; }; #endif <|endoftext|>
<commit_before>/*************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation ([email protected]) ** ** This file is part of mcompositor. ** ** If you have questions regarding the use of this file, please contact ** Nokia at [email protected]. ** ** 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 "mtexturepixmapitem.h" #include "mtexturepixmapitem_p.h" #include "mcompositewindowgroup.h" #include <QPainterPath> #include <QRect> #include <QGLContext> #include <QX11Info> #include <vector> #include <X11/Xlib.h> #include <X11/extensions/Xcomposite.h> #include <X11/extensions/Xrender.h> #include <X11/extensions/Xfixes.h> //#define GL_GLEXT_PROTOTYPES #include <GLES2/gl2.h> #include <GLES2/gl2ext.h> static PFNEGLCREATEIMAGEKHRPROC eglCreateImageKHR = 0; static PFNEGLDESTROYIMAGEKHRPROC eglDestroyImageKHR = 0; static PFNGLEGLIMAGETARGETTEXTURE2DOESPROC glEGLImageTargetTexture2DOES = 0; static EGLint attribs[] = { EGL_IMAGE_PRESERVED_KHR, EGL_TRUE, EGL_NONE }; class EglTextureManager { public: // TODO: this should be dynamic // use QCache instead like Qt's GL backend static const int sz = 20; EglTextureManager() { glGenTextures(sz, tex); for (int i = 0; i < sz; i++) textures.push_back(tex[i]); } ~EglTextureManager() { glDeleteTextures(sz, tex); } GLuint getTexture() { if (textures.empty()) { qWarning("Empty texture stack"); return 0; } GLuint ret = textures.back(); textures.pop_back(); return ret; } void closeTexture(GLuint texture) { // clear this texture glBindTexture(GL_TEXTURE_2D, texture); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 0, 0, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0); textures.push_back(texture); } GLuint tex[sz+1]; std::vector<GLuint> textures; }; class EglResourceManager { public: EglResourceManager() : has_tfp(false) { int maj, min; if (!dpy) { dpy = eglGetDisplay(EGLNativeDisplayType(QX11Info::display())); eglInitialize(dpy, &maj, &min); } QString exts = QLatin1String(eglQueryString(dpy, EGL_EXTENSIONS)); if ((exts.contains("EGL_KHR_image") && exts.contains("EGL_KHR_gl_texture_2D_image"))) { has_tfp = true; eglCreateImageKHR = (PFNEGLCREATEIMAGEKHRPROC) eglGetProcAddress("eglCreateImageKHR"); eglDestroyImageKHR = (PFNEGLDESTROYIMAGEKHRPROC) eglGetProcAddress("eglDestroyImageKHR"); glEGLImageTargetTexture2DOES = (PFNGLEGLIMAGETARGETTEXTURE2DOESPROC) eglGetProcAddress("glEGLImageTargetTexture2DOES"); } else { qDebug("EGL version: %d.%d\n", maj, min); qDebug("No EGL tfp support.\n"); } texman = new EglTextureManager(); } bool texturePixmapSupport() { return has_tfp; } EglTextureManager *texman; static EGLConfig config; static EGLConfig configAlpha; static EGLDisplay dpy; bool has_tfp; }; EglResourceManager *MTexturePixmapPrivate::eglresource = 0; EGLConfig EglResourceManager::config = 0; EGLConfig EglResourceManager::configAlpha = 0; EGLDisplay EglResourceManager::dpy = 0; void MTexturePixmapItem::init() { if ((!isValid() && !propertyCache()->isVirtual()) || propertyCache()->isInputOnly()) return; if (!d->eglresource) d->eglresource = new EglResourceManager(); d->custom_tfp = !d->eglresource->texturePixmapSupport(); d->textureId = d->eglresource->texman->getTexture(); glEnable(GL_TEXTURE_2D); if (d->custom_tfp) d->inverted_texture = false; glBindTexture(GL_TEXTURE_2D, d->textureId); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); d->saveBackingStore(); } MTexturePixmapItem::MTexturePixmapItem(Window window, MWindowPropertyCache *mpc, QGraphicsItem* parent) : MCompositeWindow(window, mpc, parent), d(new MTexturePixmapPrivate(window, this)) { init(); } static void freeEglImage(MTexturePixmapPrivate *d) { if (d->egl_image != EGL_NO_IMAGE_KHR) { /* Free EGLImage from the texture */ glBindTexture(GL_TEXTURE_2D, d->textureId); /* * Texture size 64x64 is minimum required by GL. But we can assume 0x0 * works with modern drivers/hw. */ glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 0, 0, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL); glBindTexture(GL_TEXTURE_2D, 0); eglDestroyImageKHR(d->eglresource->dpy, d->egl_image); d->egl_image = EGL_NO_IMAGE_KHR; } } void MTexturePixmapItem::rebindPixmap() { freeEglImage(d); if (!d->windowp) { d->egl_image = EGL_NO_IMAGE_KHR; return; } d->ctx->makeCurrent(); doTFP(); } void MTexturePixmapItem::enableDirectFbRendering() { if (d->direct_fb_render || propertyCache()->isVirtual()) return; if (propertyCache()) propertyCache()->damageTracking(false); d->direct_fb_render = true; freeEglImage(d); if (d->windowp) { XFreePixmap(QX11Info::display(), d->windowp); d->windowp = 0; } XCompositeUnredirectWindow(QX11Info::display(), window(), CompositeRedirectManual); } void MTexturePixmapItem::enableRedirectedRendering() { if (!d->direct_fb_render || propertyCache()->isVirtual()) return; if (propertyCache()) propertyCache()->damageTracking(true); d->direct_fb_render = false; XCompositeRedirectWindow(QX11Info::display(), window(), CompositeRedirectManual); saveBackingStore(); updateWindowPixmap(); } MTexturePixmapItem::~MTexturePixmapItem() { cleanup(); delete d; // frees the pixmap too } void MTexturePixmapItem::initCustomTfp() { // UNUSED. // TODO: GLX backend should probably use same approach as here and // re-use same texture id } void MTexturePixmapItem::cleanup() { freeEglImage(d); d->eglresource->texman->closeTexture(d->textureId); } void MTexturePixmapItem::updateWindowPixmap(XRectangle *rects, int num, Time when) { // When a window is in transitioning limit the number of updates // to @limit/@expiry miliseconds. const unsigned expiry = 1000; const int limit = 10; if (hasTransitioningWindow()) { // Limit the number of damages we're willing to process if we're // in the middle of a transition, so the competition for the GL // resources will be less tight. if (d->pastDamages) { // Forget about pastDamages we received long ago. while (d->pastDamages->size() > 0 && d->pastDamages->first() + expiry < when) d->pastDamages->removeFirst(); if (d->pastDamages->size() >= limit) // Too many damages in the given timeframe, throttle. return; } else d->pastDamages = new QList<Time>; // Can afford this damage, but recoed when we received it, // so to know when to forget about them. d->pastDamages->append(when); } else if (d->pastDamages) { // The window is not transitioning, forget about all pastDamages. delete d->pastDamages; d->pastDamages = NULL; } // we want to update the pixmap even if the item is not visible because // certain animations require up-to-date pixmap (alternatively we could mark // it dirty and update it before the animation starts...) if (d->direct_fb_render || propertyCache()->isInputOnly()) return; if (!rects) // no rects means the whole area d->damageRegion = boundingRect().toRect(); else { QRegion r; for (int i = 0; i < num; ++i) r += QRegion(rects[i].x, rects[i].y, rects[i].width, rects[i].height); d->damageRegion = r; } bool new_image = false; if (d->custom_tfp) { QPixmap qp = QPixmap::fromX11Pixmap(d->windowp); QImage img = d->glwidget->convertToGLFormat(qp.toImage()); glBindTexture(GL_TEXTURE_2D, d->textureId); glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, img.width(), img.height(), GL_RGBA, GL_UNSIGNED_BYTE, img.bits()); new_image = true; } else if (d->egl_image == EGL_NO_IMAGE_KHR) { saveBackingStore(); new_image = true; } if (new_image || !d->damageRegion.isEmpty()) { if (!d->current_window_group) d->glwidget->update(); else d->current_window_group->updateWindowPixmap(); } } void MTexturePixmapItem::doTFP() { if (isClosing()) // Pixmap is already freed. No sense to create EGL image return; // from it again if (d->custom_tfp) { // no EGL texture from pixmap extensions available // use regular X11/GL calls to copy pixels from Pixmap to GL Texture QPixmap qp = QPixmap::fromX11Pixmap(d->windowp); QT_TRY { QImage img = QGLWidget::convertToGLFormat(qp.toImage()); glBindTexture(GL_TEXTURE_2D, d->textureId); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, img.width(), img.height(), 0, GL_RGBA, GL_UNSIGNED_BYTE, img.bits()); } QT_CATCH(std::bad_alloc e) { /* XGetImage() failed, the window has been unmapped. */; qWarning("MTexturePixmapItem::%s(): std::bad_alloc e", __func__); } } else { //use EGL extensions d->egl_image = eglCreateImageKHR(d->eglresource->dpy, 0, EGL_NATIVE_PIXMAP_KHR, (EGLClientBuffer)d->windowp, attribs); if (d->egl_image == EGL_NO_IMAGE_KHR) { // window is probably unmapped /*qWarning("MTexturePixmapItem::%s(): Cannot create EGL image: 0x%x", __func__, eglGetError());*/ return; } else { glBindTexture(GL_TEXTURE_2D, d->textureId); glEGLImageTargetTexture2DOES(GL_TEXTURE_2D, d->egl_image); } } } <commit_msg>Fixes: NB#233110 - On switching to an application, window content from previous application is shown for a while - EglTextureManager: remove hard-coded limit of 20 textures (cherry picked from commit 630f510bd87c95355e337a588ec089a56a79cc0e)<commit_after>/*************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation ([email protected]) ** ** This file is part of mcompositor. ** ** If you have questions regarding the use of this file, please contact ** Nokia at [email protected]. ** ** 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 "mtexturepixmapitem.h" #include "mtexturepixmapitem_p.h" #include "mcompositewindowgroup.h" #include <QPainterPath> #include <QRect> #include <QGLContext> #include <QX11Info> #include <QVector> #include <X11/Xlib.h> #include <X11/extensions/Xcomposite.h> #include <X11/extensions/Xrender.h> #include <X11/extensions/Xfixes.h> //#define GL_GLEXT_PROTOTYPES #include <GLES2/gl2.h> #include <GLES2/gl2ext.h> static PFNEGLCREATEIMAGEKHRPROC eglCreateImageKHR = 0; static PFNEGLDESTROYIMAGEKHRPROC eglDestroyImageKHR = 0; static PFNGLEGLIMAGETARGETTEXTURE2DOESPROC glEGLImageTargetTexture2DOES = 0; static EGLint attribs[] = { EGL_IMAGE_PRESERVED_KHR, EGL_TRUE, EGL_NONE }; class EglTextureManager { public: EglTextureManager() { genTextures(20); } ~EglTextureManager() { int sz = all_tex.size(); glDeleteTextures(sz, all_tex.constData()); } GLuint getTexture() { if (free_tex.empty()) genTextures(10); GLuint ret = free_tex.back(); free_tex.pop_back(); return ret; } void closeTexture(GLuint texture) { // clear this texture glBindTexture(GL_TEXTURE_2D, texture); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 0, 0, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0); free_tex.push_back(texture); } private: void genTextures(int n) { GLuint tex[n + 1]; glGenTextures(n, tex); for (int i = 0; i < n; i++) { free_tex.push_back(tex[i]); all_tex.push_back(tex[i]); } } QVector<GLuint> free_tex, all_tex; }; class EglResourceManager { public: EglResourceManager() : has_tfp(false) { int maj, min; if (!dpy) { dpy = eglGetDisplay(EGLNativeDisplayType(QX11Info::display())); eglInitialize(dpy, &maj, &min); } QString exts = QLatin1String(eglQueryString(dpy, EGL_EXTENSIONS)); if ((exts.contains("EGL_KHR_image") && exts.contains("EGL_KHR_gl_texture_2D_image"))) { has_tfp = true; eglCreateImageKHR = (PFNEGLCREATEIMAGEKHRPROC) eglGetProcAddress("eglCreateImageKHR"); eglDestroyImageKHR = (PFNEGLDESTROYIMAGEKHRPROC) eglGetProcAddress("eglDestroyImageKHR"); glEGLImageTargetTexture2DOES = (PFNGLEGLIMAGETARGETTEXTURE2DOESPROC) eglGetProcAddress("glEGLImageTargetTexture2DOES"); } else { qDebug("EGL version: %d.%d\n", maj, min); qDebug("No EGL tfp support.\n"); } texman = new EglTextureManager(); } bool texturePixmapSupport() { return has_tfp; } EglTextureManager *texman; static EGLConfig config; static EGLConfig configAlpha; static EGLDisplay dpy; bool has_tfp; }; EglResourceManager *MTexturePixmapPrivate::eglresource = 0; EGLConfig EglResourceManager::config = 0; EGLConfig EglResourceManager::configAlpha = 0; EGLDisplay EglResourceManager::dpy = 0; void MTexturePixmapItem::init() { if ((!isValid() && !propertyCache()->isVirtual()) || propertyCache()->isInputOnly()) return; if (!d->eglresource) d->eglresource = new EglResourceManager(); d->custom_tfp = !d->eglresource->texturePixmapSupport(); d->textureId = d->eglresource->texman->getTexture(); glEnable(GL_TEXTURE_2D); if (d->custom_tfp) d->inverted_texture = false; glBindTexture(GL_TEXTURE_2D, d->textureId); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); d->saveBackingStore(); } MTexturePixmapItem::MTexturePixmapItem(Window window, MWindowPropertyCache *mpc, QGraphicsItem* parent) : MCompositeWindow(window, mpc, parent), d(new MTexturePixmapPrivate(window, this)) { init(); } static void freeEglImage(MTexturePixmapPrivate *d) { if (d->egl_image != EGL_NO_IMAGE_KHR) { /* Free EGLImage from the texture */ glBindTexture(GL_TEXTURE_2D, d->textureId); /* * Texture size 64x64 is minimum required by GL. But we can assume 0x0 * works with modern drivers/hw. */ glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 0, 0, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL); glBindTexture(GL_TEXTURE_2D, 0); eglDestroyImageKHR(d->eglresource->dpy, d->egl_image); d->egl_image = EGL_NO_IMAGE_KHR; } } void MTexturePixmapItem::rebindPixmap() { freeEglImage(d); if (!d->windowp) { d->egl_image = EGL_NO_IMAGE_KHR; return; } d->ctx->makeCurrent(); doTFP(); } void MTexturePixmapItem::enableDirectFbRendering() { if (d->direct_fb_render || propertyCache()->isVirtual()) return; if (propertyCache()) propertyCache()->damageTracking(false); d->direct_fb_render = true; freeEglImage(d); if (d->windowp) { XFreePixmap(QX11Info::display(), d->windowp); d->windowp = 0; } XCompositeUnredirectWindow(QX11Info::display(), window(), CompositeRedirectManual); } void MTexturePixmapItem::enableRedirectedRendering() { if (!d->direct_fb_render || propertyCache()->isVirtual()) return; if (propertyCache()) propertyCache()->damageTracking(true); d->direct_fb_render = false; XCompositeRedirectWindow(QX11Info::display(), window(), CompositeRedirectManual); saveBackingStore(); updateWindowPixmap(); } MTexturePixmapItem::~MTexturePixmapItem() { cleanup(); delete d; // frees the pixmap too } void MTexturePixmapItem::initCustomTfp() { // UNUSED. // TODO: GLX backend should probably use same approach as here and // re-use same texture id } void MTexturePixmapItem::cleanup() { freeEglImage(d); d->eglresource->texman->closeTexture(d->textureId); } void MTexturePixmapItem::updateWindowPixmap(XRectangle *rects, int num, Time when) { // When a window is in transitioning limit the number of updates // to @limit/@expiry miliseconds. const unsigned expiry = 1000; const int limit = 10; if (hasTransitioningWindow()) { // Limit the number of damages we're willing to process if we're // in the middle of a transition, so the competition for the GL // resources will be less tight. if (d->pastDamages) { // Forget about pastDamages we received long ago. while (d->pastDamages->size() > 0 && d->pastDamages->first() + expiry < when) d->pastDamages->removeFirst(); if (d->pastDamages->size() >= limit) // Too many damages in the given timeframe, throttle. return; } else d->pastDamages = new QList<Time>; // Can afford this damage, but recoed when we received it, // so to know when to forget about them. d->pastDamages->append(when); } else if (d->pastDamages) { // The window is not transitioning, forget about all pastDamages. delete d->pastDamages; d->pastDamages = NULL; } // we want to update the pixmap even if the item is not visible because // certain animations require up-to-date pixmap (alternatively we could mark // it dirty and update it before the animation starts...) if (d->direct_fb_render || propertyCache()->isInputOnly()) return; if (!rects) // no rects means the whole area d->damageRegion = boundingRect().toRect(); else { QRegion r; for (int i = 0; i < num; ++i) r += QRegion(rects[i].x, rects[i].y, rects[i].width, rects[i].height); d->damageRegion = r; } bool new_image = false; if (d->custom_tfp) { QPixmap qp = QPixmap::fromX11Pixmap(d->windowp); QImage img = d->glwidget->convertToGLFormat(qp.toImage()); glBindTexture(GL_TEXTURE_2D, d->textureId); glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, img.width(), img.height(), GL_RGBA, GL_UNSIGNED_BYTE, img.bits()); new_image = true; } else if (d->egl_image == EGL_NO_IMAGE_KHR) { saveBackingStore(); new_image = true; } if (new_image || !d->damageRegion.isEmpty()) { if (!d->current_window_group) d->glwidget->update(); else d->current_window_group->updateWindowPixmap(); } } void MTexturePixmapItem::doTFP() { if (isClosing()) // Pixmap is already freed. No sense to create EGL image return; // from it again if (d->custom_tfp) { // no EGL texture from pixmap extensions available // use regular X11/GL calls to copy pixels from Pixmap to GL Texture QPixmap qp = QPixmap::fromX11Pixmap(d->windowp); QT_TRY { QImage img = QGLWidget::convertToGLFormat(qp.toImage()); glBindTexture(GL_TEXTURE_2D, d->textureId); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, img.width(), img.height(), 0, GL_RGBA, GL_UNSIGNED_BYTE, img.bits()); } QT_CATCH(std::bad_alloc e) { /* XGetImage() failed, the window has been unmapped. */; qWarning("MTexturePixmapItem::%s(): std::bad_alloc e", __func__); } } else { //use EGL extensions d->egl_image = eglCreateImageKHR(d->eglresource->dpy, 0, EGL_NATIVE_PIXMAP_KHR, (EGLClientBuffer)d->windowp, attribs); if (d->egl_image == EGL_NO_IMAGE_KHR) { // window is probably unmapped /*qWarning("MTexturePixmapItem::%s(): Cannot create EGL image: 0x%x", __func__, eglGetError());*/ return; } else { glBindTexture(GL_TEXTURE_2D, d->textureId); glEGLImageTargetTexture2DOES(GL_TEXTURE_2D, d->egl_image); } } } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: parrtf.hxx,v $ * * $Revision: 1.2 $ * * last change: $Author: vg $ $Date: 2007-04-11 19:30: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 * ************************************************************************/ #ifndef _PARRTF_HXX #define _PARRTF_HXX #ifndef INCLUDED_SVTDLLAPI_H #include "svtools/svtdllapi.h" #endif #ifndef _SVPARSER_HXX #include <svtools/svparser.hxx> #endif #ifndef _SVARRAY_HXX #include <svtools/svarray.hxx> #endif struct RtfParserState_Impl { rtl_TextEncoding eCodeSet; BYTE nUCharOverread; RtfParserState_Impl( BYTE nUOverread, rtl_TextEncoding eCdSt ) : eCodeSet( eCdSt ), nUCharOverread( nUOverread ) {} }; SV_DECL_VARARR( RtfParserStates_Impl, RtfParserState_Impl, 16, 16 ) class SVT_DLLPUBLIC SvRTFParser : public SvParser { RtfParserStates_Impl aParserStates; int nOpenBrakets; rtl_TextEncoding eCodeSet, eUNICodeSet; BYTE nUCharOverread; private: static short _inSkipGroup; protected: sal_Unicode GetHexValue(); void ScanText( const sal_Unicode = 0 ); void SkipGroup(); // scanne das naechste Token, virtual int _GetNextToken(); virtual void ReadUnknownData(); virtual void ReadBitmapData(); virtual void ReadOLEData(); virtual ~SvRTFParser(); rtl_TextEncoding GetCodeSet() const { return eCodeSet; } void SetEncoding( rtl_TextEncoding eEnc ); rtl_TextEncoding GetUNICodeSet() const { return eUNICodeSet; } void SetUNICodeSet( rtl_TextEncoding eSet ) { eUNICodeSet = eSet; } public: SvRTFParser( SvStream& rIn, BYTE nStackSize = 3 ); virtual SvParserState CallParser(); // Aufruf des Parsers int GetOpenBrakets() const { return nOpenBrakets; } // fuers asynchrone lesen aus dem SvStream // virtual void SaveState( int nToken ); // virtual void RestoreState(); virtual void Continue( int nToken ); }; #endif //_PARRTF_HXX <commit_msg>INTEGRATION: CWS changefileheader (1.2.320); FILE MERGED 2008/04/01 12:43:14 thb 1.2.320.2: #i85898# Stripping all external header guards 2008/03/31 13:01:07 rt 1.2.320.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: parrtf.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 _PARRTF_HXX #define _PARRTF_HXX #include "svtools/svtdllapi.h" #include <svtools/svparser.hxx> #include <svtools/svarray.hxx> struct RtfParserState_Impl { rtl_TextEncoding eCodeSet; BYTE nUCharOverread; RtfParserState_Impl( BYTE nUOverread, rtl_TextEncoding eCdSt ) : eCodeSet( eCdSt ), nUCharOverread( nUOverread ) {} }; SV_DECL_VARARR( RtfParserStates_Impl, RtfParserState_Impl, 16, 16 ) class SVT_DLLPUBLIC SvRTFParser : public SvParser { RtfParserStates_Impl aParserStates; int nOpenBrakets; rtl_TextEncoding eCodeSet, eUNICodeSet; BYTE nUCharOverread; private: static short _inSkipGroup; protected: sal_Unicode GetHexValue(); void ScanText( const sal_Unicode = 0 ); void SkipGroup(); // scanne das naechste Token, virtual int _GetNextToken(); virtual void ReadUnknownData(); virtual void ReadBitmapData(); virtual void ReadOLEData(); virtual ~SvRTFParser(); rtl_TextEncoding GetCodeSet() const { return eCodeSet; } void SetEncoding( rtl_TextEncoding eEnc ); rtl_TextEncoding GetUNICodeSet() const { return eUNICodeSet; } void SetUNICodeSet( rtl_TextEncoding eSet ) { eUNICodeSet = eSet; } public: SvRTFParser( SvStream& rIn, BYTE nStackSize = 3 ); virtual SvParserState CallParser(); // Aufruf des Parsers int GetOpenBrakets() const { return nOpenBrakets; } // fuers asynchrone lesen aus dem SvStream // virtual void SaveState( int nToken ); // virtual void RestoreState(); virtual void Continue( int nToken ); }; #endif //_PARRTF_HXX <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: element.hxx,v $ * * $Revision: 1.2 $ * * last change: $Author: lo $ $Date: 2004-02-26 14:43:16 $ * * 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: 2004 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _ELEMENT_HXX #define _ELEMENT_HXX #include <com/sun/star/uno/Reference.h> #include <com/sun/star/uno/Exception.hpp> #include <com/sun/star/xml/dom/XNode.hpp> #include <com/sun/star/xml/dom/XNodeList.hpp> #include <com/sun/star/xml/dom/XNamedNodeMap.hpp> #include <com/sun/star/xml/dom/NodeType.hpp> #include <libxml/tree.h> #include "node.hxx" using namespace rtl; using namespace com::sun::star::uno; using namespace com::sun::star::lang; using namespace com::sun::star::xml::dom; namespace DOM { class CElement : public cppu::ImplInheritanceHelper1<CNode, XElement > { friend class CNode; private: Reference< XAttr > _setAttributeNode(const Reference< XAttr >& newAttr, sal_Bool bNS) throw (RuntimeException); protected: CElement(const xmlNodePtr aNodePtr); public: /** Retrieves an attribute value by name. */ virtual OUString SAL_CALL getAttribute(const OUString& name) throw (RuntimeException); /** Retrieves an attribute node by name. */ virtual Reference< XAttr > SAL_CALL getAttributeNode(const OUString& name) throw (RuntimeException); /** Retrieves an Attr node by local name and namespace URI. */ virtual Reference< XAttr > SAL_CALL getAttributeNodeNS(const OUString& namespaceURI, const OUString& localName) throw (RuntimeException); /** Retrieves an attribute value by local name and namespace URI. */ virtual OUString SAL_CALL getAttributeNS(const OUString& namespaceURI, const OUString& localName) throw (RuntimeException); /** Returns a NodeList of all descendant Elements with a given tag name, in the order in which they are encountered in a preorder traversal of this Element tree. */ virtual Reference< XNodeList > SAL_CALL getElementsByTagName(const OUString& name) throw (RuntimeException); /** Returns a NodeList of all the descendant Elements with a given local name and namespace URI in the order in which they are encountered in a preorder traversal of this Element tree. */ virtual Reference< XNodeList > SAL_CALL getElementsByTagNameNS(const OUString& namespaceURI, const OUString& localName) throw (RuntimeException); /** The name of the element. */ virtual OUString SAL_CALL getTagName() throw (RuntimeException); /** Returns true when an attribute with a given name is specified on this element or has a default value, false otherwise. */ virtual sal_Bool SAL_CALL hasAttribute(const OUString& name) throw (RuntimeException); /** Returns true when an attribute with a given local name and namespace URI is specified on this element or has a default value, false otherwise. */ virtual sal_Bool SAL_CALL hasAttributeNS(const OUString& namespaceURI, const OUString& localName) throw (RuntimeException); /** Removes an attribute by name. */ virtual void SAL_CALL removeAttribute(const OUString& name) throw (DOMException); /** Removes the specified attribute node. */ virtual Reference< XAttr > SAL_CALL removeAttributeNode(const Reference< XAttr >& oldAttr) throw (DOMException); /** Removes an attribute by local name and namespace URI. */ virtual void SAL_CALL removeAttributeNS(const OUString& namespaceURI, const OUString& localName) throw (DOMException); /** Adds a new attribute. */ virtual void SAL_CALL setAttribute(const OUString& name, const OUString& value) throw (DOMException); /** Adds a new attribute node. */ virtual Reference< XAttr > SAL_CALL setAttributeNode(const Reference< XAttr >& newAttr) throw (DOMException); /** Adds a new attribute. */ virtual Reference< XAttr > SAL_CALL setAttributeNodeNS(const Reference< XAttr >& newAttr) throw (DOMException); /** Adds a new attribute. */ virtual void SAL_CALL setAttributeNS( const OUString& namespaceURI, const OUString& qualifiedName, const OUString& value) throw (DOMException); // overrides for XNode base virtual OUString SAL_CALL getNodeName() throw (RuntimeException); virtual OUString SAL_CALL getNodeValue() throw (RuntimeException); virtual Reference< XNamedNodeMap > SAL_CALL getAttributes() throw (RuntimeException); // resolve uno inheritance problems... // --- delegation for XNde base. virtual Reference< XNode > SAL_CALL appendChild(const Reference< XNode >& newChild) throw (DOMException) { return CNode::appendChild(newChild); } virtual Reference< XNode > SAL_CALL cloneNode(sal_Bool deep) throw (RuntimeException) { return CNode::cloneNode(deep); } virtual Reference< XNodeList > SAL_CALL getChildNodes() throw (RuntimeException) { return CNode::getChildNodes(); } virtual Reference< XNode > SAL_CALL getFirstChild() throw (RuntimeException) { return CNode::getFirstChild(); } virtual Reference< XNode > SAL_CALL getLastChild() throw (RuntimeException) { return CNode::getLastChild(); } virtual OUString SAL_CALL getLocalName() throw (RuntimeException) { return CNode::getLocalName(); } virtual OUString SAL_CALL getNamespaceURI() throw (RuntimeException) { return CNode::getNamespaceURI(); } virtual Reference< XNode > SAL_CALL getNextSibling() throw (RuntimeException) { return CNode::getNextSibling(); } virtual NodeType SAL_CALL getNodeType() throw (RuntimeException) { return CNode::getNodeType(); } virtual Reference< XDocument > SAL_CALL getOwnerDocument() throw (RuntimeException) { return CNode::getOwnerDocument(); } virtual Reference< XNode > SAL_CALL getParentNode() throw (RuntimeException) { return CNode::getParentNode(); } virtual OUString SAL_CALL getPrefix() throw (RuntimeException) { return CNode::getPrefix(); } virtual Reference< XNode > SAL_CALL getPreviousSibling() throw (RuntimeException) { return CNode::getPreviousSibling(); } virtual sal_Bool SAL_CALL hasAttributes() throw (RuntimeException) { return CNode::hasAttributes(); } virtual sal_Bool SAL_CALL hasChildNodes() throw (RuntimeException) { return CNode::hasChildNodes(); } virtual Reference< XNode > SAL_CALL insertBefore( const Reference< XNode >& newChild, const Reference< XNode >& refChild) throw (DOMException) { return CNode::insertBefore(newChild, refChild); } virtual sal_Bool SAL_CALL isSupported(const OUString& feature, const OUString& ver) throw (RuntimeException) { return CNode::isSupported(feature, ver); } virtual void SAL_CALL normalize() throw (RuntimeException) { CNode::normalize(); } virtual Reference< XNode > SAL_CALL removeChild(const Reference< XNode >& oldChild) throw (DOMException) { return CNode::removeChild(oldChild); } virtual Reference< XNode > SAL_CALL replaceChild( const Reference< XNode >& newChild, const Reference< XNode >& oldChild) throw (DOMException) { return CNode::replaceChild(newChild, oldChild); } virtual void SAL_CALL setNodeValue(const OUString& nodeValue) throw (DOMException) { return CNode::setNodeValue(nodeValue); } virtual void SAL_CALL setPrefix(const OUString& prefix) throw (DOMException) { return CNode::setPrefix(prefix); } }; } #endif<commit_msg>INTEGRATION: CWS eforms2 (1.2.2); FILE MERGED 2004/08/12 08:38:46 lo 1.2.2.2: fix Element::removeAttributeNode() 2004/04/23 11:34:56 lo 1.2.2.1: #i26721# put/get/post support for submission node cloning<commit_after>/************************************************************************* * * $RCSfile: element.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: obo $ $Date: 2004-11-16 12:23:12 $ * * 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: 2004 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _ELEMENT_HXX #define _ELEMENT_HXX #include <com/sun/star/uno/Reference.h> #include <com/sun/star/uno/Exception.hpp> #include <com/sun/star/xml/dom/XNode.hpp> #include <com/sun/star/xml/dom/XNodeList.hpp> #include <com/sun/star/xml/dom/XNamedNodeMap.hpp> #include <com/sun/star/xml/dom/NodeType.hpp> #include <libxml/tree.h> #include "node.hxx" using namespace rtl; using namespace com::sun::star::uno; using namespace com::sun::star::lang; using namespace com::sun::star::xml::dom; namespace DOM { class CElement : public cppu::ImplInheritanceHelper1<CNode, XElement > { friend class CNode; private: Reference< XAttr > _setAttributeNode(const Reference< XAttr >& newAttr, sal_Bool bNS) throw (RuntimeException); protected: CElement(const xmlNodePtr aNodePtr); public: /** Retrieves an attribute value by name. */ virtual OUString SAL_CALL getAttribute(const OUString& name) throw (RuntimeException); /** Retrieves an attribute node by name. */ virtual Reference< XAttr > SAL_CALL getAttributeNode(const OUString& name) throw (RuntimeException); /** Retrieves an Attr node by local name and namespace URI. */ virtual Reference< XAttr > SAL_CALL getAttributeNodeNS(const OUString& namespaceURI, const OUString& localName) throw (RuntimeException); /** Retrieves an attribute value by local name and namespace URI. */ virtual OUString SAL_CALL getAttributeNS(const OUString& namespaceURI, const OUString& localName) throw (RuntimeException); /** Returns a NodeList of all descendant Elements with a given tag name, in the order in which they are encountered in a preorder traversal of this Element tree. */ virtual Reference< XNodeList > SAL_CALL getElementsByTagName(const OUString& name) throw (RuntimeException); /** Returns a NodeList of all the descendant Elements with a given local name and namespace URI in the order in which they are encountered in a preorder traversal of this Element tree. */ virtual Reference< XNodeList > SAL_CALL getElementsByTagNameNS(const OUString& namespaceURI, const OUString& localName) throw (RuntimeException); /** The name of the element. */ virtual OUString SAL_CALL getTagName() throw (RuntimeException); /** Returns true when an attribute with a given name is specified on this element or has a default value, false otherwise. */ virtual sal_Bool SAL_CALL hasAttribute(const OUString& name) throw (RuntimeException); /** Returns true when an attribute with a given local name and namespace URI is specified on this element or has a default value, false otherwise. */ virtual sal_Bool SAL_CALL hasAttributeNS(const OUString& namespaceURI, const OUString& localName) throw (RuntimeException); /** Removes an attribute by name. */ virtual void SAL_CALL removeAttribute(const OUString& name) throw (DOMException); /** Removes the specified attribute node. */ virtual Reference< XAttr > SAL_CALL removeAttributeNode(const Reference< XAttr >& oldAttr) throw (DOMException); /** Removes an attribute by local name and namespace URI. */ virtual void SAL_CALL removeAttributeNS(const OUString& namespaceURI, const OUString& localName) throw (DOMException); /** Adds a new attribute. */ virtual void SAL_CALL setAttribute(const OUString& name, const OUString& value) throw (DOMException); /** Adds a new attribute node. */ virtual Reference< XAttr > SAL_CALL setAttributeNode(const Reference< XAttr >& newAttr) throw (DOMException); /** Adds a new attribute. */ virtual Reference< XAttr > SAL_CALL setAttributeNodeNS(const Reference< XAttr >& newAttr) throw (DOMException); /** Adds a new attribute. */ virtual void SAL_CALL setAttributeNS( const OUString& namespaceURI, const OUString& qualifiedName, const OUString& value) throw (DOMException); /** sets the element name */ virtual void SAL_CALL setElementName(const OUString& elementName) throw (DOMException); // overrides for XNode base virtual OUString SAL_CALL getNodeName() throw (RuntimeException); virtual OUString SAL_CALL getNodeValue() throw (RuntimeException); virtual Reference< XNamedNodeMap > SAL_CALL getAttributes() throw (RuntimeException); // resolve uno inheritance problems... // --- delegation for XNde base. virtual Reference< XNode > SAL_CALL appendChild(const Reference< XNode >& newChild) throw (DOMException) { return CNode::appendChild(newChild); } virtual Reference< XNode > SAL_CALL cloneNode(sal_Bool deep) throw (RuntimeException) { return CNode::cloneNode(deep); } virtual Reference< XNodeList > SAL_CALL getChildNodes() throw (RuntimeException) { return CNode::getChildNodes(); } virtual Reference< XNode > SAL_CALL getFirstChild() throw (RuntimeException) { return CNode::getFirstChild(); } virtual Reference< XNode > SAL_CALL getLastChild() throw (RuntimeException) { return CNode::getLastChild(); } virtual OUString SAL_CALL getLocalName() throw (RuntimeException) { return CNode::getLocalName(); } virtual OUString SAL_CALL getNamespaceURI() throw (RuntimeException) { return CNode::getNamespaceURI(); } virtual Reference< XNode > SAL_CALL getNextSibling() throw (RuntimeException) { return CNode::getNextSibling(); } virtual NodeType SAL_CALL getNodeType() throw (RuntimeException) { return CNode::getNodeType(); } virtual Reference< XDocument > SAL_CALL getOwnerDocument() throw (RuntimeException) { return CNode::getOwnerDocument(); } virtual Reference< XNode > SAL_CALL getParentNode() throw (RuntimeException) { return CNode::getParentNode(); } virtual OUString SAL_CALL getPrefix() throw (RuntimeException) { return CNode::getPrefix(); } virtual Reference< XNode > SAL_CALL getPreviousSibling() throw (RuntimeException) { return CNode::getPreviousSibling(); } virtual sal_Bool SAL_CALL hasAttributes() throw (RuntimeException) { return CNode::hasAttributes(); } virtual sal_Bool SAL_CALL hasChildNodes() throw (RuntimeException) { return CNode::hasChildNodes(); } virtual Reference< XNode > SAL_CALL insertBefore( const Reference< XNode >& newChild, const Reference< XNode >& refChild) throw (DOMException) { return CNode::insertBefore(newChild, refChild); } virtual sal_Bool SAL_CALL isSupported(const OUString& feature, const OUString& ver) throw (RuntimeException) { return CNode::isSupported(feature, ver); } virtual void SAL_CALL normalize() throw (RuntimeException) { CNode::normalize(); } virtual Reference< XNode > SAL_CALL removeChild(const Reference< XNode >& oldChild) throw (DOMException) { return CNode::removeChild(oldChild); } virtual Reference< XNode > SAL_CALL replaceChild( const Reference< XNode >& newChild, const Reference< XNode >& oldChild) throw (DOMException) { return CNode::replaceChild(newChild, oldChild); } virtual void SAL_CALL setNodeValue(const OUString& nodeValue) throw (DOMException) { return CNode::setNodeValue(nodeValue); } virtual void SAL_CALL setPrefix(const OUString& prefix) throw (DOMException) { return CNode::setPrefix(prefix); } }; } #endif<|endoftext|>
<commit_before>#ifndef _IRC_BOT_H #define _IRC_BOT_H #include <string> #include <vector> #include <unordered_map> #include <functional> #include <algorithm> #include "./types.hpp" #include "./server.hpp" #include "./packet.hpp" namespace IRC { class Bot { struct Command { std::string trigger, desc; std::function<void(const Packet&)> func; bool requires_admin; Command(const std::string& t , std::function<void(const Packet&)> f, const std::string& d, bool ra) : trigger(t), func(f), desc(d), requires_admin(ra) {} }; std::string nick; std::string password; std::vector<std::string> admins, ignored; std::vector< Server* > servers; std::vector<Command*> commands; public: enum class RELATIONSHIP { ADMIN, IGNORED }; Bot(const std::string& n, const std::string& pass, const std::vector<std::string>& _admins); ~Bot(); void add_server(std::string n , const std::string& a , const int& port, bool with_ssl = true); void connect_server(const std::string& server_name); void connect_server(const std::vector<Server*>::iterator& it); void disconnect_server(Server *s); bool join_channel(const std::string& server_name , const std::string& channel_name); bool join_channel(const std::vector<Server*>::iterator& it, const std::string& channel_name); void add_a(const RELATIONSHIP& r , const std::string& user); /* on some trigger, use function f. f has to be: void f(const Packet& p); */ template <class Func> void on_privmsg(const std::string& trigger, Func f, const std::string& desc, bool requires_admin = false); template <class Func> void on_join(Func f); template <class Func> void on_kick(Func f); void on_nick(); void listen(); private: void _check_for_triggers(const Packet& p); std::vector<Server*>::iterator _find_server_by_name(const std::string& n); bool _is_admin(const std::string& person); }; template <class Func> void Bot::on_privmsg(const std::string& trigger, Func f, const std::string& desc, bool requires_admin) { commands.push_back( new Command(trigger, f , desc, requires_admin) ); } }; #endif <commit_msg>add documentation to bot.hpp<commit_after>#ifndef _IRC_BOT_H #define _IRC_BOT_H #include <string> #include <vector> #include <unordered_map> #include <functional> #include <algorithm> #include "./types.hpp" #include "./server.hpp" #include "./packet.hpp" namespace IRC { class Bot { struct Command { std::string trigger, desc; std::function<void(const Packet&)> func; bool requires_admin; Command(const std::string& t , std::function<void(const Packet&)> f, const std::string& d, bool ra) : trigger(t), func(f), desc(d), requires_admin(ra) {} }; std::string nick; std::string password; std::vector<std::string> admins, ignored; std::vector< Server* > servers; std::vector<Command*> commands; public: /* A flag for add_a(...) */ enum class RELATIONSHIP { ADMIN, IGNORED }; /* Constructor. @param n the bot's nick. @param pass the bot's nickserv password. @param _admins a vector of strings representing the current nicks of admins. Note: Admins may change their nicks once the bot comes on; the bot tracks NICK changes. */ Bot(const std::string& n, const std::string& pass, const std::vector<std::string>& _admins); /* Deallocates servers and commands. */ ~Bot(); /* Adds a server. @param n the name of the server. @param a the address (irc.example.net) @param port the port as an integer. @param with_ssl whether or not to use SSL on the server. Defaults to using SSL. */ void add_server(std::string n , const std::string& a , const int& port, bool with_ssl = true); /* Connect to server by name @param server_name the server's name. This must be unique to work. */ void connect_server(const std::string& server_name); /* Disconnect from the server pointed to by s. @param s the server to disconnect from. TODO: Alternative means of disconnecting on the Bot level should be added. */ void disconnect_server(Server *s); /* Joins channel. @param server_name the server to send the JOIN to. @param channel_name the channel to join. This may be a #channel or a private message, but a private message wouldn't make much sense. @return the success of joining or not, to the best of the Bot's ability. */ bool join_channel(const std::string& server_name , const std::string& channel_name); /* Adds someone either to the IGNORE list or the ADMIN list. @param r the relationship (i.e., ADMIN, or IGNORED) @param user the user to relate to. */ void add_a(const RELATIONSHIP& r , const std::string& user); /* on some trigger, use function f. f has to be: void f(const Packet& p); @param trigger the string to look for. The trigger must appear at the beginning of the message being inspected for it to be a valid command. @param f the function to call upon triggering the command. @param desc a description of the command. This is used in @help @param requires_admin whether or not the command is privileged/sensitive and therefore requires administrative rights to run. */ template <class Func> void on_privmsg(const std::string& trigger, Func f, const std::string& desc, bool requires_admin = false); /* on_join, on_kick, and on_nick have not yet been implemented. */ // template <class Func> // void on_join(Func f); // // template <class Func> // void on_kick(Func f); // void on_nick(); /* Reads from all connected servers and responds accordingly if a trigger is found. */ void listen(); private: /* Helper function to perform the check for triggers and perform the appropriate actions on the appropriate channel on the right server. @param p the Packet to analyze. */ void _check_for_triggers(const Packet& p); /* Finds a server by name and returns the iterator. @param n the name of the server. This n is expected to be unique amongst all the servers. @return an iterator to the server named n, or std::vector::vector::end() if the server isn't found by the name n. */ std::vector<Server*>::iterator _find_server_by_name(const std::string& n); /* Verifies a person's presence in the admin list. @param person the person to look for in the admin list. @return whether or not the person is an admin. */ bool _is_admin(const std::string& person); void connect_server(const std::vector<Server*>::iterator& it); bool join_channel(const std::vector<Server*>::iterator& it, const std::string& channel_name); }; template <class Func> void Bot::on_privmsg(const std::string& trigger, Func f, const std::string& desc, bool requires_admin) { commands.push_back( new Command(trigger, f , desc, requires_admin) ); } }; #endif <|endoftext|>
<commit_before>//===-- tsan_external.cc --------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file is a part of ThreadSanitizer (TSan), a race detector. // //===----------------------------------------------------------------------===// #include "tsan_rtl.h" #include "tsan_interceptors.h" namespace __tsan { #define CALLERPC ((uptr)__builtin_return_address(0)) const uptr kMaxTag = 128; // Limited to 65,536, since MBlock only stores tags // as 16-bit values, see tsan_defs.h. const char *registered_tags[kMaxTag]; static atomic_uint32_t used_tags{1}; // Tag 0 means "no tag". NOLINT const char *GetObjectTypeFromTag(uptr tag) { if (tag == 0) return nullptr; // Invalid/corrupted tag? Better return NULL and let the caller deal with it. if (tag >= atomic_load(&used_tags, memory_order_relaxed)) return nullptr; return registered_tags[tag]; } extern "C" { SANITIZER_INTERFACE_ATTRIBUTE void *__tsan_external_register_tag(const char *object_type) { uptr new_tag = atomic_fetch_add(&used_tags, 1, memory_order_relaxed); CHECK_LT(new_tag, kMaxTag); registered_tags[new_tag] = internal_strdup(object_type); return (void *)new_tag; } SANITIZER_INTERFACE_ATTRIBUTE void __tsan_external_assign_tag(void *addr, void *tag) { CHECK_LT(tag, atomic_load(&used_tags, memory_order_relaxed)); Allocator *a = allocator(); MBlock *b = nullptr; if (a->PointerIsMine((void *)addr)) { void *block_begin = a->GetBlockBegin((void *)addr); if (block_begin) b = ctx->metamap.GetBlock((uptr)block_begin); } if (b) { b->tag = (uptr)tag; } } SANITIZER_INTERFACE_ATTRIBUTE void __tsan_external_read(void *addr, void *caller_pc, void *tag) { CHECK_LT(tag, atomic_load(&used_tags, memory_order_relaxed)); ThreadState *thr = cur_thread(); thr->external_tag = (uptr)tag; if (caller_pc) FuncEntry(thr, (uptr)caller_pc); bool in_ignored_lib; if (!caller_pc || !libignore()->IsIgnored((uptr)caller_pc, &in_ignored_lib)) { MemoryRead(thr, CALLERPC, (uptr)addr, kSizeLog8); } if (caller_pc) FuncExit(thr); thr->external_tag = 0; } SANITIZER_INTERFACE_ATTRIBUTE void __tsan_external_write(void *addr, void *caller_pc, void *tag) { CHECK_LT(tag, atomic_load(&used_tags, memory_order_relaxed)); ThreadState *thr = cur_thread(); thr->external_tag = (uptr)tag; if (caller_pc) FuncEntry(thr, (uptr)caller_pc); bool in_ignored_lib; if (!caller_pc || !libignore()->IsIgnored((uptr)caller_pc, &in_ignored_lib)) { MemoryWrite(thr, CALLERPC, (uptr)addr, kSizeLog8); } if (caller_pc) FuncExit(thr); thr->external_tag = 0; } } // extern "C" } // namespace __tsan <commit_msg>[tsan] Track external API accesses as 1-byte accesses (instead of 8-byte)<commit_after>//===-- tsan_external.cc --------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file is a part of ThreadSanitizer (TSan), a race detector. // //===----------------------------------------------------------------------===// #include "tsan_rtl.h" #include "tsan_interceptors.h" namespace __tsan { #define CALLERPC ((uptr)__builtin_return_address(0)) const uptr kMaxTag = 128; // Limited to 65,536, since MBlock only stores tags // as 16-bit values, see tsan_defs.h. const char *registered_tags[kMaxTag]; static atomic_uint32_t used_tags{1}; // Tag 0 means "no tag". NOLINT const char *GetObjectTypeFromTag(uptr tag) { if (tag == 0) return nullptr; // Invalid/corrupted tag? Better return NULL and let the caller deal with it. if (tag >= atomic_load(&used_tags, memory_order_relaxed)) return nullptr; return registered_tags[tag]; } extern "C" { SANITIZER_INTERFACE_ATTRIBUTE void *__tsan_external_register_tag(const char *object_type) { uptr new_tag = atomic_fetch_add(&used_tags, 1, memory_order_relaxed); CHECK_LT(new_tag, kMaxTag); registered_tags[new_tag] = internal_strdup(object_type); return (void *)new_tag; } SANITIZER_INTERFACE_ATTRIBUTE void __tsan_external_assign_tag(void *addr, void *tag) { CHECK_LT(tag, atomic_load(&used_tags, memory_order_relaxed)); Allocator *a = allocator(); MBlock *b = nullptr; if (a->PointerIsMine((void *)addr)) { void *block_begin = a->GetBlockBegin((void *)addr); if (block_begin) b = ctx->metamap.GetBlock((uptr)block_begin); } if (b) { b->tag = (uptr)tag; } } SANITIZER_INTERFACE_ATTRIBUTE void __tsan_external_read(void *addr, void *caller_pc, void *tag) { CHECK_LT(tag, atomic_load(&used_tags, memory_order_relaxed)); ThreadState *thr = cur_thread(); thr->external_tag = (uptr)tag; if (caller_pc) FuncEntry(thr, (uptr)caller_pc); bool in_ignored_lib; if (!caller_pc || !libignore()->IsIgnored((uptr)caller_pc, &in_ignored_lib)) { MemoryRead(thr, CALLERPC, (uptr)addr, kSizeLog1); } if (caller_pc) FuncExit(thr); thr->external_tag = 0; } SANITIZER_INTERFACE_ATTRIBUTE void __tsan_external_write(void *addr, void *caller_pc, void *tag) { CHECK_LT(tag, atomic_load(&used_tags, memory_order_relaxed)); ThreadState *thr = cur_thread(); thr->external_tag = (uptr)tag; if (caller_pc) FuncEntry(thr, (uptr)caller_pc); bool in_ignored_lib; if (!caller_pc || !libignore()->IsIgnored((uptr)caller_pc, &in_ignored_lib)) { MemoryWrite(thr, CALLERPC, (uptr)addr, kSizeLog1); } if (caller_pc) FuncExit(thr); thr->external_tag = 0; } } // extern "C" } // namespace __tsan <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: dstribut.cxx,v $ * * $Revision: 1.11 $ * * last change: $Author: hr $ $Date: 2007-06-27 17:03: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 * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_svx.hxx" #ifdef SVX_DLLIMPLEMENTATION #undef SVX_DLLIMPLEMENTATION #endif #ifndef _BASEDLGS_HXX #include <sfx2/basedlgs.hxx> #endif #include <svx/dialogs.hrc> #include "dstribut.hxx" #include "dstribut.hrc" #include <svx/svddef.hxx> #include <svx/dialmgr.hxx> #ifndef _SHL_HXX #include <tools/shl.hxx> #endif static USHORT pRanges[] = { SDRATTR_MEASURE_FIRST, SDRATTR_MEASURE_LAST, 0 }; /************************************************************************* |* |* Dialog |* \************************************************************************/ SvxDistributeDialog::SvxDistributeDialog( Window* pParent, const SfxItemSet& rInAttrs, SvxDistributeHorizontal eHor, SvxDistributeVertical eVer) : SfxSingleTabDialog(pParent, rInAttrs, RID_SVXPAGE_DISTRIBUTE ), mpPage(0L) { mpPage = new SvxDistributePage(this, rInAttrs, eHor, eVer); SetTabPage(mpPage); SetText(mpPage->GetText()); } /************************************************************************* |* |* Dtor |* \************************************************************************/ SvxDistributeDialog::~SvxDistributeDialog() { } /************************************************************************* |* |* Tabpage |* \************************************************************************/ SvxDistributePage::SvxDistributePage( Window* pWindow, const SfxItemSet& rInAttrs, SvxDistributeHorizontal eHor, SvxDistributeVertical eVer) : SvxTabPage(pWindow, SVX_RES(RID_SVXPAGE_DISTRIBUTE), rInAttrs), meDistributeHor(eHor), meDistributeVer(eVer), maFlHorizontal (this, SVX_RES(FL_HORIZONTAL )), maBtnHorNone (this, SVX_RES(BTN_HOR_NONE )), maBtnHorLeft (this, SVX_RES(BTN_HOR_LEFT )), maBtnHorCenter (this, SVX_RES(BTN_HOR_CENTER )), maBtnHorDistance (this, SVX_RES(BTN_HOR_DISTANCE )), maBtnHorRight (this, SVX_RES(BTN_HOR_RIGHT )), maHorLow (this, SVX_RES(IMG_HOR_LOW )), maHorCenter (this, SVX_RES(IMG_HOR_CENTER )), maHorDistance (this, SVX_RES(IMG_HOR_DISTANCE )), maHorHigh (this, SVX_RES(IMG_HOR_HIGH )), maFlVertical (this, SVX_RES(FL_VERTICAL )), maBtnVerNone (this, SVX_RES(BTN_VER_NONE )), maBtnVerTop (this, SVX_RES(BTN_VER_TOP )), maBtnVerCenter (this, SVX_RES(BTN_VER_CENTER )), maBtnVerDistance (this, SVX_RES(BTN_VER_DISTANCE )), maBtnVerBottom (this, SVX_RES(BTN_VER_BOTTOM )), maVerLow (this, SVX_RES(IMG_VER_LOW )), maVerCenter (this, SVX_RES(IMG_VER_CENTER )), maVerDistance (this, SVX_RES(IMG_VER_DISTANCE )), maVerHigh (this, SVX_RES(IMG_VER_HIGH )) { maHorLow.SetModeImage( Image( SVX_RES( IMG_HOR_LOW_H ) ), BMP_COLOR_HIGHCONTRAST ); maHorCenter.SetModeImage( Image( SVX_RES( IMG_HOR_CENTER_H ) ), BMP_COLOR_HIGHCONTRAST ); maHorDistance.SetModeImage( Image( SVX_RES( IMG_HOR_DISTANCE_H ) ), BMP_COLOR_HIGHCONTRAST ); maHorHigh.SetModeImage( Image( SVX_RES( IMG_HOR_HIGH_H ) ), BMP_COLOR_HIGHCONTRAST ); maVerDistance.SetModeImage( Image( SVX_RES( IMG_VER_DISTANCE_H ) ), BMP_COLOR_HIGHCONTRAST ); maVerLow.SetModeImage( Image( SVX_RES( IMG_VER_LOW_H ) ), BMP_COLOR_HIGHCONTRAST ); maVerCenter.SetModeImage( Image( SVX_RES( IMG_VER_CENTER_H ) ), BMP_COLOR_HIGHCONTRAST ); maVerHigh.SetModeImage( Image( SVX_RES( IMG_VER_HIGH_H ) ), BMP_COLOR_HIGHCONTRAST ); FreeResource(); } /************************************************************************* |* |* Dtor |* \************************************************************************/ SvxDistributePage::~SvxDistributePage() { } /************************************************************************* |* |* create the tabpage |* \************************************************************************/ SfxTabPage* SvxDistributePage::Create(Window* pWindow, const SfxItemSet& rAttrs, SvxDistributeHorizontal eHor, SvxDistributeVertical eVer) { return(new SvxDistributePage(pWindow, rAttrs, eHor, eVer)); } /************************************************************************* |* |* |* \************************************************************************/ UINT16* SvxDistributePage::GetRanges() { return(pRanges); } /************************************************************************* |* |* |* \************************************************************************/ void SvxDistributePage::PointChanged(Window* /*pWindow*/, RECT_POINT /*eRP*/) { } /************************************************************************* |* |* read the delivered Item-Set |* \************************************************************************/ void __EXPORT SvxDistributePage::Reset(const SfxItemSet& ) { maBtnHorNone.SetState(FALSE); maBtnHorLeft.SetState(FALSE); maBtnHorCenter.SetState(FALSE); maBtnHorDistance.SetState(FALSE); maBtnHorRight.SetState(FALSE); switch(meDistributeHor) { case SvxDistributeHorizontalNone : maBtnHorNone.SetState(TRUE); break; case SvxDistributeHorizontalLeft : maBtnHorLeft.SetState(TRUE); break; case SvxDistributeHorizontalCenter : maBtnHorCenter.SetState(TRUE); break; case SvxDistributeHorizontalDistance : maBtnHorDistance.SetState(TRUE); break; case SvxDistributeHorizontalRight : maBtnHorRight.SetState(TRUE); break; } maBtnVerNone.SetState(FALSE); maBtnVerTop.SetState(FALSE); maBtnVerCenter.SetState(FALSE); maBtnVerDistance.SetState(FALSE); maBtnVerBottom.SetState(FALSE); switch(meDistributeVer) { case SvxDistributeVerticalNone : maBtnVerNone.SetState(TRUE); break; case SvxDistributeVerticalTop : maBtnVerTop.SetState(TRUE); break; case SvxDistributeVerticalCenter : maBtnVerCenter.SetState(TRUE); break; case SvxDistributeVerticalDistance : maBtnVerDistance.SetState(TRUE); break; case SvxDistributeVerticalBottom : maBtnVerBottom.SetState(TRUE); break; } } /************************************************************************* |* |* Fill the delivered Item-Set with dialogbox-attributes |* \************************************************************************/ BOOL SvxDistributePage::FillItemSet( SfxItemSet& ) { SvxDistributeHorizontal eDistributeHor(SvxDistributeHorizontalNone); SvxDistributeVertical eDistributeVer(SvxDistributeVerticalNone); if(maBtnHorLeft.IsChecked()) eDistributeHor = SvxDistributeHorizontalLeft; else if(maBtnHorCenter.IsChecked()) eDistributeHor = SvxDistributeHorizontalCenter; else if(maBtnHorDistance.IsChecked()) eDistributeHor = SvxDistributeHorizontalDistance; else if(maBtnHorRight.IsChecked()) eDistributeHor = SvxDistributeHorizontalRight; if(maBtnVerTop.IsChecked()) eDistributeVer = SvxDistributeVerticalTop; else if(maBtnVerCenter.IsChecked()) eDistributeVer = SvxDistributeVerticalCenter; else if(maBtnVerDistance.IsChecked()) eDistributeVer = SvxDistributeVerticalDistance; else if(maBtnVerBottom.IsChecked()) eDistributeVer = SvxDistributeVerticalBottom; if(eDistributeHor != meDistributeHor || eDistributeVer != meDistributeVer) { meDistributeHor = eDistributeHor; meDistributeVer = eDistributeVer; return TRUE; } return FALSE; } <commit_msg>INTEGRATION: CWS changefileheader (1.11.368); FILE MERGED 2008/04/01 15:50:19 thb 1.11.368.2: #i85898# Stripping all external header guards 2008/03/31 14:19:24 rt 1.11.368.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: dstribut.cxx,v $ * $Revision: 1.12 $ * * 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. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_svx.hxx" #ifdef SVX_DLLIMPLEMENTATION #undef SVX_DLLIMPLEMENTATION #endif #include <sfx2/basedlgs.hxx> #include <svx/dialogs.hrc> #include "dstribut.hxx" #include "dstribut.hrc" #include <svx/svddef.hxx> #include <svx/dialmgr.hxx> #include <tools/shl.hxx> static USHORT pRanges[] = { SDRATTR_MEASURE_FIRST, SDRATTR_MEASURE_LAST, 0 }; /************************************************************************* |* |* Dialog |* \************************************************************************/ SvxDistributeDialog::SvxDistributeDialog( Window* pParent, const SfxItemSet& rInAttrs, SvxDistributeHorizontal eHor, SvxDistributeVertical eVer) : SfxSingleTabDialog(pParent, rInAttrs, RID_SVXPAGE_DISTRIBUTE ), mpPage(0L) { mpPage = new SvxDistributePage(this, rInAttrs, eHor, eVer); SetTabPage(mpPage); SetText(mpPage->GetText()); } /************************************************************************* |* |* Dtor |* \************************************************************************/ SvxDistributeDialog::~SvxDistributeDialog() { } /************************************************************************* |* |* Tabpage |* \************************************************************************/ SvxDistributePage::SvxDistributePage( Window* pWindow, const SfxItemSet& rInAttrs, SvxDistributeHorizontal eHor, SvxDistributeVertical eVer) : SvxTabPage(pWindow, SVX_RES(RID_SVXPAGE_DISTRIBUTE), rInAttrs), meDistributeHor(eHor), meDistributeVer(eVer), maFlHorizontal (this, SVX_RES(FL_HORIZONTAL )), maBtnHorNone (this, SVX_RES(BTN_HOR_NONE )), maBtnHorLeft (this, SVX_RES(BTN_HOR_LEFT )), maBtnHorCenter (this, SVX_RES(BTN_HOR_CENTER )), maBtnHorDistance (this, SVX_RES(BTN_HOR_DISTANCE )), maBtnHorRight (this, SVX_RES(BTN_HOR_RIGHT )), maHorLow (this, SVX_RES(IMG_HOR_LOW )), maHorCenter (this, SVX_RES(IMG_HOR_CENTER )), maHorDistance (this, SVX_RES(IMG_HOR_DISTANCE )), maHorHigh (this, SVX_RES(IMG_HOR_HIGH )), maFlVertical (this, SVX_RES(FL_VERTICAL )), maBtnVerNone (this, SVX_RES(BTN_VER_NONE )), maBtnVerTop (this, SVX_RES(BTN_VER_TOP )), maBtnVerCenter (this, SVX_RES(BTN_VER_CENTER )), maBtnVerDistance (this, SVX_RES(BTN_VER_DISTANCE )), maBtnVerBottom (this, SVX_RES(BTN_VER_BOTTOM )), maVerLow (this, SVX_RES(IMG_VER_LOW )), maVerCenter (this, SVX_RES(IMG_VER_CENTER )), maVerDistance (this, SVX_RES(IMG_VER_DISTANCE )), maVerHigh (this, SVX_RES(IMG_VER_HIGH )) { maHorLow.SetModeImage( Image( SVX_RES( IMG_HOR_LOW_H ) ), BMP_COLOR_HIGHCONTRAST ); maHorCenter.SetModeImage( Image( SVX_RES( IMG_HOR_CENTER_H ) ), BMP_COLOR_HIGHCONTRAST ); maHorDistance.SetModeImage( Image( SVX_RES( IMG_HOR_DISTANCE_H ) ), BMP_COLOR_HIGHCONTRAST ); maHorHigh.SetModeImage( Image( SVX_RES( IMG_HOR_HIGH_H ) ), BMP_COLOR_HIGHCONTRAST ); maVerDistance.SetModeImage( Image( SVX_RES( IMG_VER_DISTANCE_H ) ), BMP_COLOR_HIGHCONTRAST ); maVerLow.SetModeImage( Image( SVX_RES( IMG_VER_LOW_H ) ), BMP_COLOR_HIGHCONTRAST ); maVerCenter.SetModeImage( Image( SVX_RES( IMG_VER_CENTER_H ) ), BMP_COLOR_HIGHCONTRAST ); maVerHigh.SetModeImage( Image( SVX_RES( IMG_VER_HIGH_H ) ), BMP_COLOR_HIGHCONTRAST ); FreeResource(); } /************************************************************************* |* |* Dtor |* \************************************************************************/ SvxDistributePage::~SvxDistributePage() { } /************************************************************************* |* |* create the tabpage |* \************************************************************************/ SfxTabPage* SvxDistributePage::Create(Window* pWindow, const SfxItemSet& rAttrs, SvxDistributeHorizontal eHor, SvxDistributeVertical eVer) { return(new SvxDistributePage(pWindow, rAttrs, eHor, eVer)); } /************************************************************************* |* |* |* \************************************************************************/ UINT16* SvxDistributePage::GetRanges() { return(pRanges); } /************************************************************************* |* |* |* \************************************************************************/ void SvxDistributePage::PointChanged(Window* /*pWindow*/, RECT_POINT /*eRP*/) { } /************************************************************************* |* |* read the delivered Item-Set |* \************************************************************************/ void __EXPORT SvxDistributePage::Reset(const SfxItemSet& ) { maBtnHorNone.SetState(FALSE); maBtnHorLeft.SetState(FALSE); maBtnHorCenter.SetState(FALSE); maBtnHorDistance.SetState(FALSE); maBtnHorRight.SetState(FALSE); switch(meDistributeHor) { case SvxDistributeHorizontalNone : maBtnHorNone.SetState(TRUE); break; case SvxDistributeHorizontalLeft : maBtnHorLeft.SetState(TRUE); break; case SvxDistributeHorizontalCenter : maBtnHorCenter.SetState(TRUE); break; case SvxDistributeHorizontalDistance : maBtnHorDistance.SetState(TRUE); break; case SvxDistributeHorizontalRight : maBtnHorRight.SetState(TRUE); break; } maBtnVerNone.SetState(FALSE); maBtnVerTop.SetState(FALSE); maBtnVerCenter.SetState(FALSE); maBtnVerDistance.SetState(FALSE); maBtnVerBottom.SetState(FALSE); switch(meDistributeVer) { case SvxDistributeVerticalNone : maBtnVerNone.SetState(TRUE); break; case SvxDistributeVerticalTop : maBtnVerTop.SetState(TRUE); break; case SvxDistributeVerticalCenter : maBtnVerCenter.SetState(TRUE); break; case SvxDistributeVerticalDistance : maBtnVerDistance.SetState(TRUE); break; case SvxDistributeVerticalBottom : maBtnVerBottom.SetState(TRUE); break; } } /************************************************************************* |* |* Fill the delivered Item-Set with dialogbox-attributes |* \************************************************************************/ BOOL SvxDistributePage::FillItemSet( SfxItemSet& ) { SvxDistributeHorizontal eDistributeHor(SvxDistributeHorizontalNone); SvxDistributeVertical eDistributeVer(SvxDistributeVerticalNone); if(maBtnHorLeft.IsChecked()) eDistributeHor = SvxDistributeHorizontalLeft; else if(maBtnHorCenter.IsChecked()) eDistributeHor = SvxDistributeHorizontalCenter; else if(maBtnHorDistance.IsChecked()) eDistributeHor = SvxDistributeHorizontalDistance; else if(maBtnHorRight.IsChecked()) eDistributeHor = SvxDistributeHorizontalRight; if(maBtnVerTop.IsChecked()) eDistributeVer = SvxDistributeVerticalTop; else if(maBtnVerCenter.IsChecked()) eDistributeVer = SvxDistributeVerticalCenter; else if(maBtnVerDistance.IsChecked()) eDistributeVer = SvxDistributeVerticalDistance; else if(maBtnVerBottom.IsChecked()) eDistributeVer = SvxDistributeVerticalBottom; if(eDistributeHor != meDistributeHor || eDistributeVer != meDistributeVer) { meDistributeHor = eDistributeHor; meDistributeVer = eDistributeVer; return TRUE; } return FALSE; } <|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$ */ // // Base Class // Produces the data needed to calculate the quality assurance. // All data must be mergeable objects. // Y. Schutz CERN July 2007 // // --- ROOT system --- #include <TROOT.h> #include <TSystem.h> #include <TFile.h> #include <TList.h> #include <TTree.h> #include <TClonesArray.h> #include <TParameter.h> #include <TH1K.h> #include <TH2C.h> #include <TH2D.h> #include <TH2F.h> #include <TH2I.h> #include <TH3C.h> #include <TH3D.h> #include <TH3F.h> #include <TH3I.h> #include <TH3S.h> // --- Standard library --- // --- AliRoot header files --- #include "AliLog.h" #include "AliQADataMaker.h" #include "AliQAChecker.h" #include "AliESDEvent.h" #include "AliRawReader.h" #include "AliDetectorRecoParam.h" ClassImp(AliQADataMaker) //____________________________________________________________________________ AliQADataMaker::AliQADataMaker(const Char_t * name, const Char_t * title) : TNamed(name, title), fOutput(0x0), fDetectorDir(0x0), fDetectorDirName(""), fCurrentCycle(0), fCycle(9999999), fCycleCounter(0), fWriteExpert(kFALSE), fParameterList(new TList*[AliRecoParam::kNSpecies]), fRun(0), fEventSpecie(AliRecoParam::kDefault), fDigitsArray(NULL) { // ctor fDetectorDirName = GetName() ; for (Int_t specie = 0 ; specie < AliRecoParam::kNSpecies ; specie++) { fParameterList[specie] = NULL ; } } //____________________________________________________________________________ AliQADataMaker::AliQADataMaker(const AliQADataMaker& qadm) : TNamed(qadm.GetName(), qadm.GetTitle()), fOutput(qadm.fOutput), fDetectorDir(qadm.fDetectorDir), fDetectorDirName(qadm.fDetectorDirName), fCurrentCycle(qadm.fCurrentCycle), fCycle(qadm.fCycle), fCycleCounter(qadm.fCycleCounter), fWriteExpert(qadm.fWriteExpert), fParameterList(qadm.fParameterList), fRun(qadm.fRun), fEventSpecie(qadm.fEventSpecie), fDigitsArray(NULL) { //copy ctor fDetectorDirName = GetName() ; for (Int_t specie = 0 ; specie < AliRecoParam::kNSpecies ; specie++) { fParameterList[specie] = qadm.fParameterList[specie] ; // fImage[specie] = qadm.fImage[specie] ; } } //____________________________________________________________________________ AliQADataMaker::~AliQADataMaker() { for (Int_t esIndex = 0 ; esIndex < AliRecoParam::kNSpecies ; esIndex++) { if (fParameterList[esIndex] ) delete fParameterList[esIndex] ; } delete[] fParameterList ; if (fDigitsArray) { fDigitsArray->Clear() ; delete fDigitsArray ; } } //____________________________________________________________________________ Int_t AliQADataMaker::Add2List(TH1 * hist, const Int_t index, TObjArray ** list, const Bool_t expert, const Bool_t image, const Bool_t saveForCorr) { // Set histograms memory resident and add to the list // Maximm allowed is 10000 Int_t rv = -1 ; TClass * classType = hist->Class() ; TString className(classType->GetName()) ; if( ! className.BeginsWith("T") && ! classType->InheritsFrom("TH1") ) { AliError(Form("QA data Object must be a generic ROOT object and derive fom TH1 and not %s", className.Data())) ; } else if ( index > AliQAv1::GetMaxQAObj() ) { AliError(Form("Max number of authorized QA objects is %d", AliQAv1::GetMaxQAObj())) ; } else { hist->SetDirectory(0) ; if (expert) hist->SetBit(AliQAv1::GetExpertBit()) ; if (image) hist->SetBit(AliQAv1::GetImageBit()) ; const Char_t * name = Form("%s_%s", AliRecoParam::GetEventSpecieName(fEventSpecie), hist->GetName()) ; hist->SetName(name) ; if(saveForCorr) { const Char_t * cname = Form("%s_%s", list[AliRecoParam::AConvert(AliRecoParam::kDefault)]->GetName(), hist->GetName()) ; TParameter<double> * p = new TParameter<double>(cname, 9999.9999) ; if ( fParameterList[AliRecoParam::AConvert(fEventSpecie)] == NULL ) fParameterList[AliRecoParam::AConvert(fEventSpecie)] = new TList() ; fParameterList[AliRecoParam::AConvert(fEventSpecie)]->Add(p) ; } list[AliRecoParam::AConvert(fEventSpecie)]->AddAtAndExpand(hist, index) ; rv = list[AliRecoParam::AConvert(fEventSpecie)]->GetLast() ; } return rv ; } //____________________________________________________________________________ TH1 * AliQADataMaker::CloneMe(TH1 * hist, Int_t specie) const { // clones a histogram const Char_t * name = Form("%s_%s", AliRecoParam::GetEventSpecieName(specie), hist->GetName()) ; TH1 * hClone = static_cast<TH1 *>(hist->Clone(name)) ; if ( hist->TestBit(AliQAv1::GetExpertBit()) ) hClone->SetBit(AliQAv1::GetExpertBit()) ; if ( hist->TestBit(AliQAv1::GetImageBit()) ) hClone->SetBit(AliQAv1::GetImageBit()) ; return hClone ; } //____________________________________________________________________________ void AliQADataMaker::DefaultEndOfDetectorCycle(AliQAv1::TASKINDEX_t task) { // this method must be oveloaded by detectors // sets the QA result to Fatal AliQAv1::Instance(AliQAv1::GetDetIndex(GetName())) ; AliQAv1 * qa = AliQAv1::Instance(task) ; for (Int_t specie = 0 ; specie < AliRecoParam::kNSpecies ; specie++) qa->Set(AliQAv1::kFATAL, specie) ; AliQAv1::GetQAResultFile()->cd() ; qa->Write(AliQAv1::GetQAName(), kWriteDelete) ; AliQAv1::GetQAResultFile()->Close() ; } //____________________________________________________________________________ void AliQADataMaker::Finish() const { // write to the output File if (fOutput) fOutput->Close() ; } //____________________________________________________________________________ TObject * AliQADataMaker::GetData(TObjArray ** list, const Int_t index) { // Returns the QA object at index. Limit is AliQAv1::GetMaxQAObj() if ( ! list ) { AliError("Data list is NULL !!") ; return NULL ; } SetEventSpecie(fEventSpecie) ; Int_t esindex = AliRecoParam::AConvert(fEventSpecie) ; TH1 * histClone = NULL ; TObjArray * arr = list[esindex] ; if (arr) { if ( ! arr->GetEntriesFast() ) { // Initializes the histograms TString arrName(arr->GetName()) ; if (arrName.Contains(AliQAv1::GetTaskName(AliQAv1::kRAWS))) InitRaws() ; else if (arrName.Contains(AliQAv1::GetTaskName(AliQAv1::kHITS))) InitHits() ; else if (arrName.Contains(AliQAv1::GetTaskName(AliQAv1::kSDIGITS))) InitSDigits() ; else if (arrName.Contains(AliQAv1::GetTaskName(AliQAv1::kDIGITS))) InitDigits() ; else if (arrName.Contains(AliQAv1::GetTaskName(AliQAv1::kDIGITSR))) InitDigits() ; else if (arrName.Contains(AliQAv1::GetTaskName(AliQAv1::kRECPOINTS))) InitRecPoints() ; else if (arrName.Contains(AliQAv1::GetTaskName(AliQAv1::kESDS))) InitESDs() ; } if ( index > AliQAv1::GetMaxQAObj() ) { AliError(Form("Max number of authorized QA objects is %d", AliQAv1::GetMaxQAObj())) ; } else { if ( arr->At(index) ) { histClone = static_cast<TH1*>(arr->At(index)) ; } } } return histClone ; } //____________________________________________________________________________ TObjArray* AliQADataMaker::Init(AliQAv1::TASKINDEX_t task, AliRecoParam::EventSpecie_t es, Int_t cycles) { // Initialializes and returns the QAData list for a given event specie TObjArray ** ar = Init(task, cycles) ; return ar[AliRecoParam::AConvert(es)] ; } //____________________________________________________________________________ Bool_t AliQADataMaker::IsValidEventSpecie(Int_t eventSpecieIndex, TObjArray ** list) { // check if event specie was present in current run or // if histograms of this event specie have been created if (! AliQAv1::Instance(AliQAv1::GetDetIndex(GetName()))->IsEventSpecieSet(AliRecoParam::ConvertIndex(eventSpecieIndex)) || ! list[eventSpecieIndex]->GetEntriesFast() ) return kFALSE ; else return kTRUE ; } <commit_msg>https://savannah.cern.ch/bugs/index.php?72621<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$ */ // // Base Class // Produces the data needed to calculate the quality assurance. // All data must be mergeable objects. // Y. Schutz CERN July 2007 // // --- ROOT system --- #include <TROOT.h> #include <TSystem.h> #include <TFile.h> #include <TList.h> #include <TTree.h> #include <TClonesArray.h> #include <TParameter.h> #include <TH1K.h> #include <TH2C.h> #include <TH2D.h> #include <TH2F.h> #include <TH2I.h> #include <TH3C.h> #include <TH3D.h> #include <TH3F.h> #include <TH3I.h> #include <TH3S.h> // --- Standard library --- // --- AliRoot header files --- #include "AliLog.h" #include "AliQADataMaker.h" #include "AliQAChecker.h" #include "AliESDEvent.h" #include "AliRawReader.h" #include "AliDetectorRecoParam.h" ClassImp(AliQADataMaker) //____________________________________________________________________________ AliQADataMaker::AliQADataMaker(const Char_t * name, const Char_t * title) : TNamed(name, title), fOutput(0x0), fDetectorDir(0x0), fDetectorDirName(""), fCurrentCycle(0), fCycle(9999999), fCycleCounter(0), fWriteExpert(kFALSE), fParameterList(new TList*[AliRecoParam::kNSpecies]), fRun(0), fEventSpecie(AliRecoParam::kDefault), fDigitsArray(NULL) { // ctor fDetectorDirName = GetName() ; for (Int_t specie = 0 ; specie < AliRecoParam::kNSpecies ; specie++) { fParameterList[specie] = NULL ; } } //____________________________________________________________________________ AliQADataMaker::AliQADataMaker(const AliQADataMaker& qadm) : TNamed(qadm.GetName(), qadm.GetTitle()), fOutput(qadm.fOutput), fDetectorDir(qadm.fDetectorDir), fDetectorDirName(qadm.fDetectorDirName), fCurrentCycle(qadm.fCurrentCycle), fCycle(qadm.fCycle), fCycleCounter(qadm.fCycleCounter), fWriteExpert(qadm.fWriteExpert), fParameterList(qadm.fParameterList), fRun(qadm.fRun), fEventSpecie(qadm.fEventSpecie), fDigitsArray(NULL) { //copy ctor fDetectorDirName = GetName() ; for (Int_t specie = 0 ; specie < AliRecoParam::kNSpecies ; specie++) { fParameterList[specie] = qadm.fParameterList[specie] ; // fImage[specie] = qadm.fImage[specie] ; } } //____________________________________________________________________________ AliQADataMaker::~AliQADataMaker() { for (Int_t esIndex = 0 ; esIndex < AliRecoParam::kNSpecies ; esIndex++) { if (fParameterList[esIndex] ) delete fParameterList[esIndex] ; } delete[] fParameterList ; if (fDigitsArray) { fDigitsArray->Clear() ; delete fDigitsArray ; } } //____________________________________________________________________________ Int_t AliQADataMaker::Add2List(TH1 * hist, const Int_t index, TObjArray ** list, const Bool_t expert, const Bool_t image, const Bool_t saveForCorr) { // Set histograms memory resident and add to the list // Maximm allowed is 10000 Int_t rv = -1 ; TClass * classType = hist->Class() ; TString className(classType->GetName()) ; if( ! className.BeginsWith("T") && ! classType->InheritsFrom("TH1") ) { AliError(Form("QA data Object must be a generic ROOT object and derive fom TH1 and not %s", className.Data())) ; } else if ( index > AliQAv1::GetMaxQAObj() ) { AliError(Form("Max number of authorized QA objects is %d", AliQAv1::GetMaxQAObj())) ; } else { hist->SetDirectory(0) ; if (expert) hist->SetBit(AliQAv1::GetExpertBit()) ; if (image) hist->SetBit(AliQAv1::GetImageBit()) ; const Char_t * name = Form("%s_%s", AliRecoParam::GetEventSpecieName(fEventSpecie), hist->GetName()) ; hist->SetName(name) ; if(saveForCorr) { const Char_t * cname = Form("%s_%s", list[AliRecoParam::AConvert(AliRecoParam::kDefault)]->GetName(), hist->GetName()) ; TParameter<double> * p = new TParameter<double>(cname, 9999.9999) ; if ( fParameterList[AliRecoParam::AConvert(fEventSpecie)] == NULL ) fParameterList[AliRecoParam::AConvert(fEventSpecie)] = new TList() ; fParameterList[AliRecoParam::AConvert(fEventSpecie)]->Add(p) ; } TObject* old = list[AliRecoParam::AConvert(fEventSpecie)]->At(index); if (old) { AliError(Form("%s - OUPS ! Already got an object (%p,%s) for index=%d => will most probably get a memory leak by replacing it with (%p,%s) !", GetName(),old,old->GetName(),index,hist,hist->GetName())); } list[AliRecoParam::AConvert(fEventSpecie)]->AddAtAndExpand(hist, index) ; rv = list[AliRecoParam::AConvert(fEventSpecie)]->GetLast() ; } return rv ; } //____________________________________________________________________________ TH1 * AliQADataMaker::CloneMe(TH1 * hist, Int_t specie) const { // clones a histogram const Char_t * name = Form("%s_%s", AliRecoParam::GetEventSpecieName(specie), hist->GetName()) ; TH1 * hClone = static_cast<TH1 *>(hist->Clone(name)) ; if ( hist->TestBit(AliQAv1::GetExpertBit()) ) hClone->SetBit(AliQAv1::GetExpertBit()) ; if ( hist->TestBit(AliQAv1::GetImageBit()) ) hClone->SetBit(AliQAv1::GetImageBit()) ; return hClone ; } //____________________________________________________________________________ void AliQADataMaker::DefaultEndOfDetectorCycle(AliQAv1::TASKINDEX_t task) { // this method must be oveloaded by detectors // sets the QA result to Fatal AliQAv1::Instance(AliQAv1::GetDetIndex(GetName())) ; AliQAv1 * qa = AliQAv1::Instance(task) ; for (Int_t specie = 0 ; specie < AliRecoParam::kNSpecies ; specie++) qa->Set(AliQAv1::kFATAL, specie) ; AliQAv1::GetQAResultFile()->cd() ; qa->Write(AliQAv1::GetQAName(), kWriteDelete) ; AliQAv1::GetQAResultFile()->Close() ; } //____________________________________________________________________________ void AliQADataMaker::Finish() const { // write to the output File if (fOutput) fOutput->Close() ; } //____________________________________________________________________________ TObject * AliQADataMaker::GetData(TObjArray ** list, const Int_t index) { // Returns the QA object at index. Limit is AliQAv1::GetMaxQAObj() if ( ! list ) { AliError("Data list is NULL !!") ; return NULL ; } SetEventSpecie(fEventSpecie) ; Int_t esindex = AliRecoParam::AConvert(fEventSpecie) ; TH1 * histClone = NULL ; TObjArray * arr = list[esindex] ; if (arr) { if ( ! arr->GetEntriesFast() ) { // Initializes the histograms TString arrName(arr->GetName()) ; if (arrName.Contains(AliQAv1::GetTaskName(AliQAv1::kRAWS))) InitRaws() ; else if (arrName.Contains(AliQAv1::GetTaskName(AliQAv1::kHITS))) InitHits() ; else if (arrName.Contains(AliQAv1::GetTaskName(AliQAv1::kSDIGITS))) InitSDigits() ; else if (arrName.Contains(AliQAv1::GetTaskName(AliQAv1::kDIGITS))) InitDigits() ; else if (arrName.Contains(AliQAv1::GetTaskName(AliQAv1::kDIGITSR))) InitDigits() ; else if (arrName.Contains(AliQAv1::GetTaskName(AliQAv1::kRECPOINTS))) InitRecPoints() ; else if (arrName.Contains(AliQAv1::GetTaskName(AliQAv1::kESDS))) InitESDs() ; } if ( index > AliQAv1::GetMaxQAObj() ) { AliError(Form("Max number of authorized QA objects is %d", AliQAv1::GetMaxQAObj())) ; } else { if ( arr->At(index) ) { histClone = static_cast<TH1*>(arr->At(index)) ; } } } return histClone ; } //____________________________________________________________________________ TObjArray* AliQADataMaker::Init(AliQAv1::TASKINDEX_t task, AliRecoParam::EventSpecie_t es, Int_t cycles) { // Initialializes and returns the QAData list for a given event specie TObjArray ** ar = Init(task, cycles) ; return ar[AliRecoParam::AConvert(es)] ; } //____________________________________________________________________________ Bool_t AliQADataMaker::IsValidEventSpecie(Int_t eventSpecieIndex, TObjArray ** list) { // check if event specie was present in current run or // if histograms of this event specie have been created if (! AliQAv1::Instance(AliQAv1::GetDetIndex(GetName()))->IsEventSpecieSet(AliRecoParam::ConvertIndex(eventSpecieIndex)) || ! list[eventSpecieIndex]->GetEntriesFast() ) return kFALSE ; else return kTRUE ; } <|endoftext|>
<commit_before>#ifndef ALGORITHM #define ALGORITHM #include<algorithm> //find_if, remove_if #include<cstddef> //ptrdiff_t #include<functional> //equal_to #include<iterator> //iterator_traits, next namespace nAlgorithm { template<class T,class UnaryPred> bool all_of_val(T begin,const T end,const UnaryPred pred) { while(begin!=end) { if(!pred(begin)) return false; ++begin; } return true; } template<class T,class UnaryPred> T find_if_val(T begin,const T end,const UnaryPred pred) { while(begin!=end) { if(pred(begin)) return begin; ++begin; } return end; } template<class T,class UnaryPred> inline bool any_of_val(const T begin,const T end,const UnaryPred pred) { return find_if_val(begin,end,pred)!=end; } template<class T,class UnaryPred> std::ptrdiff_t count_if_val(T begin,const T end,const UnaryPred pred) { std::ptrdiff_t accu{0}; while(begin!=end) { if(pred(begin)) ++accu; ++begin; } return accu; } template<class T,class UnaryFunc> UnaryFunc for_each_val(T begin,const T end,UnaryFunc func) { while(begin!=end) { func(begin); ++begin; } return func; } template<class InIter,class UnaryPred,class UnaryFunc> void loop_until_none_of(const InIter begin,const InIter end,const UnaryPred pred,const UnaryFunc func) { for(InIter iter;(iter=std::find_if(begin,end,pred))!=end;) func(*iter); } template<class InIter,class OutIter,class BinaryOp> void multiply(InIter lbegin,const InIter lend,const InIter rbegin,const InIter rend,OutIter des,const BinaryOp op) { while(lbegin!=lend) { for(auto begin{rbegin};begin!=rend;++begin,++des) *des=op(*lbegin,*begin); ++lbegin; } } //unique_without_sort will reorder the input permutation. template<class FwdIter,class BinaryPred=std::equal_to<typename std::iterator_traits<FwdIter>::value_type>> FwdIter unique_without_sort(FwdIter begin,FwdIter end,const BinaryPred pred=BinaryPred()) { while(begin!=end) { end=std::remove_if(std::next(begin),end,[&begin=*begin,pred](auto &&val){ return pred(begin,std::forward<decltype(val)>(val)); }); ++begin; } return end; } } #endif<commit_msg>fix for_each_val<commit_after>#ifndef ALGORITHM #define ALGORITHM #include<algorithm> //find_if, remove_if #include<cstddef> //ptrdiff_t #include<functional> //equal_to #include<iterator> //iterator_traits, next #include<utility> //move namespace nAlgorithm { template<class T,class UnaryPred> bool all_of_val(T begin,const T end,const UnaryPred pred) { while(begin!=end) { if(!pred(begin)) return false; ++begin; } return true; } template<class T,class UnaryPred> T find_if_val(T begin,const T end,const UnaryPred pred) { while(begin!=end) { if(pred(begin)) return begin; ++begin; } return end; } template<class T,class UnaryPred> inline bool any_of_val(const T begin,const T end,const UnaryPred pred) { return find_if_val(begin,end,pred)!=end; } template<class T,class UnaryPred> std::ptrdiff_t count_if_val(T begin,const T end,const UnaryPred pred) { std::ptrdiff_t accu{0}; while(begin!=end) { if(pred(begin)) ++accu; ++begin; } return accu; } template<class T,class UnaryFunc> UnaryFunc for_each_val(T begin,const T end,UnaryFunc func) { while(begin!=end) { func(begin); ++begin; } return std::move(func); } template<class InIter,class UnaryPred,class UnaryFunc> void loop_until_none_of(const InIter begin,const InIter end,const UnaryPred pred,const UnaryFunc func) { for(InIter iter;(iter=std::find_if(begin,end,pred))!=end;) func(*iter); } template<class InIter,class OutIter,class BinaryOp> void multiply(InIter lbegin,const InIter lend,const InIter rbegin,const InIter rend,OutIter des,const BinaryOp op) { while(lbegin!=lend) { for(auto begin{rbegin};begin!=rend;++begin,++des) *des=op(*lbegin,*begin); ++lbegin; } } //unique_without_sort will reorder the input permutation. template<class FwdIter,class BinaryPred=std::equal_to<typename std::iterator_traits<FwdIter>::value_type>> FwdIter unique_without_sort(FwdIter begin,FwdIter end,const BinaryPred pred=BinaryPred()) { while(begin!=end) { end=std::remove_if(std::next(begin),end,[&begin=*begin,pred](auto &&val){ return pred(begin,std::forward<decltype(val)>(val)); }); ++begin; } return end; } } #endif<|endoftext|>
<commit_before>#include <semaphore.h> #include <fcntl.h> #include <sys/stat.h> #include <mist/defines.h> #include "input.h" #include <sstream> #include <fstream> #include <iterator> namespace Mist { Input * Input::singleton = NULL; void Input::userCallback(char * data, size_t len, unsigned int id){ for (int i = 0; i < 5; i++){ long tid = ((long)(data[i*6]) << 24) | ((long)(data[i*6+1]) << 16) | ((long)(data[i*6+2]) << 8) | ((long)(data[i*6+3])); if (tid){ long keyNum = ((long)(data[i*6+4]) << 8) | ((long)(data[i*6+5])); bufferFrame(tid, keyNum + 1);//Try buffer next frame } } } void Input::doNothing(char * data, size_t len, unsigned int id){ DEBUG_MSG(DLVL_DONTEVEN, "Doing 'nothing'"); singleton->userCallback(data, 30, id);//call the userCallback for this input } Input::Input(Util::Config * cfg) { config = cfg; JSON::Value option; option["long"] = "json"; option["short"] = "j"; option["help"] = "Output MistIn info in JSON format, then exit."; option["value"].append(0ll); config->addOption("json", option); option.null(); option["arg_num"] = 1ll; option["arg"] = "string"; option["help"] = "Name of the input file or - for stdin"; option["value"].append("-"); config->addOption("input", option); option.null(); option["arg_num"] = 2ll; option["arg"] = "string"; option["help"] = "Name of the output file or - for stdout"; option["value"].append("-"); config->addOption("output", option); option.null(); option["arg"] = "string"; option["short"] = "s"; option["long"] = "stream"; option["help"] = "The name of the stream that this connector will transmit."; config->addOption("streamname", option); option.null(); option["short"] = "p"; option["long"] = "player"; option["help"] = "Makes this connector into a player"; config->addOption("player", option); packTime = 0; lastActive = Util::epoch(); playing = 0; playUntil = 0; singleton = this; isBuffer = false; } void Input::checkHeaderTimes(std::string streamFile){ if ( streamFile == "-" ){ return; } std::string headerFile = streamFile + ".dtsh"; FILE * tmp = fopen(headerFile.c_str(),"r"); if (tmp == NULL) { INFO_MSG("can't open file: %s (no header times compared, nothing removed)", headerFile.c_str() ); return; } struct stat bufStream; struct stat bufHeader; //fstat(fileno(streamFile), &bufStream); //fstat(fileno(tmp), &bufHeader); if (stat(streamFile.c_str(), &bufStream) !=0 || stat(headerFile.c_str(), &bufHeader) !=0){ ERROR_MSG("could not get file info (no header times compared, nothing removed)"); fclose(tmp); return; } int timeStream = bufStream.st_mtime; int timeHeader = bufHeader.st_mtime; fclose(tmp); INFO_MSG("time header: %i time stream: %i ", timeHeader, timeStream); if (timeHeader < timeStream) { INFO_MSG("removing old header file: %s ",headerFile.c_str()); //delete filename remove(headerFile.c_str()); } } int Input::run() { if (config->getBool("json")) { std::cerr << capa.toString() << std::endl; return 0; } if (!setup()) { std::cerr << config->getString("cmd") << " setup failed." << std::endl; return 0; } checkHeaderTimes(config->getString("input")); if (!readHeader()) { std::cerr << "Reading header for " << config->getString("input") << " failed." << std::endl; return 0; } parseHeader(); if (!config->getBool("player")){ //check filename for no - if (config->getString("output") != "-"){ std::string filename = config->getString("output"); if (filename.size() < 5 || filename.substr(filename.size() - 5) != ".dtsc"){ filename += ".dtsc"; } //output to dtsc DTSC::Meta newMeta = myMeta; newMeta.reset(); JSON::Value tempVal; std::ofstream file(filename.c_str()); long long int bpos = 0; seek(0); getNext(); while (lastPack){ tempVal = lastPack.toJSON(); tempVal["bpos"] = bpos; newMeta.update(tempVal); file << std::string(lastPack.getData(), lastPack.getDataLen()); bpos += lastPack.getDataLen(); getNext(); } //close file file.close(); //create header file.open((filename+".dtsh").c_str()); file << newMeta.toJSON().toNetPacked(); file.close(); }else{ DEBUG_MSG(DLVL_FAIL,"No filename specified, exiting"); } }else{ //after this player functionality #ifdef __CYGWIN__ metaPage.init(config->getString("streamname"), 8 * 1024 * 1024, true); #else metaPage.init(config->getString("streamname"), (isBuffer ? 8 * 1024 * 1024 : myMeta.getSendLen()), true); #endif myMeta.writeTo(metaPage.mapped); userPage.init(config->getString("streamname") + "_users", 30, true); if (!isBuffer){ for (std::map<int,DTSC::Track>::iterator it = myMeta.tracks.begin(); it != myMeta.tracks.end(); it++){ bufferFrame(it->first, 1); } } DEBUG_MSG(DLVL_DONTEVEN,"Pre-While"); long long int activityCounter = Util::bootSecs(); while ((Util::getMS() - activityCounter) < 10){//10 second timeout DEBUG_MSG(DLVL_INSANE, "Timer running"); Util::wait(1000); removeUnused(); userPage.parseEach(doNothing); if (userPage.amount){ activityCounter = Util::bootSecs(); DEBUG_MSG(DLVL_HIGH, "Connected users: %d", userPage.amount); } } DEBUG_MSG(DLVL_DEVEL,"Closing clean"); //end player functionality } return 0; } void Input::removeUnused(){ for (std::map<unsigned int, std::map<unsigned int, unsigned int> >::iterator it = pageCounter.begin(); it != pageCounter.end(); it++){ for (std::map<unsigned int, unsigned int>::iterator it2 = it->second.begin(); it2 != it->second.end(); it2++){ it2->second--; } bool change = true; while (change){ change = false; for (std::map<unsigned int, unsigned int>::iterator it2 = it->second.begin(); it2 != it->second.end(); it2++){ if (!it2->second){ dataPages[it->first].erase(it2->first); pageCounter[it->first].erase(it2->first); change = true; break; } } } } } void Input::parseHeader(){ DEBUG_MSG(DLVL_DONTEVEN,"Parsing the header"); //Select all tracks for parsing header selectedTracks.clear(); std::stringstream trackSpec; for (std::map<int, DTSC::Track>::iterator it = myMeta.tracks.begin(); it != myMeta.tracks.end(); it++) { DEBUG_MSG(DLVL_VERYHIGH, "Track %d encountered", it->first); if (trackSpec.str() != ""){ trackSpec << " "; } trackSpec << it->first; DEBUG_MSG(DLVL_VERYHIGH, "Trackspec now %s", trackSpec.str().c_str()); for (std::deque<DTSC::Key>::iterator it2 = it->second.keys.begin(); it2 != it->second.keys.end(); it2++){ keyTimes[it->first].insert(it2->getTime()); } } trackSelect(trackSpec.str()); std::map<int, DTSCPageData> curData; std::map<int, booking> bookKeeping; seek(0); getNext(); while(lastPack){//loop through all int tid = lastPack.getTrackId(); if (!tid){ getNext(false); continue; } if (!bookKeeping.count(tid)){ bookKeeping[tid].first = 1; bookKeeping[tid].curPart = 0; bookKeeping[tid].curKey = 0; curData[tid].lastKeyTime = 0xFFFFFFFF; curData[tid].keyNum = 1; curData[tid].partNum = 0; curData[tid].dataSize = 0; curData[tid].curOffset = 0; curData[tid].firstTime = myMeta.tracks[tid].keys[0].getTime(); char tmpId[20]; sprintf(tmpId, "%d", tid); indexPages[tid].init(config->getString("streamname") + tmpId, 8 * 1024, true);//Pages of 8kb in size, room for 512 parts. } if (myMeta.tracks[tid].keys[bookKeeping[tid].curKey].getParts() == curData[tid].partNum){ if (curData[tid].dataSize > 8 * 1024 * 1024) { pagesByTrack[tid][bookKeeping[tid].first] = curData[tid]; bookKeeping[tid].first += curData[tid].keyNum; curData[tid].keyNum = 0; curData[tid].dataSize = 0; curData[tid].firstTime = myMeta.tracks[tid].keys[bookKeeping[tid].curKey].getTime(); } bookKeeping[tid].curKey++; curData[tid].keyNum++; curData[tid].partNum = 0; } curData[tid].dataSize += lastPack.getDataLen(); curData[tid].partNum ++; bookKeeping[tid].curPart ++; getNext(false); } for (std::map<int, DTSC::Track>::iterator it = myMeta.tracks.begin(); it != myMeta.tracks.end(); it++) { if (curData.count(it->first) && !pagesByTrack[it->first].count(bookKeeping[it->first].first)){ pagesByTrack[it->first][bookKeeping[it->first].first] = curData[it->first]; } if (!pagesByTrack.count(it->first)){ DEBUG_MSG(DLVL_WARN, "No pages for track %d found", it->first); }else{ DEBUG_MSG(DLVL_DEVEL, "Track %d (%s) split into %lu pages", it->first, myMeta.tracks[it->first].codec.c_str(), pagesByTrack[it->first].size()); for (std::map<int, DTSCPageData>::iterator it2 = pagesByTrack[it->first].begin(); it2 != pagesByTrack[it->first].end(); it2++){ DEBUG_MSG(DLVL_DEVEL, "Page %u-%u", it2->first, it2->first + it2->second.keyNum - 1); } } } } bool Input::bufferFrame(int track, int keyNum){ if (keyNum < 1){keyNum = 1;} if (!pagesByTrack.count(track)){ return false; } std::map<int, DTSCPageData>::iterator it = pagesByTrack[track].upper_bound(keyNum); if (it != pagesByTrack[track].begin()){ it--; } int pageNum = it->first; pageCounter[track][pageNum] = 15;///Keep page 15seconds in memory after last use DEBUG_MSG(DLVL_DONTEVEN, "Attempting to buffer page %d key %d->%d", track, keyNum, pageNum); if (dataPages[track].count(pageNum)){ return true; } char pageId[100]; int pageIdLen = sprintf(pageId, "%s%d_%d", config->getString("streamname").c_str(), track, pageNum); std::string tmpString(pageId, pageIdLen); #ifdef __CYGWIN__ dataPages[track][pageNum].init(tmpString, 26 * 1024 * 1024, true); #else dataPages[track][pageNum].init(tmpString, it->second.dataSize, true); #endif DEBUG_MSG(DLVL_DEVEL, "Buffering track %d page %d through %d", track, pageNum, pageNum-1 + it->second.keyNum); std::stringstream trackSpec; trackSpec << track; trackSelect(trackSpec.str()); seek(myMeta.tracks[track].keys[pageNum-1].getTime()); long long unsigned int stopTime = myMeta.tracks[track].lastms + 1; if ((int)myMeta.tracks[track].keys.size() > pageNum-1 + it->second.keyNum){ stopTime = myMeta.tracks[track].keys[pageNum-1 + it->second.keyNum].getTime(); } DEBUG_MSG(DLVL_HIGH, "Playing from %ld to %llu", myMeta.tracks[track].keys[pageNum-1].getTime(), stopTime); it->second.curOffset = 0; getNext(); //in case earlier seeking was inprecise, seek to the exact point while (lastPack && lastPack.getTime() < (unsigned long long)myMeta.tracks[track].keys[pageNum-1].getTime()){ getNext(); } while (lastPack && lastPack.getTime() < stopTime){ if (it->second.curOffset + lastPack.getDataLen() > pagesByTrack[track][pageNum].dataSize){ DEBUG_MSG(DLVL_WARN, "Trying to write %u bytes on pos %llu where size is %llu (time: %llu / %llu, track %u page %u)", lastPack.getDataLen(), it->second.curOffset, pagesByTrack[track][pageNum].dataSize, lastPack.getTime(), stopTime, track, pageNum); break; }else{ memcpy(dataPages[track][pageNum].mapped + it->second.curOffset, lastPack.getData(), lastPack.getDataLen()); it->second.curOffset += lastPack.getDataLen(); } getNext(); } for (int i = 0; i < indexPages[track].len / 8; i++){ if (((long long int*)indexPages[track].mapped)[i] == 0){ ((long long int*)indexPages[track].mapped)[i] = (((long long int)htonl(pageNum)) << 32) | htonl(it->second.keyNum); break; } } DEBUG_MSG(DLVL_DEVEL, "Done buffering page %d for track %d", pageNum, track); return true; } bool Input::atKeyFrame(){ static std::map<int, unsigned long long> lastSeen; //not in keyTimes? We're not at a keyframe. unsigned int c = keyTimes[lastPack.getTrackId()].count(lastPack.getTime()); if (!c){ return false; } //skip double times if (lastSeen.count(lastPack.getTrackId()) && lastSeen[lastPack.getTrackId()] == lastPack.getTime()){ return false; } //set last seen, and return true lastSeen[lastPack.getTrackId()] = lastPack.getTime(); return true; } void Input::play(int until) { playing = -1; playUntil = until; initialTime = 0; benchMark = Util::getMS(); } void Input::playOnce() { if (playing <= 0) { playing = 1; } ++playing; benchMark = Util::getMS(); } void Input::quitPlay() { playing = 0; } } <commit_msg>Various tweaks and fixes to all MistIn processes.<commit_after>#include <semaphore.h> #include <fcntl.h> #include <sys/stat.h> #include <mist/defines.h> #include "input.h" #include <sstream> #include <fstream> #include <iterator> namespace Mist { Input * Input::singleton = NULL; void Input::userCallback(char * data, size_t len, unsigned int id){ for (int i = 0; i < 5; i++){ long tid = ((long)(data[i*6]) << 24) | ((long)(data[i*6+1]) << 16) | ((long)(data[i*6+2]) << 8) | ((long)(data[i*6+3])); if (tid){ long keyNum = ((long)(data[i*6+4]) << 8) | ((long)(data[i*6+5])); bufferFrame(tid, keyNum + 1);//Try buffer next frame } } } void Input::doNothing(char * data, size_t len, unsigned int id){ DEBUG_MSG(DLVL_DONTEVEN, "Doing 'nothing'"); singleton->userCallback(data, 30, id);//call the userCallback for this input } Input::Input(Util::Config * cfg) { config = cfg; JSON::Value option; option["long"] = "json"; option["short"] = "j"; option["help"] = "Output MistIn info in JSON format, then exit."; option["value"].append(0ll); config->addOption("json", option); option.null(); option["arg_num"] = 1ll; option["arg"] = "string"; option["help"] = "Name of the input file or - for stdin"; option["value"].append("-"); config->addOption("input", option); option.null(); option["arg_num"] = 2ll; option["arg"] = "string"; option["help"] = "Name of the output file or - for stdout"; option["value"].append("-"); config->addOption("output", option); option.null(); option["arg"] = "string"; option["short"] = "s"; option["long"] = "stream"; option["help"] = "The name of the stream that this connector will transmit."; config->addOption("streamname", option); option.null(); option["short"] = "p"; option["long"] = "player"; option["help"] = "Makes this connector into a player"; config->addOption("player", option); packTime = 0; lastActive = Util::epoch(); playing = 0; playUntil = 0; singleton = this; isBuffer = false; } void Input::checkHeaderTimes(std::string streamFile){ if ( streamFile == "-" ){ return; } std::string headerFile = streamFile + ".dtsh"; FILE * tmp = fopen(headerFile.c_str(),"r"); if (tmp == NULL) { DEBUG_MSG(DLVL_HIGH, "Can't open header: %s. Assuming all is fine.", headerFile.c_str() ); return; } struct stat bufStream; struct stat bufHeader; //fstat(fileno(streamFile), &bufStream); //fstat(fileno(tmp), &bufHeader); if (stat(streamFile.c_str(), &bufStream) !=0 || stat(headerFile.c_str(), &bufHeader) !=0){ DEBUG_MSG(DLVL_HIGH, "Could not compare stream and header timestamps - assuming all is fine."); fclose(tmp); return; } int timeStream = bufStream.st_mtime; int timeHeader = bufHeader.st_mtime; fclose(tmp); if (timeHeader < timeStream) { //delete filename INFO_MSG("Overwriting outdated DTSH header file: %s ",headerFile.c_str()); remove(headerFile.c_str()); } } int Input::run() { if (config->getBool("json")) { std::cerr << capa.toString() << std::endl; return 0; } if (!setup()) { std::cerr << config->getString("cmd") << " setup failed." << std::endl; return 0; } checkHeaderTimes(config->getString("input")); if (!readHeader()) { std::cerr << "Reading header for " << config->getString("input") << " failed." << std::endl; return 0; } parseHeader(); if (!config->getBool("player")){ //check filename for no - if (config->getString("output") != "-"){ std::string filename = config->getString("output"); if (filename.size() < 5 || filename.substr(filename.size() - 5) != ".dtsc"){ filename += ".dtsc"; } //output to dtsc DTSC::Meta newMeta = myMeta; newMeta.reset(); JSON::Value tempVal; std::ofstream file(filename.c_str()); long long int bpos = 0; seek(0); getNext(); while (lastPack){ tempVal = lastPack.toJSON(); tempVal["bpos"] = bpos; newMeta.update(tempVal); file << std::string(lastPack.getData(), lastPack.getDataLen()); bpos += lastPack.getDataLen(); getNext(); } //close file file.close(); //create header file.open((filename+".dtsh").c_str()); file << newMeta.toJSON().toNetPacked(); file.close(); }else{ DEBUG_MSG(DLVL_FAIL,"No filename specified, exiting"); } }else{ //after this player functionality #ifdef __CYGWIN__ metaPage.init(config->getString("streamname"), 8 * 1024 * 1024, true); #else metaPage.init(config->getString("streamname"), (isBuffer ? 8 * 1024 * 1024 : myMeta.getSendLen()), true); #endif myMeta.writeTo(metaPage.mapped); userPage.init(config->getString("streamname") + "_users", 30, true); if (!isBuffer){ for (std::map<int,DTSC::Track>::iterator it = myMeta.tracks.begin(); it != myMeta.tracks.end(); it++){ bufferFrame(it->first, 1); } } DEBUG_MSG(DLVL_DONTEVEN,"Pre-While"); long long int activityCounter = Util::bootSecs(); while ((Util::bootSecs() - activityCounter) < 10){//10 second timeout Util::wait(1000); removeUnused(); userPage.parseEach(doNothing); if (userPage.amount){ activityCounter = Util::bootSecs(); DEBUG_MSG(DLVL_INSANE, "Connected users: %d", userPage.amount); }else{ DEBUG_MSG(DLVL_INSANE, "Timer running"); } } DEBUG_MSG(DLVL_DEVEL,"Closing clean"); //end player functionality } return 0; } void Input::removeUnused(){ for (std::map<unsigned int, std::map<unsigned int, unsigned int> >::iterator it = pageCounter.begin(); it != pageCounter.end(); it++){ for (std::map<unsigned int, unsigned int>::iterator it2 = it->second.begin(); it2 != it->second.end(); it2++){ it2->second--; } bool change = true; while (change){ change = false; for (std::map<unsigned int, unsigned int>::iterator it2 = it->second.begin(); it2 != it->second.end(); it2++){ if (!it2->second){ dataPages[it->first].erase(it2->first); pageCounter[it->first].erase(it2->first); change = true; break; } } } } } void Input::parseHeader(){ DEBUG_MSG(DLVL_DONTEVEN,"Parsing the header"); //Select all tracks for parsing header selectedTracks.clear(); std::stringstream trackSpec; for (std::map<int, DTSC::Track>::iterator it = myMeta.tracks.begin(); it != myMeta.tracks.end(); it++) { DEBUG_MSG(DLVL_VERYHIGH, "Track %d encountered", it->first); if (trackSpec.str() != ""){ trackSpec << " "; } trackSpec << it->first; DEBUG_MSG(DLVL_VERYHIGH, "Trackspec now %s", trackSpec.str().c_str()); for (std::deque<DTSC::Key>::iterator it2 = it->second.keys.begin(); it2 != it->second.keys.end(); it2++){ keyTimes[it->first].insert(it2->getTime()); } } trackSelect(trackSpec.str()); std::map<int, DTSCPageData> curData; std::map<int, booking> bookKeeping; seek(0); getNext(); while(lastPack){//loop through all int tid = lastPack.getTrackId(); if (!tid){ getNext(false); continue; } if (!bookKeeping.count(tid)){ bookKeeping[tid].first = 1; bookKeeping[tid].curPart = 0; bookKeeping[tid].curKey = 0; curData[tid].lastKeyTime = 0xFFFFFFFF; curData[tid].keyNum = 1; curData[tid].partNum = 0; curData[tid].dataSize = 0; curData[tid].curOffset = 0; curData[tid].firstTime = myMeta.tracks[tid].keys[0].getTime(); char tmpId[20]; sprintf(tmpId, "%d", tid); indexPages[tid].init(config->getString("streamname") + tmpId, 8 * 1024, true);//Pages of 8kb in size, room for 512 parts. } if (myMeta.tracks[tid].keys[bookKeeping[tid].curKey].getParts() == curData[tid].partNum){ if (curData[tid].dataSize > 8 * 1024 * 1024) { pagesByTrack[tid][bookKeeping[tid].first] = curData[tid]; bookKeeping[tid].first += curData[tid].keyNum; curData[tid].keyNum = 0; curData[tid].dataSize = 0; curData[tid].firstTime = myMeta.tracks[tid].keys[bookKeeping[tid].curKey].getTime(); } bookKeeping[tid].curKey++; curData[tid].keyNum++; curData[tid].partNum = 0; } curData[tid].dataSize += lastPack.getDataLen(); curData[tid].partNum ++; bookKeeping[tid].curPart ++; getNext(false); } for (std::map<int, DTSC::Track>::iterator it = myMeta.tracks.begin(); it != myMeta.tracks.end(); it++) { if (curData.count(it->first) && !pagesByTrack[it->first].count(bookKeeping[it->first].first)){ pagesByTrack[it->first][bookKeeping[it->first].first] = curData[it->first]; } if (!pagesByTrack.count(it->first)){ DEBUG_MSG(DLVL_WARN, "No pages for track %d found", it->first); }else{ DEBUG_MSG(DLVL_MEDIUM, "Track %d (%s) split into %lu pages", it->first, myMeta.tracks[it->first].codec.c_str(), pagesByTrack[it->first].size()); for (std::map<int, DTSCPageData>::iterator it2 = pagesByTrack[it->first].begin(); it2 != pagesByTrack[it->first].end(); it2++){ DEBUG_MSG(DLVL_VERYHIGH, "Page %u-%u", it2->first, it2->first + it2->second.keyNum - 1); } } } } bool Input::bufferFrame(int track, int keyNum){ if (keyNum < 1){keyNum = 1;} if (!pagesByTrack.count(track)){ return false; } std::map<int, DTSCPageData>::iterator it = pagesByTrack[track].upper_bound(keyNum); if (it != pagesByTrack[track].begin()){ it--; } int pageNum = it->first; pageCounter[track][pageNum] = 15;///Keep page 15seconds in memory after last use DEBUG_MSG(DLVL_DONTEVEN, "Attempting to buffer page %d key %d->%d", track, keyNum, pageNum); if (dataPages[track].count(pageNum)){ return true; } char pageId[100]; int pageIdLen = sprintf(pageId, "%s%d_%d", config->getString("streamname").c_str(), track, pageNum); std::string tmpString(pageId, pageIdLen); #ifdef __CYGWIN__ dataPages[track][pageNum].init(tmpString, 26 * 1024 * 1024, true); #else dataPages[track][pageNum].init(tmpString, it->second.dataSize, true); #endif DEBUG_MSG(DLVL_HIGH, "Buffering track %d page %d through %d", track, pageNum, pageNum-1 + it->second.keyNum); std::stringstream trackSpec; trackSpec << track; trackSelect(trackSpec.str()); seek(myMeta.tracks[track].keys[pageNum-1].getTime()); long long unsigned int stopTime = myMeta.tracks[track].lastms + 1; if ((int)myMeta.tracks[track].keys.size() > pageNum-1 + it->second.keyNum){ stopTime = myMeta.tracks[track].keys[pageNum-1 + it->second.keyNum].getTime(); } DEBUG_MSG(DLVL_HIGH, "Playing from %ld to %llu", myMeta.tracks[track].keys[pageNum-1].getTime(), stopTime); it->second.curOffset = 0; getNext(); //in case earlier seeking was inprecise, seek to the exact point while (lastPack && lastPack.getTime() < (unsigned long long)myMeta.tracks[track].keys[pageNum-1].getTime()){ getNext(); } while (lastPack && lastPack.getTime() < stopTime){ if (it->second.curOffset + lastPack.getDataLen() > pagesByTrack[track][pageNum].dataSize){ DEBUG_MSG(DLVL_WARN, "Trying to write %u bytes on pos %llu where size is %llu (time: %llu / %llu, track %u page %u)", lastPack.getDataLen(), it->second.curOffset, pagesByTrack[track][pageNum].dataSize, lastPack.getTime(), stopTime, track, pageNum); break; }else{ memcpy(dataPages[track][pageNum].mapped + it->second.curOffset, lastPack.getData(), lastPack.getDataLen()); it->second.curOffset += lastPack.getDataLen(); } getNext(); } for (int i = 0; i < indexPages[track].len / 8; i++){ if (((long long int*)indexPages[track].mapped)[i] == 0){ ((long long int*)indexPages[track].mapped)[i] = (((long long int)htonl(pageNum)) << 32) | htonl(it->second.keyNum); break; } } DEBUG_MSG(DLVL_DEVEL, "Done buffering page %d for track %d", pageNum, track); return true; } bool Input::atKeyFrame(){ static std::map<int, unsigned long long> lastSeen; //not in keyTimes? We're not at a keyframe. unsigned int c = keyTimes[lastPack.getTrackId()].count(lastPack.getTime()); if (!c){ return false; } //skip double times if (lastSeen.count(lastPack.getTrackId()) && lastSeen[lastPack.getTrackId()] == lastPack.getTime()){ return false; } //set last seen, and return true lastSeen[lastPack.getTrackId()] = lastPack.getTime(); return true; } void Input::play(int until) { playing = -1; playUntil = until; initialTime = 0; benchMark = Util::getMS(); } void Input::playOnce() { if (playing <= 0) { playing = 1; } ++playing; benchMark = Util::getMS(); } void Input::quitPlay() { playing = 0; } } <|endoftext|>
<commit_before><commit_msg>Don't bother calling slice_alleles at all; just make big nodes and dice them<commit_after><|endoftext|>
<commit_before>/* includes object for each entry square row column am I complete array[9] available numbers test if subsquare is valid test line for valid entries test if game is complete main */ #include <iostream> #include <iomanip> #include <vector> #include <getopt.h> //for getopt() #include <cstdlib> //for exit() class entry { public: int value; bool complete; int square; int row; int column; bool numbers[9]; entry() { //initializer value = 0; complete=false; //square; //row; //column; for (int i = 0; i < 9; i++) { numbers[i] = false; } } }; std::vector <entry> board(81); //hardcoded arrays of pointers to the 9 each row, column, subsquares void testLayout(){} //sweep rows for invalid numbers //sweep columns for invalid numbers //sweep subsquares for invalid numbers //check if no other in row have value n //check if no other in column have value n //check if no other in subsquare have value n //test if board complete void sweepRows() { for (int i = 0; i < 81 ; i++) { } } void sweepColumns(){} void sweepSubsquares(){} void printBoard(){;} void printReport() { std::cout << "report goes here!" << std::endl; printBoard(); return; }/**/ int main(int argc, char* argv[]) { int c; while ((c = getopt(argc, argv, "sgh")) != -1) { switch (c) { case 's': std::cout << "Running in Solver Mode" << std::endl; break; case 'g': std::cout << "Running in Generate Mode" << std::endl; break; case 'h': std::cout << "sudoku help" << std::endl << "-s\tSolver Mode" << std::endl << "-g\tGenerate Mode" << std::endl ; exit(0); break; default:; } } //get layout //test layout //fill vectors of pointers std::cout << "Program beginning.." << std::endl; //program stuff printReport(); return 0; }/**/ <commit_msg>Updated further - still does not work.<commit_after>#include <iostream> #include <iomanip> #include <vector> #include <getopt.h> //for getopt() #include <cstdlib> //for exit() class entry { public: int value; int row; int column; int subsquare; int numbers[10]; // wasted,1,2,3,4,5,6,7,8,9 // possible numbers // impossible numbers entry() { //initializer value = 0; //square; //row; //column; numbers[0] = 0; //wasted for convenience for (int v = 1; v <= 9; v++) { //set the number entries numbers[v] = v; } } };/**/ std::vector <entry> board(81); entry* rows[9][9]; entry* columns[9][9]; entry* subsquares[9][9]; void printBoard(char type='x') { switch(type) { case 'r': std::cout << "rows:"; break; case 'c': std::cout << "columns:"; break; case 's': std::cout << "subsquares:"; break; default: std::cout << "known values:"; break; } for (int i = 0; i < 81; i++) { if (i % 9 == 0) std::cout << std::endl; switch(type) { case 'r': std::cout << board.at(i).row; break; case 'c': std::cout << board.at(i).column; break; case 's': std::cout << board.at(i).subsquare; break; default: if (board.at(i).value > 0) { std::cout << board.at(i).value; } else { std::cout << "_"; } break; } std::cout << " "; } std::cout << std::endl; }/**/ void setupArrays() //this should be in a separate file { for (int i = 0; i < 81; i++) { board.at(i).row = i / 9; //remainder is the column board.at(i).column = i % 9; //abuses integar truncation board.at(i).subsquare = (board.at(i).row / 3) + (board.at(i).column / 3) + i / 27 * 2; } // row pointers rows[0][0] = &board.at(0); rows[0][1] = &board.at(1); rows[0][2] = &board.at(2); rows[0][3] = &board.at(3); rows[0][4] = &board.at(4); rows[0][5] = &board.at(5); rows[0][6] = &board.at(6); rows[0][7] = &board.at(7); rows[0][8] = &board.at(8); rows[1][0] = &board.at(9); rows[1][1] = &board.at(10); rows[1][2] = &board.at(11); rows[1][3] = &board.at(12); rows[1][4] = &board.at(13); rows[1][5] = &board.at(14); rows[1][6] = &board.at(15); rows[1][7] = &board.at(16); rows[1][8] = &board.at(17); rows[2][0] = &board.at(18); rows[2][1] = &board.at(19); rows[2][2] = &board.at(20); rows[2][3] = &board.at(21); rows[2][4] = &board.at(22); rows[2][5] = &board.at(23); rows[2][6] = &board.at(24); rows[2][7] = &board.at(25); rows[2][8] = &board.at(26); rows[3][0] = &board.at(27); rows[3][1] = &board.at(28); rows[3][2] = &board.at(29); rows[3][3] = &board.at(30); rows[3][4] = &board.at(31); rows[3][5] = &board.at(32); rows[3][6] = &board.at(33); rows[3][7] = &board.at(34); rows[3][8] = &board.at(35); rows[4][0] = &board.at(36); rows[4][1] = &board.at(37); rows[4][2] = &board.at(38); rows[4][3] = &board.at(39); rows[4][4] = &board.at(40); rows[4][5] = &board.at(41); rows[4][6] = &board.at(42); rows[4][7] = &board.at(43); rows[4][8] = &board.at(44); rows[5][0] = &board.at(45); rows[5][1] = &board.at(46); rows[5][2] = &board.at(47); rows[5][3] = &board.at(48); rows[5][4] = &board.at(49); rows[5][5] = &board.at(50); rows[5][6] = &board.at(51); rows[5][7] = &board.at(52); rows[5][8] = &board.at(53); rows[6][0] = &board.at(54); rows[6][1] = &board.at(55); rows[6][2] = &board.at(56); rows[6][3] = &board.at(57); rows[6][4] = &board.at(58); rows[6][5] = &board.at(59); rows[6][6] = &board.at(60); rows[6][7] = &board.at(61); rows[6][8] = &board.at(62); rows[7][0] = &board.at(63); rows[7][1] = &board.at(64); rows[7][2] = &board.at(65); rows[7][3] = &board.at(66); rows[7][4] = &board.at(67); rows[7][5] = &board.at(68); rows[7][6] = &board.at(69); rows[7][7] = &board.at(70); rows[7][8] = &board.at(71); rows[8][0] = &board.at(72); rows[8][1] = &board.at(73); rows[8][2] = &board.at(74); rows[8][3] = &board.at(75); rows[8][4] = &board.at(76); rows[8][5] = &board.at(77); rows[8][6] = &board.at(78); rows[8][7] = &board.at(79); rows[8][8] = &board.at(80); // column pointers columns[0][0] = &board.at(0); columns[1][0] = &board.at(1); columns[2][0] = &board.at(2); columns[3][0] = &board.at(3); columns[4][0] = &board.at(4); columns[5][0] = &board.at(5); columns[6][0] = &board.at(6); columns[7][0] = &board.at(7); columns[8][0] = &board.at(8); columns[0][1] = &board.at(9); columns[1][1] = &board.at(10); columns[2][1] = &board.at(11); columns[3][1] = &board.at(12); columns[4][1] = &board.at(13); columns[5][1] = &board.at(14); columns[6][1] = &board.at(15); columns[7][1] = &board.at(16); columns[8][1] = &board.at(17); columns[0][2] = &board.at(18); columns[1][2] = &board.at(19); columns[2][2] = &board.at(20); columns[3][2] = &board.at(21); columns[4][2] = &board.at(22); columns[5][2] = &board.at(23); columns[6][2] = &board.at(24); columns[7][2] = &board.at(25); columns[8][2] = &board.at(26); columns[0][3] = &board.at(27); columns[1][3] = &board.at(28); columns[2][3] = &board.at(29); columns[3][3] = &board.at(30); columns[4][3] = &board.at(31); columns[5][3] = &board.at(32); columns[6][3] = &board.at(33); columns[7][3] = &board.at(34); columns[8][3] = &board.at(35); columns[0][4] = &board.at(36); columns[1][4] = &board.at(37); columns[2][4] = &board.at(38); columns[3][4] = &board.at(39); columns[4][4] = &board.at(40); columns[5][4] = &board.at(41); columns[6][4] = &board.at(42); columns[7][4] = &board.at(43); columns[8][4] = &board.at(44); columns[0][5] = &board.at(45); columns[1][5] = &board.at(46); columns[2][5] = &board.at(47); columns[3][5] = &board.at(48); columns[4][5] = &board.at(49); columns[5][5] = &board.at(50); columns[6][5] = &board.at(51); columns[7][5] = &board.at(52); columns[8][5] = &board.at(53); columns[0][6] = &board.at(54); columns[1][6] = &board.at(55); columns[2][6] = &board.at(56); columns[3][6] = &board.at(57); columns[4][6] = &board.at(58); columns[5][6] = &board.at(59); columns[6][6] = &board.at(60); columns[7][6] = &board.at(61); columns[8][6] = &board.at(62); columns[0][7] = &board.at(63); columns[1][7] = &board.at(64); columns[2][7] = &board.at(65); columns[3][7] = &board.at(66); columns[4][7] = &board.at(67); columns[5][7] = &board.at(68); columns[6][7] = &board.at(69); columns[7][7] = &board.at(70); columns[8][7] = &board.at(71); columns[0][8] = &board.at(72); columns[1][8] = &board.at(73); columns[2][8] = &board.at(74); columns[3][8] = &board.at(75); columns[4][8] = &board.at(76); columns[5][8] = &board.at(77); columns[6][8] = &board.at(78); columns[7][8] = &board.at(79); columns[8][8] = &board.at(80); // subsquare pointers subsquares[0][0] = &board.at(0); subsquares[0][1] = &board.at(1); subsquares[0][2] = &board.at(2); subsquares[1][0] = &board.at(3); subsquares[1][1] = &board.at(4); subsquares[1][2] = &board.at(5); subsquares[2][0] = &board.at(6); subsquares[2][1] = &board.at(7); subsquares[2][2] = &board.at(8); subsquares[0][3] = &board.at(9); subsquares[0][4] = &board.at(10); subsquares[0][5] = &board.at(11); subsquares[1][3] = &board.at(12); subsquares[1][4] = &board.at(13); subsquares[1][5] = &board.at(14); subsquares[2][3] = &board.at(15); subsquares[2][4] = &board.at(16); subsquares[2][5] = &board.at(17); subsquares[0][6] = &board.at(18); subsquares[0][7] = &board.at(19); subsquares[0][8] = &board.at(20); subsquares[1][6] = &board.at(21); subsquares[1][7] = &board.at(22); subsquares[1][8] = &board.at(23); subsquares[2][6] = &board.at(24); subsquares[2][7] = &board.at(25); subsquares[2][8] = &board.at(26); subsquares[3][0] = &board.at(27); subsquares[3][1] = &board.at(28); subsquares[3][2] = &board.at(29); subsquares[4][0] = &board.at(30); subsquares[4][1] = &board.at(31); subsquares[4][2] = &board.at(32); subsquares[5][0] = &board.at(33); subsquares[5][1] = &board.at(34); subsquares[5][2] = &board.at(35); subsquares[3][3] = &board.at(36); subsquares[3][4] = &board.at(37); subsquares[3][5] = &board.at(38); subsquares[4][3] = &board.at(39); subsquares[4][4] = &board.at(40); subsquares[4][5] = &board.at(41); subsquares[5][3] = &board.at(42); subsquares[5][4] = &board.at(43); subsquares[5][5] = &board.at(44); subsquares[3][6] = &board.at(45); subsquares[3][7] = &board.at(46); subsquares[3][8] = &board.at(47); subsquares[4][6] = &board.at(48); subsquares[4][7] = &board.at(49); subsquares[4][8] = &board.at(50); subsquares[5][6] = &board.at(51); subsquares[5][7] = &board.at(52); subsquares[5][8] = &board.at(53); subsquares[6][0] = &board.at(54); subsquares[6][1] = &board.at(55); subsquares[6][2] = &board.at(56); subsquares[7][0] = &board.at(57); subsquares[7][1] = &board.at(58); subsquares[7][2] = &board.at(59); subsquares[8][0] = &board.at(60); subsquares[8][1] = &board.at(61); subsquares[8][2] = &board.at(62); subsquares[6][3] = &board.at(63); subsquares[6][4] = &board.at(64); subsquares[6][5] = &board.at(65); subsquares[7][3] = &board.at(66); subsquares[7][4] = &board.at(67); subsquares[7][5] = &board.at(68); subsquares[8][3] = &board.at(69); subsquares[8][4] = &board.at(70); subsquares[8][5] = &board.at(71); subsquares[6][6] = &board.at(72); subsquares[6][7] = &board.at(73); subsquares[6][8] = &board.at(74); subsquares[7][6] = &board.at(75); subsquares[7][7] = &board.at(76); subsquares[7][8] = &board.at(77); subsquares[8][6] = &board.at(78); subsquares[8][7] = &board.at(79); subsquares[8][8] = &board.at(80); }/**/ //sweep rows for invalid numbers //sweep columns for invalid numbers //sweep subsquares for invalid numbers //check if no other in row have value n //check if no other in column have value n //check if no other in subsquare have value n //test if board complete void testEntry(entry* e) { if ((*e).value > 0) { //testing only; checked upstream! std::cout << "(*e).value > 0 : " << (*e).value << std::endl; exit(-1); } // update numbers to exclude duplicates of known values for (int i = 0; i < 9; i++) { if (not (&board.at(i) == e)) { // is not itself - fixme; cannot use [i] for (int v = 1; v <= 9; v++) if (not (*rows[(*e).row][i]).value == (*e).numbers[v]) (*e).numbers[v] = 0; for (int v = 1; v <= 9; v++) if (not (*columns[(*e).column][i]).value == (*e).numbers[v]) (*e).numbers[v] = 0; for (int v = 1; v <= 9; v++) if (not (*subsquares[(*e).subsquare][i]).value == (*e).numbers[v]) (*e).numbers[v] = 0; } } // test if only valid position for numbers (no other numbers[] include it!) for (int i = 0; i < 9; i++) for (int ve = 1; ve <= 9; ve++) for (int vtest = 1; vtest <= 9; vtest++) //if (not (*rows[(*e).row][i]).value == (*e).numbers[v]) //(*e).numbers[v] = 0; ; }/**/ void validateEntry(entry* e) { int value = 0; for (int v = 1; v <= 9; v++) { //numbers index if ((*e).numbers[v] > 0 ) { if (value > 0) return; //other entries have values! value = (*e).numbers[v]; } } if (value == 0) { //safeguard; can be removed later std::cout << "value == 0\n"; exit(-1); } (*e).value = value; printBoard(); std::cout << std::endl; }/**/ void validateEntries() { for (int i = 0; i < 81 ; i++) if (board.at(i).value < 1) validateEntry(&board.at(i)); //no value yet! }/**/ void sweepEntries() { for (int i = 0; i < 81 ; i++) { if (board.at(i).value < 1) testEntry(&board.at(i)); //no value yet! } //std::cout << "sweep complete!\n"; for (int i = 0; i < 81 ; i++) { (&board.at(i)); } }/**/ void printReport() { std::cout << "report goes here!" << std::endl; printBoard(); return; }/**/ /*void testArrays() { std::cout << "Values test.." << std::endl; printBoard('r'); printBoard('c'); printBoard('s'); std::cout << "Filling layout" << std::endl; printBoard(); std::cout << "setting board values incorrectly for testing!\n"; for (int i = 0; i < 81; i++) board.at(i).value = i; for (int i = 0; i < 9; i++) std::cout << (*rows[5][i]).value << " "; std::cout << std::endl; for (int i = 0; i < 9; i++) std::cout << (*columns[5][i]).value << " "; std::cout << std::endl; for (int i = 0; i < 9; i++) std::cout << (*subsquares[5][i]).value << " "; std::cout << std::endl; }/**/ bool testBoardComplete() { for (int i = 0; i < 81; i++) if (board.at(i).value < 1) return false; //there is an unset value! return true; }/**/ void filltestvalues() { // fill with an easy sudoku for testing board.at(0).value = 4; board.at(1).value = 1; board.at(7).value = 3; board.at(8).value = 7; board.at(9).value = 6; board.at(10).value = 2; board.at(16).value = 9; board.at(17).value = 8; board.at(20).value = 5; board.at(21).value = 9; board.at(23).value = 2; board.at(24).value = 1; board.at(29).value = 2; board.at(30).value = 7; board.at(32).value = 3; board.at(33).value = 4; board.at(40).value = 5; board.at(47).value = 1; board.at(48).value = 4; board.at(50).value = 6; board.at(51).value = 9; board.at(56).value = 4; board.at(57).value = 3; board.at(59).value = 8; board.at(60).value = 6; board.at(63).value = 2; board.at(64).value = 5; board.at(70).value = 4; board.at(71).value = 3; board.at(72).value = 9; board.at(73).value = 6; board.at(79).value = 1; board.at(80).value = 2; }/**/ int main(int argc, char* argv[]) { int c; while ((c = getopt(argc, argv, "sgh")) != -1) { switch (c) { case 's': std::cout << "Running in Solver Mode" << std::endl; break; case 'h': std::cout << "sudoku help" << std::endl << "-s\tSolver Mode" << std::endl << "-g\tGenerate Mode" << std::endl ; exit(0); break; default:; } } std::cout << "Building arrays.." << std::endl; setupArrays(); //get layout //test layout //fill vectors of pointers //more testing //testArrays(); std::cout << "Program beginning.." << std::endl; filltestvalues(); printBoard(); //return 0; do { sweepEntries(); } while (not testBoardComplete()); //program stuff printReport(); return 0; }/**/ <|endoftext|>
<commit_before>/* * Copyright (c) 2015-2015, Roland Bock * 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. * * 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 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 <iostream> #include "Sample.h" #include "MockDb.h" #include <sqlpp11/sqlpp11.h> SQLPP_ALIAS_PROVIDER(now) #if _MSC_FULL_VER >= 190023918 // MSVC Update 2 provides floor, ceil, round, abs in chrono (which is C++17 only...) using ::std::chrono::floor; #else using ::date::floor; #endif int DateTime(int, char* []) { MockDb db = {}; MockDb::_serializer_context_t printer = {}; const auto t = test::TabDateTime{}; for (const auto& row : db(select(::sqlpp::value(std::chrono::system_clock::now()).as(now)))) { std::cout << row.now; } for (const auto& row : db(select(all_of(t)).from(t).unconditionally())) { std::cout << row.colDayPoint; std::cout << row.colTimePoint; } printer.reset(); std::cerr << serialize(::sqlpp::value(std::chrono::system_clock::now()), printer).str() << std::endl; db(insert_into(t).set(t.colDayPoint = floor<::sqlpp::chrono::days>(std::chrono::system_clock::now()))); db(insert_into(t).set(t.colTimePoint = floor<::sqlpp::chrono::days>(std::chrono::system_clock::now()))); db(insert_into(t).set(t.colTimePoint = std::chrono::system_clock::now())); db(insert_into(t).set(t.colTimeOfDay = ::sqlpp::chrono::time_of_day(std::chrono::system_clock::now()))); db(update(t) .set(t.colDayPoint = floor<::sqlpp::chrono::days>(std::chrono::system_clock::now())) .where(t.colDayPoint < std::chrono::system_clock::now())); db(update(t) .set(t.colTimePoint = floor<::sqlpp::chrono::days>(std::chrono::system_clock::now()), t.colTimeOfDay = ::sqlpp::chrono::time_of_day(std::chrono::system_clock::now())) .where(t.colDayPoint < std::chrono::system_clock::now())); db(update(t) .set(t.colTimePoint = std::chrono::system_clock::now(), t.colTimeOfDay = ::sqlpp::chrono::time_of_day(std::chrono::system_clock::now())) .where(t.colDayPoint < std::chrono::system_clock::now())); db(remove_from(t).where(t.colDayPoint == floor<::sqlpp::chrono::days>(std::chrono::system_clock::now()))); db(remove_from(t).where(t.colDayPoint == std::chrono::system_clock::now())); db(remove_from(t).where(t.colTimePoint == floor<::sqlpp::chrono::days>(std::chrono::system_clock::now()))); db(remove_from(t).where(t.colTimePoint == std::chrono::system_clock::now())); db(remove_from(t).where(t.colTimeOfDay == ::sqlpp::chrono::time_of_day(std::chrono::system_clock::now()))); return 0; } <commit_msg>Added an example for reading time point values<commit_after>/* * Copyright (c) 2015-2015, Roland Bock * 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. * * 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 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 <iostream> #include "Sample.h" #include "MockDb.h" #include <sqlpp11/sqlpp11.h> SQLPP_ALIAS_PROVIDER(now) #if _MSC_FULL_VER >= 190023918 // MSVC Update 2 provides floor, ceil, round, abs in chrono (which is C++17 only...) using ::std::chrono::floor; #else using ::date::floor; #endif int DateTime(int, char*[]) { MockDb db = {}; MockDb::_serializer_context_t printer = {}; const auto t = test::TabDateTime{}; for (const auto& row : db(select(::sqlpp::value(std::chrono::system_clock::now()).as(now)))) { std::cout << row.now; } for (const auto& row : db(select(all_of(t)).from(t).unconditionally())) { std::cout << row.colDayPoint; std::cout << row.colTimePoint; const auto tp = std::chrono::system_clock::time_point{row.colTimePoint.value()}; std::cout << std::chrono::system_clock::to_time_t(tp); } printer.reset(); std::cerr << serialize(::sqlpp::value(std::chrono::system_clock::now()), printer).str() << std::endl; db(insert_into(t).set(t.colDayPoint = floor<::sqlpp::chrono::days>(std::chrono::system_clock::now()))); db(insert_into(t).set(t.colTimePoint = floor<::sqlpp::chrono::days>(std::chrono::system_clock::now()))); db(insert_into(t).set(t.colTimePoint = std::chrono::system_clock::now())); db(insert_into(t).set(t.colTimeOfDay = ::sqlpp::chrono::time_of_day(std::chrono::system_clock::now()))); db(update(t) .set(t.colDayPoint = floor<::sqlpp::chrono::days>(std::chrono::system_clock::now())) .where(t.colDayPoint < std::chrono::system_clock::now())); db(update(t) .set(t.colTimePoint = floor<::sqlpp::chrono::days>(std::chrono::system_clock::now()), t.colTimeOfDay = ::sqlpp::chrono::time_of_day(std::chrono::system_clock::now())) .where(t.colDayPoint < std::chrono::system_clock::now())); db(update(t) .set(t.colTimePoint = std::chrono::system_clock::now(), t.colTimeOfDay = ::sqlpp::chrono::time_of_day(std::chrono::system_clock::now())) .where(t.colDayPoint < std::chrono::system_clock::now())); db(remove_from(t).where(t.colDayPoint == floor<::sqlpp::chrono::days>(std::chrono::system_clock::now()))); db(remove_from(t).where(t.colDayPoint == std::chrono::system_clock::now())); db(remove_from(t).where(t.colTimePoint == floor<::sqlpp::chrono::days>(std::chrono::system_clock::now()))); db(remove_from(t).where(t.colTimePoint == std::chrono::system_clock::now())); db(remove_from(t).where(t.colTimeOfDay == ::sqlpp::chrono::time_of_day(std::chrono::system_clock::now()))); return 0; } <|endoftext|>
<commit_before>/** * @file icing.cpp * * Created on: Jan 03, 2013 * @author aaltom */ #include "icing.h" #include <iostream> #include "plugin_factory.h" #include "logger_factory.h" #include <boost/lexical_cast.hpp> #include "util.h" #define HIMAN_AUXILIARY_INCLUDE #include "fetcher.h" #undef HIMAN_AUXILIARY_INCLUDE using namespace std; using namespace himan::plugin; const double kValueEpsilon = 0.00001; icing::icing() { itsClearTextFormula = "Icing = round(log(500 * CW * 1000)) + VVcor + Tcor"; itsLogger = std::unique_ptr<logger> (logger_factory::Instance()->GetLog("icing")); } void icing::Process(std::shared_ptr<const plugin_configuration> conf) { Init(conf); /* * Set target parameter to icing * - name ICEIND-N * - univ_id 480 * - grib2 descriptor 0'00'002 * * We need to specify grib and querydata parameter information * since we don't know which one will be the output format. * (todo: we could check from conf but why bother?) * */ vector<param> theParams; param theRequestedParam("ICING-N", 480); theParams.push_back(theRequestedParam); SetParams(theParams); Start(); } /* * Calculate() * * This function does the actual calculation. */ void icing::Calculate(shared_ptr<info> myTargetInfo, unsigned short theThreadIndex) { shared_ptr<fetcher> theFetcher = dynamic_pointer_cast <fetcher> (plugin_factory::Instance()->Plugin("fetcher")); // Required source parameters param TParam("T-K"); params VvParam = { param("VV-MS"), param("VV-MMS")}; param ClParam("CLDWAT-KGKG"); unique_ptr<logger> myThreadedLogger = std::unique_ptr<logger> (logger_factory::Instance()->GetLog("icingThread #" + boost::lexical_cast<string> (theThreadIndex))); ResetNonLeadingDimension(myTargetInfo); myTargetInfo->FirstParam(); while (AdjustNonLeadingDimension(myTargetInfo)) { myThreadedLogger->Debug("Calculating time " + myTargetInfo->Time().ValidDateTime()->String("%Y%m%d%H") + " level " + boost::lexical_cast<string> (myTargetInfo->Level().Value())); shared_ptr<info> TInfo; shared_ptr<info> VvInfo; shared_ptr<info> ClInfo; double VvScale = 1; // Assume we'll have VV-MMS try { // Source info for T TInfo = theFetcher->Fetch(itsConfiguration, myTargetInfo->Time(), myTargetInfo->Level(), TParam); // Source info for Tg VvInfo = theFetcher->Fetch(itsConfiguration, myTargetInfo->Time(), myTargetInfo->Level(), VvParam); if (VvInfo) { VvInfo->First(); if (VvInfo->Param().Name() == "VV-MS") { VvScale = 1000; } } // Source info for FF ClInfo = theFetcher->Fetch(itsConfiguration, myTargetInfo->Time(), myTargetInfo->Level(), ClParam); } catch (HPExceptionType& e) { switch (e) { case kFileDataNotFound: itsLogger->Info("Skipping step " + boost::lexical_cast<string> (myTargetInfo->Time().Step()) + ", level " + boost::lexical_cast<string> (myTargetInfo->Level().Value())); myTargetInfo->Data()->Fill(kFloatMissing); // Fill data with missing value if (itsConfiguration->StatisticsEnabled()) { itsConfiguration->Statistics()->AddToMissingCount(myTargetInfo->Grid()->Size()); itsConfiguration->Statistics()->AddToValueCount(myTargetInfo->Grid()->Size()); } continue; break; default: throw runtime_error(ClassName() + ": Unable to proceed"); break; } } unique_ptr<timer> processTimer = unique_ptr<timer> (timer_factory::Instance()->GetTimer()); if (itsConfiguration->StatisticsEnabled()) { processTimer->Start(); } assert(TInfo->Grid()->AB() == VvInfo->Grid()->AB() && TInfo->Grid()->AB() == ClInfo->Grid()->AB()); SetAB(myTargetInfo, TInfo); shared_ptr<NFmiGrid> targetGrid(myTargetInfo->Grid()->ToNewbaseGrid()); shared_ptr<NFmiGrid> TGrid(TInfo->Grid()->ToNewbaseGrid()); shared_ptr<NFmiGrid> VvGrid(VvInfo->Grid()->ToNewbaseGrid()); shared_ptr<NFmiGrid> ClGrid(ClInfo->Grid()->ToNewbaseGrid()); size_t missingCount = 0; size_t count = 0; assert(targetGrid->Size() == myTargetInfo->Data()->Size()); bool equalGrids = (*myTargetInfo->Grid() == *TInfo->Grid() && *myTargetInfo->Grid() == *VvInfo->Grid() && *myTargetInfo->Grid() == *ClInfo->Grid()); myTargetInfo->ResetLocation(); targetGrid->Reset(); string deviceType = "CPU"; while (myTargetInfo->NextLocation() && targetGrid->Next()) { count++; double T = kFloatMissing; double Vv = kFloatMissing; double Cl = kFloatMissing; InterpolateToPoint(targetGrid, TGrid, equalGrids, T); InterpolateToPoint(targetGrid, VvGrid, equalGrids, Vv); InterpolateToPoint(targetGrid, ClGrid, equalGrids, Cl); if (T == kFloatMissing || Vv == kFloatMissing || Cl == kFloatMissing) { missingCount++; myTargetInfo->Value(kFloatMissing); continue; } double Icing; double TBase = 273.15; int vCor = kHPMissingInt; int tCor = kHPMissingInt; T = T - TBase; Vv *= VvScale; // Vertical velocity correction factor if (Vv < 0) { vCor = -1; } else if ((Vv >= 0) && (Vv <= 50)) { vCor = 0; } else if ((Vv >= 50) && (Vv <= 100)) { vCor = 1; } else if ((Vv >= 100) && (Vv <= 200)) { vCor = 2; } else if ((Vv >= 200) && (Vv <= 300)) { vCor = 3; } else if ((Vv >= 300) && (Vv <= 1000)) { vCor = 4; } else if (Vv > 1000) { vCor = 5; } // Temperature correction factor if ((T <= 0) && (T > -1)) { tCor = -2; } else if ((T <= -1) && (T > -2)) { tCor = -1; } else if ((T <= -2) && (T > -3)) { tCor = 0; } else if ((T <= -3) && (T > -12)) { tCor = 1; } else if ((T <= -12) && (T > -15)) { tCor = 0; } else if ((T <= -15) && (T > -18)) { tCor = -1; } else if (T < -18) { tCor = -2; } else { tCor = 0; } if ((Cl <= 0) || (T > 0)) { Icing = 0; } else { Icing = round(log(500 * Cl * 1000)) + vCor + tCor; } // Maximum and minimum values for index if (Icing > 15) { Icing = 15; } if (Icing < 0) { Icing = 0; } if (!myTargetInfo->Value(Icing)) { throw runtime_error(ClassName() + ": Failed to set value to matrix"); } } /* * Newbase normalizes scanning mode to bottom left -- if that's not what * the target scanning mode is, we have to swap the data back. */ SwapTo(myTargetInfo, kBottomLeft); if (itsConfiguration->StatisticsEnabled()) { processTimer->Stop(); itsConfiguration->Statistics()->AddToProcessingTime(processTimer->GetTime()); #ifdef DEBUG itsLogger->Debug("Calculation took " + boost::lexical_cast<string> (processTimer->GetTime()) + " microseconds on " + deviceType); #endif itsConfiguration->Statistics()->AddToMissingCount(missingCount); itsConfiguration->Statistics()->AddToValueCount(count); } /* * Now we are done for this level * * Clone info-instance to writer since it might change our descriptor places */ myThreadedLogger->Info("[" + deviceType + "] Missing values: " + boost::lexical_cast<string> (missingCount) + "/" + boost::lexical_cast<string> (count)); if (itsConfiguration->FileWriteOption() != kSingleFile) { WriteToFile(myTargetInfo); } } } <commit_msg>add grib2 number<commit_after>/** * @file icing.cpp * * Created on: Jan 03, 2013 * @author aaltom */ #include "icing.h" #include <iostream> #include "plugin_factory.h" #include "logger_factory.h" #include <boost/lexical_cast.hpp> #include "util.h" #define HIMAN_AUXILIARY_INCLUDE #include "fetcher.h" #undef HIMAN_AUXILIARY_INCLUDE using namespace std; using namespace himan::plugin; const double kValueEpsilon = 0.00001; icing::icing() { itsClearTextFormula = "Icing = round(log(500 * CW * 1000)) + VVcor + Tcor"; itsLogger = std::unique_ptr<logger> (logger_factory::Instance()->GetLog("icing")); } void icing::Process(std::shared_ptr<const plugin_configuration> conf) { Init(conf); /* * Set target parameter to icing * - name ICEIND-N * - univ_id 480 * - grib2 descriptor 0'00'002 * * We need to specify grib and querydata parameter information * since we don't know which one will be the output format. * (todo: we could check from conf but why bother?) * */ vector<param> theParams; param theRequestedParam("ICING-N", 480, 0, 19, 7); theParams.push_back(theRequestedParam); SetParams(theParams); Start(); } /* * Calculate() * * This function does the actual calculation. */ void icing::Calculate(shared_ptr<info> myTargetInfo, unsigned short theThreadIndex) { shared_ptr<fetcher> theFetcher = dynamic_pointer_cast <fetcher> (plugin_factory::Instance()->Plugin("fetcher")); // Required source parameters param TParam("T-K"); params VvParam = { param("VV-MS"), param("VV-MMS")}; param ClParam("CLDWAT-KGKG"); unique_ptr<logger> myThreadedLogger = std::unique_ptr<logger> (logger_factory::Instance()->GetLog("icingThread #" + boost::lexical_cast<string> (theThreadIndex))); ResetNonLeadingDimension(myTargetInfo); myTargetInfo->FirstParam(); while (AdjustNonLeadingDimension(myTargetInfo)) { myThreadedLogger->Debug("Calculating time " + myTargetInfo->Time().ValidDateTime()->String("%Y%m%d%H") + " level " + boost::lexical_cast<string> (myTargetInfo->Level().Value())); shared_ptr<info> TInfo; shared_ptr<info> VvInfo; shared_ptr<info> ClInfo; double VvScale = 1; // Assume we'll have VV-MMS try { // Source info for T TInfo = theFetcher->Fetch(itsConfiguration, myTargetInfo->Time(), myTargetInfo->Level(), TParam); // Source info for Tg VvInfo = theFetcher->Fetch(itsConfiguration, myTargetInfo->Time(), myTargetInfo->Level(), VvParam); if (VvInfo) { VvInfo->First(); if (VvInfo->Param().Name() == "VV-MS") { VvScale = 1000; } } // Source info for FF ClInfo = theFetcher->Fetch(itsConfiguration, myTargetInfo->Time(), myTargetInfo->Level(), ClParam); } catch (HPExceptionType& e) { switch (e) { case kFileDataNotFound: itsLogger->Info("Skipping step " + boost::lexical_cast<string> (myTargetInfo->Time().Step()) + ", level " + boost::lexical_cast<string> (myTargetInfo->Level().Value())); myTargetInfo->Data()->Fill(kFloatMissing); // Fill data with missing value if (itsConfiguration->StatisticsEnabled()) { itsConfiguration->Statistics()->AddToMissingCount(myTargetInfo->Grid()->Size()); itsConfiguration->Statistics()->AddToValueCount(myTargetInfo->Grid()->Size()); } continue; break; default: throw runtime_error(ClassName() + ": Unable to proceed"); break; } } unique_ptr<timer> processTimer = unique_ptr<timer> (timer_factory::Instance()->GetTimer()); if (itsConfiguration->StatisticsEnabled()) { processTimer->Start(); } assert(TInfo->Grid()->AB() == VvInfo->Grid()->AB() && TInfo->Grid()->AB() == ClInfo->Grid()->AB()); SetAB(myTargetInfo, TInfo); shared_ptr<NFmiGrid> targetGrid(myTargetInfo->Grid()->ToNewbaseGrid()); shared_ptr<NFmiGrid> TGrid(TInfo->Grid()->ToNewbaseGrid()); shared_ptr<NFmiGrid> VvGrid(VvInfo->Grid()->ToNewbaseGrid()); shared_ptr<NFmiGrid> ClGrid(ClInfo->Grid()->ToNewbaseGrid()); size_t missingCount = 0; size_t count = 0; assert(targetGrid->Size() == myTargetInfo->Data()->Size()); bool equalGrids = (*myTargetInfo->Grid() == *TInfo->Grid() && *myTargetInfo->Grid() == *VvInfo->Grid() && *myTargetInfo->Grid() == *ClInfo->Grid()); myTargetInfo->ResetLocation(); targetGrid->Reset(); string deviceType = "CPU"; while (myTargetInfo->NextLocation() && targetGrid->Next()) { count++; double T = kFloatMissing; double Vv = kFloatMissing; double Cl = kFloatMissing; InterpolateToPoint(targetGrid, TGrid, equalGrids, T); InterpolateToPoint(targetGrid, VvGrid, equalGrids, Vv); InterpolateToPoint(targetGrid, ClGrid, equalGrids, Cl); if (T == kFloatMissing || Vv == kFloatMissing || Cl == kFloatMissing) { missingCount++; myTargetInfo->Value(kFloatMissing); continue; } double Icing; double TBase = 273.15; int vCor = kHPMissingInt; int tCor = kHPMissingInt; T = T - TBase; Vv *= VvScale; // Vertical velocity correction factor if (Vv < 0) { vCor = -1; } else if ((Vv >= 0) && (Vv <= 50)) { vCor = 0; } else if ((Vv >= 50) && (Vv <= 100)) { vCor = 1; } else if ((Vv >= 100) && (Vv <= 200)) { vCor = 2; } else if ((Vv >= 200) && (Vv <= 300)) { vCor = 3; } else if ((Vv >= 300) && (Vv <= 1000)) { vCor = 4; } else if (Vv > 1000) { vCor = 5; } // Temperature correction factor if ((T <= 0) && (T > -1)) { tCor = -2; } else if ((T <= -1) && (T > -2)) { tCor = -1; } else if ((T <= -2) && (T > -3)) { tCor = 0; } else if ((T <= -3) && (T > -12)) { tCor = 1; } else if ((T <= -12) && (T > -15)) { tCor = 0; } else if ((T <= -15) && (T > -18)) { tCor = -1; } else if (T < -18) { tCor = -2; } else { tCor = 0; } if ((Cl <= 0) || (T > 0)) { Icing = 0; } else { Icing = round(log(500 * Cl * 1000)) + vCor + tCor; } // Maximum and minimum values for index if (Icing > 15) { Icing = 15; } if (Icing < 0) { Icing = 0; } if (!myTargetInfo->Value(Icing)) { throw runtime_error(ClassName() + ": Failed to set value to matrix"); } } /* * Newbase normalizes scanning mode to bottom left -- if that's not what * the target scanning mode is, we have to swap the data back. */ SwapTo(myTargetInfo, kBottomLeft); if (itsConfiguration->StatisticsEnabled()) { processTimer->Stop(); itsConfiguration->Statistics()->AddToProcessingTime(processTimer->GetTime()); #ifdef DEBUG itsLogger->Debug("Calculation took " + boost::lexical_cast<string> (processTimer->GetTime()) + " microseconds on " + deviceType); #endif itsConfiguration->Statistics()->AddToMissingCount(missingCount); itsConfiguration->Statistics()->AddToValueCount(count); } /* * Now we are done for this level * * Clone info-instance to writer since it might change our descriptor places */ myThreadedLogger->Info("[" + deviceType + "] Missing values: " + boost::lexical_cast<string> (missingCount) + "/" + boost::lexical_cast<string> (count)); if (itsConfiguration->FileWriteOption() != kSingleFile) { WriteToFile(myTargetInfo); } } } <|endoftext|>
<commit_before>/* Copyright (C) 2019 The Falco Authors. 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 <stdio.h> #include <string.h> #include "falco_common.h" #include "webserver.h" #include "json_evt.h" #include "banned.h" // This raises a compilation error when certain functions are used using json = nlohmann::json; using namespace std; string k8s_audit_handler::m_k8s_audit_event_source = "k8s_audit"; k8s_audit_handler::k8s_audit_handler(falco_engine *engine, falco_outputs *outputs): m_engine(engine), m_outputs(outputs) { } k8s_audit_handler::~k8s_audit_handler() { } bool k8s_healthz_handler::handleGet(CivetServer *server, struct mg_connection *conn) { const std::string status_body = "{\"status\": \"ok\"}"; mg_send_http_ok(conn, "application/json", status_body.size()); mg_printf(conn, "%s", status_body.c_str()); return true; } bool k8s_audit_handler::accept_data(falco_engine *engine, falco_outputs *outputs, std::string &data, std::string &errstr) { std::list<json_event> jevts; json j; try { j = json::parse(data); } catch(json::parse_error &e) { errstr = string("Could not parse data: ") + e.what(); return false; } catch(json::out_of_range &e) { errstr = string("Could not parse data: ") + e.what(); return false; } bool ok; try { ok = falco_k8s_audit::parse_k8s_audit_json(j, jevts); } catch(json::type_error &e) { ok = false; } if(!ok) { errstr = string("Data not recognized as a k8s audit event"); return false; } for(auto &jev : jevts) { std::unique_ptr<falco_engine::rule_result> res; try { res = engine->process_event(m_k8s_audit_event_source, &jev); } catch(...) { errstr = string("unkown error processing audit event"); fprintf(stderr, "%s\n", errstr.c_str()); return false; } if(res) { try { outputs->handle_event(res->evt, res->rule, res->source, res->priority_num, res->format, res->tags); } catch(falco_exception &e) { errstr = string("Internal error handling output: ") + e.what(); fprintf(stderr, "%s\n", errstr.c_str()); return false; } } } return true; } bool k8s_audit_handler::accept_uploaded_data(std::string &post_data, std::string &errstr) { return k8s_audit_handler::accept_data(m_engine, m_outputs, post_data, errstr); } bool k8s_audit_handler::handleGet(CivetServer *server, struct mg_connection *conn) { mg_send_http_error(conn, 405, "GET method not allowed"); return true; } // The version in CivetServer.cpp has valgrind compliants due to // unguarded initialization of c++ string from buffer. static void get_post_data(struct mg_connection *conn, std::string &postdata) { mg_lock_connection(conn); char buf[2048]; int r = mg_read(conn, buf, sizeof(buf)); while(r > 0) { postdata.append(buf, r); r = mg_read(conn, buf, sizeof(buf)); } mg_unlock_connection(conn); } bool k8s_audit_handler::handlePost(CivetServer *server, struct mg_connection *conn) { // Ensure that the content-type is application/json const char *ct = server->getHeader(conn, string("Content-Type")); if(ct == NULL || strstr(ct, "application/json") == NULL) { mg_send_http_error(conn, 400, "Wrong Content Type"); return true; } std::string post_data; get_post_data(conn, post_data); std::string errstr; if(!accept_uploaded_data(post_data, errstr)) { errstr = "Bad Request: " + errstr; mg_send_http_error(conn, 400, "%s", errstr.c_str()); return true; } const std::string ok_body = "<html><body>Ok</body></html>"; mg_send_http_ok(conn, "text/html", ok_body.size()); mg_printf(conn, "%s", ok_body.c_str()); return true; } falco_webserver::falco_webserver(): m_config(NULL) { } falco_webserver::~falco_webserver() { stop(); } void falco_webserver::init(falco_configuration *config, falco_engine *engine, falco_outputs *outputs) { m_config = config; m_engine = engine; m_outputs = outputs; } template<typename T, typename... Args> std::unique_ptr<T> make_unique(Args &&... args) { return std::unique_ptr<T>(new T(std::forward<Args>(args)...)); } void falco_webserver::start() { if(m_server) { stop(); } if(!m_config) { throw falco_exception("No config provided to webserver"); } if(!m_engine) { throw falco_exception("No engine provided to webserver"); } if(!m_outputs) { throw falco_exception("No outputs provided to webserver"); } std::vector<std::string> cpp_options = { "num_threads", to_string(1)}; if(m_config->m_webserver_ssl_enabled) { cpp_options.push_back("listening_ports"); cpp_options.push_back(to_string(m_config->m_webserver_listen_port) + "s"); cpp_options.push_back("ssl_certificate"); cpp_options.push_back(m_config->m_webserver_ssl_certificate); } else { cpp_options.push_back("listening_ports"); cpp_options.push_back(to_string(m_config->m_webserver_listen_port)); } try { m_server = make_unique<CivetServer>(cpp_options); } catch(CivetException &e) { throw falco_exception(std::string("Could not create embedded webserver: ") + e.what()); } if(!m_server->getContext()) { throw falco_exception("Could not create embedded webserver"); } m_k8s_audit_handler = make_unique<k8s_audit_handler>(m_engine, m_outputs); m_server->addHandler(m_config->m_webserver_k8s_audit_endpoint, *m_k8s_audit_handler); m_k8s_healthz_handler = make_unique<k8s_healthz_handler>(); m_server->addHandler(m_config->m_webserver_k8s_healthz_endpoint, *m_k8s_healthz_handler); } void falco_webserver::stop() { if(m_server) { m_server = NULL; m_k8s_audit_handler = NULL; m_k8s_healthz_handler = NULL; } } <commit_msg>update(userspace/falco): enforce check that content-type actually starts with "application/json" string.<commit_after>/* Copyright (C) 2019 The Falco Authors. 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 <stdio.h> #include <string.h> #include "falco_common.h" #include "webserver.h" #include "json_evt.h" #include "banned.h" // This raises a compilation error when certain functions are used using json = nlohmann::json; using namespace std; string k8s_audit_handler::m_k8s_audit_event_source = "k8s_audit"; k8s_audit_handler::k8s_audit_handler(falco_engine *engine, falco_outputs *outputs): m_engine(engine), m_outputs(outputs) { } k8s_audit_handler::~k8s_audit_handler() { } bool k8s_healthz_handler::handleGet(CivetServer *server, struct mg_connection *conn) { const std::string status_body = "{\"status\": \"ok\"}"; mg_send_http_ok(conn, "application/json", status_body.size()); mg_printf(conn, "%s", status_body.c_str()); return true; } bool k8s_audit_handler::accept_data(falco_engine *engine, falco_outputs *outputs, std::string &data, std::string &errstr) { std::list<json_event> jevts; json j; try { j = json::parse(data); } catch(json::parse_error &e) { errstr = string("Could not parse data: ") + e.what(); return false; } catch(json::out_of_range &e) { errstr = string("Could not parse data: ") + e.what(); return false; } bool ok; try { ok = falco_k8s_audit::parse_k8s_audit_json(j, jevts); } catch(json::type_error &e) { ok = false; } if(!ok) { errstr = string("Data not recognized as a k8s audit event"); return false; } for(auto &jev : jevts) { std::unique_ptr<falco_engine::rule_result> res; try { res = engine->process_event(m_k8s_audit_event_source, &jev); } catch(...) { errstr = string("unkown error processing audit event"); fprintf(stderr, "%s\n", errstr.c_str()); return false; } if(res) { try { outputs->handle_event(res->evt, res->rule, res->source, res->priority_num, res->format, res->tags); } catch(falco_exception &e) { errstr = string("Internal error handling output: ") + e.what(); fprintf(stderr, "%s\n", errstr.c_str()); return false; } } } return true; } bool k8s_audit_handler::accept_uploaded_data(std::string &post_data, std::string &errstr) { return k8s_audit_handler::accept_data(m_engine, m_outputs, post_data, errstr); } bool k8s_audit_handler::handleGet(CivetServer *server, struct mg_connection *conn) { mg_send_http_error(conn, 405, "GET method not allowed"); return true; } // The version in CivetServer.cpp has valgrind compliants due to // unguarded initialization of c++ string from buffer. static void get_post_data(struct mg_connection *conn, std::string &postdata) { mg_lock_connection(conn); char buf[2048]; int r = mg_read(conn, buf, sizeof(buf)); while(r > 0) { postdata.append(buf, r); r = mg_read(conn, buf, sizeof(buf)); } mg_unlock_connection(conn); } bool k8s_audit_handler::handlePost(CivetServer *server, struct mg_connection *conn) { // Ensure that the content-type is application/json const char *ct = server->getHeader(conn, string("Content-Type")); // content type *must* start with application/json if(ct == NULL || strncmp(ct, "application/json", strlen("application/json")) != 0) { mg_send_http_error(conn, 400, "Wrong Content Type"); return true; } std::string post_data; get_post_data(conn, post_data); std::string errstr; if(!accept_uploaded_data(post_data, errstr)) { errstr = "Bad Request: " + errstr; mg_send_http_error(conn, 400, "%s", errstr.c_str()); return true; } const std::string ok_body = "<html><body>Ok</body></html>"; mg_send_http_ok(conn, "text/html", ok_body.size()); mg_printf(conn, "%s", ok_body.c_str()); return true; } falco_webserver::falco_webserver(): m_config(NULL) { } falco_webserver::~falco_webserver() { stop(); } void falco_webserver::init(falco_configuration *config, falco_engine *engine, falco_outputs *outputs) { m_config = config; m_engine = engine; m_outputs = outputs; } template<typename T, typename... Args> std::unique_ptr<T> make_unique(Args &&... args) { return std::unique_ptr<T>(new T(std::forward<Args>(args)...)); } void falco_webserver::start() { if(m_server) { stop(); } if(!m_config) { throw falco_exception("No config provided to webserver"); } if(!m_engine) { throw falco_exception("No engine provided to webserver"); } if(!m_outputs) { throw falco_exception("No outputs provided to webserver"); } std::vector<std::string> cpp_options = { "num_threads", to_string(1)}; if(m_config->m_webserver_ssl_enabled) { cpp_options.push_back("listening_ports"); cpp_options.push_back(to_string(m_config->m_webserver_listen_port) + "s"); cpp_options.push_back("ssl_certificate"); cpp_options.push_back(m_config->m_webserver_ssl_certificate); } else { cpp_options.push_back("listening_ports"); cpp_options.push_back(to_string(m_config->m_webserver_listen_port)); } try { m_server = make_unique<CivetServer>(cpp_options); } catch(CivetException &e) { throw falco_exception(std::string("Could not create embedded webserver: ") + e.what()); } if(!m_server->getContext()) { throw falco_exception("Could not create embedded webserver"); } m_k8s_audit_handler = make_unique<k8s_audit_handler>(m_engine, m_outputs); m_server->addHandler(m_config->m_webserver_k8s_audit_endpoint, *m_k8s_audit_handler); m_k8s_healthz_handler = make_unique<k8s_healthz_handler>(); m_server->addHandler(m_config->m_webserver_k8s_healthz_endpoint, *m_k8s_healthz_handler); } void falco_webserver::stop() { if(m_server) { m_server = NULL; m_k8s_audit_handler = NULL; m_k8s_healthz_handler = NULL; } } <|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 "gfx/font.h" #include "testing/gtest/include/gtest/gtest.h" namespace { using gfx::Font; class FontTest : public testing::Test { }; TEST_F(FontTest, LoadArial) { Font cf(Font::CreateFont(L"Arial", 16)); ASSERT_TRUE(cf.nativeFont()); ASSERT_EQ(cf.style(), Font::NORMAL); ASSERT_EQ(cf.FontSize(), 16); ASSERT_EQ(cf.FontName(), L"Arial"); } TEST_F(FontTest, LoadArialBold) { Font cf(Font::CreateFont(L"Arial", 16)); Font bold(cf.DeriveFont(0, Font::BOLD)); ASSERT_TRUE(bold.nativeFont()); ASSERT_EQ(bold.style(), Font::BOLD); } TEST_F(FontTest, Ascent) { Font cf(Font::CreateFont(L"Arial", 16)); ASSERT_GT(cf.baseline(), 2); ASSERT_LE(cf.baseline(), 22); } TEST_F(FontTest, Height) { Font cf(Font::CreateFont(L"Arial", 16)); ASSERT_GE(cf.height(), 16); // TODO(akalin): Figure out why height is so large on Linux. ASSERT_LE(cf.height(), 26); } TEST_F(FontTest, AvgWidths) { Font cf(Font::CreateFont(L"Arial", 16)); ASSERT_EQ(cf.GetExpectedTextWidth(0), 0); ASSERT_GT(cf.GetExpectedTextWidth(1), cf.GetExpectedTextWidth(0)); ASSERT_GT(cf.GetExpectedTextWidth(2), cf.GetExpectedTextWidth(1)); ASSERT_GT(cf.GetExpectedTextWidth(3), cf.GetExpectedTextWidth(2)); } TEST_F(FontTest, Widths) { Font cf(Font::CreateFont(L"Arial", 16)); ASSERT_EQ(cf.GetStringWidth(L""), 0); ASSERT_GT(cf.GetStringWidth(L"a"), cf.GetStringWidth(L"")); ASSERT_GT(cf.GetStringWidth(L"ab"), cf.GetStringWidth(L"a")); ASSERT_GT(cf.GetStringWidth(L"abc"), cf.GetStringWidth(L"ab")); } #if defined(OS_WIN) // TODO(beng): re-enable evening of 3/22. TEST_F(FontTest, DISABLED_DeriveFontResizesIfSizeTooSmall) { // This creates font of height -8. Font cf(Font::CreateFont(L"Arial", 6)); Font derived_font = cf.DeriveFont(-4); LOGFONT font_info; GetObject(derived_font.hfont(), sizeof(LOGFONT), &font_info); EXPECT_EQ(-5, font_info.lfHeight); } TEST_F(FontTest, DISABLED_DeriveFontKeepsOriginalSizeIfHeightOk) { // This creates font of height -8. Font cf(Font::CreateFont(L"Arial", 6)); Font derived_font = cf.DeriveFont(-2); LOGFONT font_info; GetObject(derived_font.hfont(), sizeof(LOGFONT), &font_info); EXPECT_EQ(-6, font_info.lfHeight); } #endif } // anonymous namespace <commit_msg>TTF: Enable disabled tests: FontTest.DeriveFont{ResizesIfSizeTooSmall,KeepsOriginalSizeIfHeightOk}<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 "gfx/font.h" #include "testing/gtest/include/gtest/gtest.h" namespace { using gfx::Font; class FontTest : public testing::Test { }; TEST_F(FontTest, LoadArial) { Font cf(Font::CreateFont(L"Arial", 16)); ASSERT_TRUE(cf.nativeFont()); ASSERT_EQ(cf.style(), Font::NORMAL); ASSERT_EQ(cf.FontSize(), 16); ASSERT_EQ(cf.FontName(), L"Arial"); } TEST_F(FontTest, LoadArialBold) { Font cf(Font::CreateFont(L"Arial", 16)); Font bold(cf.DeriveFont(0, Font::BOLD)); ASSERT_TRUE(bold.nativeFont()); ASSERT_EQ(bold.style(), Font::BOLD); } TEST_F(FontTest, Ascent) { Font cf(Font::CreateFont(L"Arial", 16)); ASSERT_GT(cf.baseline(), 2); ASSERT_LE(cf.baseline(), 22); } TEST_F(FontTest, Height) { Font cf(Font::CreateFont(L"Arial", 16)); ASSERT_GE(cf.height(), 16); // TODO(akalin): Figure out why height is so large on Linux. ASSERT_LE(cf.height(), 26); } TEST_F(FontTest, AvgWidths) { Font cf(Font::CreateFont(L"Arial", 16)); ASSERT_EQ(cf.GetExpectedTextWidth(0), 0); ASSERT_GT(cf.GetExpectedTextWidth(1), cf.GetExpectedTextWidth(0)); ASSERT_GT(cf.GetExpectedTextWidth(2), cf.GetExpectedTextWidth(1)); ASSERT_GT(cf.GetExpectedTextWidth(3), cf.GetExpectedTextWidth(2)); } TEST_F(FontTest, Widths) { Font cf(Font::CreateFont(L"Arial", 16)); ASSERT_EQ(cf.GetStringWidth(L""), 0); ASSERT_GT(cf.GetStringWidth(L"a"), cf.GetStringWidth(L"")); ASSERT_GT(cf.GetStringWidth(L"ab"), cf.GetStringWidth(L"a")); ASSERT_GT(cf.GetStringWidth(L"abc"), cf.GetStringWidth(L"ab")); } #if defined(OS_WIN) // http://crbug.com/46733 TEST_F(FontTest, FAILS_DeriveFontResizesIfSizeTooSmall) { // This creates font of height -8. Font cf(Font::CreateFont(L"Arial", 6)); Font derived_font = cf.DeriveFont(-4); LOGFONT font_info; GetObject(derived_font.hfont(), sizeof(LOGFONT), &font_info); EXPECT_EQ(-5, font_info.lfHeight); } TEST_F(FontTest, DeriveFontKeepsOriginalSizeIfHeightOk) { // This creates font of height -8. Font cf(Font::CreateFont(L"Arial", 6)); Font derived_font = cf.DeriveFont(-2); LOGFONT font_info; GetObject(derived_font.hfont(), sizeof(LOGFONT), &font_info); EXPECT_EQ(-6, font_info.lfHeight); } #endif } // anonymous namespace <|endoftext|>
<commit_before>/* * (C) Copyright 2015 ETH Zurich Systems Group (http://www.systems.ethz.ch/) and others. * * 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. * * Contributors: * Markus Pilman <[email protected]> * Simon Loesing <[email protected]> * Thomas Etter <[email protected]> * Kevin Bocksrocker <[email protected]> * Lucas Braun <[email protected]> */ #include "ScanQuery.hpp" #include <crossbow/alignment.hpp> namespace tell { namespace store { namespace { const uint16_t gMaxTupleCount = 250; Record buildScanRecord(ScanQueryType queryType, const char* queryData, const char* queryDataEnd, const Record& record) { switch (queryType) { case ScanQueryType::FULL: { return record; } break; case ScanQueryType::PROJECTION: { Schema schema(TableType::UNKNOWN); ProjectionIterator end(queryDataEnd); for (ProjectionIterator i(queryData); i != end; ++i) { auto& field = record.getFieldMeta(*i).field; schema.addField(field.type(), field.name(), field.isNotNull()); } return Record(std::move(schema)); } break; case ScanQueryType::AGGREGATION: { Schema schema(TableType::UNKNOWN); Record::id_t fieldId = 0u; AggregationIterator end(queryDataEnd); for (AggregationIterator i(queryData); i != end; ++i, ++fieldId) { Record::id_t id; AggregationType aggType; std::tie(id, aggType) = *i; bool notNull; switch (aggType) { case AggregationType::MIN: case AggregationType::MAX: case AggregationType::SUM: { notNull = false; } break; case AggregationType::CNT: { notNull = true; } break; default: { LOG_ASSERT(false, "Unknown aggregation type"); notNull = false; } break; } auto& field = record.getFieldMeta(id).field; schema.addField(field.aggType(aggType), crossbow::to_string(fieldId), notNull); } return Record(std::move(schema)); } break; default: { LOG_ASSERT(false, "Unknown scan query type"); return Record(); } break; } } } // anonymous namespace ScanQuery::ScanQuery(ScanQueryType queryType, std::unique_ptr<char[]> selectionData, size_t selectionLength, std::unique_ptr<char[]> queryData, size_t queryLength, std::unique_ptr<commitmanager::SnapshotDescriptor> snapshot, const Record& record) : mQueryType(queryType), mSelectionData(std::move(selectionData)), mSelectionLength(selectionLength), mQueryData(std::move(queryData)), mQueryLength(queryLength), mSnapshot(std::move(snapshot)), mRecord(buildScanRecord(mQueryType, mQueryData.get(), mQueryData.get() + mQueryLength, record)), mMinimumLength(mRecord.staticSize() + ScanQueryProcessor::TUPLE_OVERHEAD) { } ScanQuery::~ScanQuery() = default; ScanQueryProcessor::~ScanQueryProcessor() { if (!mData) { return; } std::error_code ec; if (mBuffer) { mData->writeLast(mBuffer, mBufferWriter.data(), ec); } else { LOG_ASSERT(mTupleCount == 0, "Invalid buffer containing tuples"); mData->writeLast(ec); } if (ec) { // TODO FIXME This leads to a leak (the ServerSocket does not notice that the scan has finished) LOG_ERROR("Error while flushing buffer [error = %1% %2%]", ec, ec.message()); } LOG_DEBUG("Scan processor done [totalWritten = %1%]", mTotalWritten); } ScanQueryProcessor::ScanQueryProcessor(ScanQueryProcessor&& other) : mData(other.mData), mBuffer(std::move(other.mBuffer)), mBufferWriter(other.mBufferWriter), mTotalWritten(other.mTotalWritten), mTupleCount(other.mTupleCount) { other.mData = nullptr; other.mBuffer = nullptr; other.mTotalWritten = 0u; other.mTupleCount = 0u; } ScanQueryProcessor& ScanQueryProcessor::operator=(ScanQueryProcessor&& other) { mData = other.mData; other.mData = nullptr; mBuffer = other.mBuffer; other.mBuffer = nullptr; mBufferWriter = std::move(other.mBufferWriter); mTotalWritten = other.mTotalWritten; other.mTotalWritten = 0u; mTupleCount = other.mTupleCount; other.mTupleCount = 0u; return *this; } void ScanQueryProcessor::initAggregationRecord() { ensureBufferSpace(mData->minimumLength()); mBufferWriter.write<uint64_t>(0u); auto tupleData = mBufferWriter.data(); mBufferWriter.set(0, mData->minimumLength() - TUPLE_OVERHEAD); auto& record = mData->record(); auto aggIter = mData->aggregationBegin(); for (Record::id_t i = 0; i < record.fieldCount(); ++i, ++aggIter) { uint16_t destFieldIdx; record.idOf(crossbow::to_string(i), destFieldIdx); auto& metadata = record.getFieldMeta(destFieldIdx); auto& field = metadata.field; auto aggType = std::get<1>(*aggIter); field.initAgg(aggType, tupleData + metadata.offset); // Set all fields that can be NULL to NULL // Whenever the first value is written the field will be marked as non-NULL if (!field.isNotNull()) { record.setFieldNull(tupleData, metadata.nullIdx, true); } } } void ScanQueryProcessor::ensureBufferSpace(uint32_t length) { if (mTupleCount < gMaxTupleCount && mBufferWriter.canWrite(length)) { return; } if (mBuffer) { mTotalWritten += static_cast<uint64_t>(mBufferWriter.data() - mBuffer); std::error_code ec; mData->writeOngoing(mBuffer, mBufferWriter.data(), ec); if (ec) { LOG_ERROR("Error while sending buffer [error = %1% %2%]", ec, ec.message()); } } uint32_t bufferLength; std::tie(mBuffer, bufferLength) = mData->acquireBuffer(); if (!mBuffer) { // TODO Handle error throw std::runtime_error("Error acquiring buffer"); } mBufferWriter = crossbow::buffer_writer(mBuffer, bufferLength); mTupleCount = 0u; if (!mBufferWriter.canWrite(length)) { // TODO Handle error throw std::runtime_error("Trying to write too much data into the buffer"); } } } // namespace store } // namespace tell <commit_msg>Increase maximum tuple count in a scan buffer<commit_after>/* * (C) Copyright 2015 ETH Zurich Systems Group (http://www.systems.ethz.ch/) and others. * * 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. * * Contributors: * Markus Pilman <[email protected]> * Simon Loesing <[email protected]> * Thomas Etter <[email protected]> * Kevin Bocksrocker <[email protected]> * Lucas Braun <[email protected]> */ #include "ScanQuery.hpp" #include <crossbow/alignment.hpp> namespace tell { namespace store { namespace { const uint16_t gMaxTupleCount = 4u * 1024u; Record buildScanRecord(ScanQueryType queryType, const char* queryData, const char* queryDataEnd, const Record& record) { switch (queryType) { case ScanQueryType::FULL: { return record; } break; case ScanQueryType::PROJECTION: { Schema schema(TableType::UNKNOWN); ProjectionIterator end(queryDataEnd); for (ProjectionIterator i(queryData); i != end; ++i) { auto& field = record.getFieldMeta(*i).field; schema.addField(field.type(), field.name(), field.isNotNull()); } return Record(std::move(schema)); } break; case ScanQueryType::AGGREGATION: { Schema schema(TableType::UNKNOWN); Record::id_t fieldId = 0u; AggregationIterator end(queryDataEnd); for (AggregationIterator i(queryData); i != end; ++i, ++fieldId) { Record::id_t id; AggregationType aggType; std::tie(id, aggType) = *i; bool notNull; switch (aggType) { case AggregationType::MIN: case AggregationType::MAX: case AggregationType::SUM: { notNull = false; } break; case AggregationType::CNT: { notNull = true; } break; default: { LOG_ASSERT(false, "Unknown aggregation type"); notNull = false; } break; } auto& field = record.getFieldMeta(id).field; schema.addField(field.aggType(aggType), crossbow::to_string(fieldId), notNull); } return Record(std::move(schema)); } break; default: { LOG_ASSERT(false, "Unknown scan query type"); return Record(); } break; } } } // anonymous namespace ScanQuery::ScanQuery(ScanQueryType queryType, std::unique_ptr<char[]> selectionData, size_t selectionLength, std::unique_ptr<char[]> queryData, size_t queryLength, std::unique_ptr<commitmanager::SnapshotDescriptor> snapshot, const Record& record) : mQueryType(queryType), mSelectionData(std::move(selectionData)), mSelectionLength(selectionLength), mQueryData(std::move(queryData)), mQueryLength(queryLength), mSnapshot(std::move(snapshot)), mRecord(buildScanRecord(mQueryType, mQueryData.get(), mQueryData.get() + mQueryLength, record)), mMinimumLength(mRecord.staticSize() + ScanQueryProcessor::TUPLE_OVERHEAD) { } ScanQuery::~ScanQuery() = default; ScanQueryProcessor::~ScanQueryProcessor() { if (!mData) { return; } std::error_code ec; if (mBuffer) { mData->writeLast(mBuffer, mBufferWriter.data(), ec); } else { LOG_ASSERT(mTupleCount == 0, "Invalid buffer containing tuples"); mData->writeLast(ec); } if (ec) { // TODO FIXME This leads to a leak (the ServerSocket does not notice that the scan has finished) LOG_ERROR("Error while flushing buffer [error = %1% %2%]", ec, ec.message()); } LOG_DEBUG("Scan processor done [totalWritten = %1%]", mTotalWritten); } ScanQueryProcessor::ScanQueryProcessor(ScanQueryProcessor&& other) : mData(other.mData), mBuffer(std::move(other.mBuffer)), mBufferWriter(other.mBufferWriter), mTotalWritten(other.mTotalWritten), mTupleCount(other.mTupleCount) { other.mData = nullptr; other.mBuffer = nullptr; other.mTotalWritten = 0u; other.mTupleCount = 0u; } ScanQueryProcessor& ScanQueryProcessor::operator=(ScanQueryProcessor&& other) { mData = other.mData; other.mData = nullptr; mBuffer = other.mBuffer; other.mBuffer = nullptr; mBufferWriter = std::move(other.mBufferWriter); mTotalWritten = other.mTotalWritten; other.mTotalWritten = 0u; mTupleCount = other.mTupleCount; other.mTupleCount = 0u; return *this; } void ScanQueryProcessor::initAggregationRecord() { ensureBufferSpace(mData->minimumLength()); mBufferWriter.write<uint64_t>(0u); auto tupleData = mBufferWriter.data(); mBufferWriter.set(0, mData->minimumLength() - TUPLE_OVERHEAD); auto& record = mData->record(); auto aggIter = mData->aggregationBegin(); for (Record::id_t i = 0; i < record.fieldCount(); ++i, ++aggIter) { uint16_t destFieldIdx; record.idOf(crossbow::to_string(i), destFieldIdx); auto& metadata = record.getFieldMeta(destFieldIdx); auto& field = metadata.field; auto aggType = std::get<1>(*aggIter); field.initAgg(aggType, tupleData + metadata.offset); // Set all fields that can be NULL to NULL // Whenever the first value is written the field will be marked as non-NULL if (!field.isNotNull()) { record.setFieldNull(tupleData, metadata.nullIdx, true); } } } void ScanQueryProcessor::ensureBufferSpace(uint32_t length) { if (mTupleCount < gMaxTupleCount && mBufferWriter.canWrite(length)) { return; } if (mBuffer) { mTotalWritten += static_cast<uint64_t>(mBufferWriter.data() - mBuffer); std::error_code ec; mData->writeOngoing(mBuffer, mBufferWriter.data(), ec); if (ec) { LOG_ERROR("Error while sending buffer [error = %1% %2%]", ec, ec.message()); } } uint32_t bufferLength; std::tie(mBuffer, bufferLength) = mData->acquireBuffer(); if (!mBuffer) { // TODO Handle error throw std::runtime_error("Error acquiring buffer"); } mBufferWriter = crossbow::buffer_writer(mBuffer, bufferLength); mTupleCount = 0u; if (!mBufferWriter.canWrite(length)) { // TODO Handle error throw std::runtime_error("Trying to write too much data into the buffer"); } } } // namespace store } // namespace tell <|endoftext|>
<commit_before>// kmfiltermgr.cpp #include <kapplication.h> #include <kdebug.h> #include <kmessagebox.h> #include <klocale.h> #include "kmfoldermgr.h" #include "kmfiltermgr.h" #include "kmfilterdlg.h" #include "kmmessage.h" //todo #include <kdebug.h> //----------------------------------------------------------------------------- KMFilterMgr::KMFilterMgr(bool popFilter): KMFilterMgrInherited(), bPopFilter(popFilter) { if (bPopFilter) kdDebug(5006) << "pPopFilter set" << endl; setAutoDelete(TRUE); mEditDialog = NULL; mShowLater = false; } //----------------------------------------------------------------------------- KMFilterMgr::~KMFilterMgr() { writeConfig(FALSE); } //----------------------------------------------------------------------------- void KMFilterMgr::readConfig(void) { KConfig* config = kapp->config(); int i, numFilters; QString grpName; KMFilter* filter; QString group; clear(); KConfigGroupSaver saver(config, "General"); if (bPopFilter) { numFilters = config->readNumEntry("popfilters",0); mShowLater = config->readNumEntry("popshowDLmsgs",0); group = "PopFilter"; } else { numFilters = config->readNumEntry("filters",0); group = "Filter"; } for (i=0; i<numFilters; i++) { grpName.sprintf("%s #%d", group.latin1(), i); KConfigGroupSaver saver(config, grpName); filter = new KMFilter(config, bPopFilter); filter->purify(); if ( filter->isEmpty() ) { kdDebug(5006) << "KMFilter::readConfig: filter\n" << filter->asString() << "is empty!" << endl; delete filter; } else append(filter); } } //----------------------------------------------------------------------------- void KMFilterMgr::writeConfig(bool withSync) { KConfig* config = kapp->config(); QString grpName; int i = 0; QString group; if (bPopFilter) group = "PopFilter"; else group = "Filter"; QPtrListIterator<KMFilter> it(*this); it.toFirst(); while ( it.current() ) { if ( !(*it)->isEmpty() ) { grpName.sprintf("%s #%d", group.latin1(), i); //grpName.sprintf("Filter #%d", i); KConfigGroupSaver saver(config, grpName); (*it)->writeConfig(config); ++i; } ++it; } KConfigGroupSaver saver(config, "General"); if (bPopFilter) { config->writeEntry("popfilters", i); config->writeEntry("popshowDLmsgs", mShowLater); } else { config->writeEntry("filters", i); } if (withSync) config->sync(); } //----------------------------------------------------------------------------- int KMFilterMgr::process(KMMessage* msg, FilterSet aSet) { if(bPopFilter) { QPtrListIterator<KMFilter> it(*this); for (it.toFirst() ; it.current() ; ++it) { if ((*it)->pattern()->matches(msg)) return (*it)->action(); } return NoAction; } else { if (!aSet) { kdDebug(5006) << "KMFilterMgr: process() called with not filter set selected" << endl; return 1; } bool stopIt = FALSE; int status = -1; KMFilter::ReturnCode result; QPtrListIterator<KMFilter> it(*this); for (it.toFirst() ; !stopIt && it.current() ; ++it) { if ( aSet&All || ( (aSet&Outbound) && (*it)->applyOnOutbound() ) || ( (aSet&Inbound) && (*it)->applyOnInbound() ) || ( (aSet&Explicit) && (*it)->applyOnExplicit() ) ) { if ((*it)->pattern()->matches(msg)) { result = (*it)->execActions(msg, stopIt); switch ( result ) { case KMFilter::CriticalError: // Critical error - immediate return return 2; case KMFilter::MsgExpropriated: // Message saved in a folder status = 0; default: break; } } } } if (status < 0) // No filters matched, keep copy of message status = 1; return status; } } //----------------------------------------------------------------------------- void KMFilterMgr::cleanup(void) { QPtrListIterator<KMFolder> it(mOpenFolders); for ( it.toFirst() ; it.current() ; ++it ) (*it)->close(); mOpenFolders.clear(); } //----------------------------------------------------------------------------- int KMFilterMgr::tempOpenFolder(KMFolder* aFolder) { assert(aFolder!=NULL); int rc = aFolder->open(); if (rc) return rc; mOpenFolders.append(aFolder); return rc; } //----------------------------------------------------------------------------- void KMFilterMgr::openDialog( QWidget *parent ) { if( !mEditDialog ) { // // We can't use the parent as long as the dialog is modeless // and there is one shared dialog for all top level windows. // (void)parent; mEditDialog = new KMFilterDlg( 0, "filterdialog", bPopFilter ); } mEditDialog->show(); } //----------------------------------------------------------------------------- void KMFilterMgr::createFilter( const QCString field, const QString value ) { openDialog( 0 ); mEditDialog->createFilter( field, value ); } //----------------------------------------------------------------------------- bool KMFilterMgr::folderRemoved(KMFolder* aFolder, KMFolder* aNewFolder) { bool rem = FALSE; QPtrListIterator<KMFilter> it(*this); for ( it.toFirst() ; it.current() ; ++it ) if ( (*it)->folderRemoved(aFolder, aNewFolder) ) rem=TRUE; return rem; } //----------------------------------------------------------------------------- void KMFilterMgr::setShowLaterMsgs(bool aShow) { mShowLater = aShow; } //----------------------------------------------------------------------------- bool KMFilterMgr::showLaterMsgs() { return mShowLater; } //----------------------------------------------------------------------------- void KMFilterMgr::dump(void) { QPtrListIterator<KMFilter> it(*this); for ( it.toFirst() ; it.current() ; ++it ) { kdDebug(5006) << (*it)->asString() << endl; } } <commit_msg>fix the "all filters are always applied regardless of their Inbound, Outbound, Explicit setting" bug<commit_after>// kmfiltermgr.cpp #include <kapplication.h> #include <kdebug.h> #include <kmessagebox.h> #include <klocale.h> #include "kmfoldermgr.h" #include "kmfiltermgr.h" #include "kmfilterdlg.h" #include "kmmessage.h" //todo #include <kdebug.h> //----------------------------------------------------------------------------- KMFilterMgr::KMFilterMgr(bool popFilter): KMFilterMgrInherited(), bPopFilter(popFilter) { if (bPopFilter) kdDebug(5006) << "pPopFilter set" << endl; setAutoDelete(TRUE); mEditDialog = NULL; mShowLater = false; } //----------------------------------------------------------------------------- KMFilterMgr::~KMFilterMgr() { writeConfig(FALSE); } //----------------------------------------------------------------------------- void KMFilterMgr::readConfig(void) { KConfig* config = kapp->config(); int i, numFilters; QString grpName; KMFilter* filter; QString group; clear(); KConfigGroupSaver saver(config, "General"); if (bPopFilter) { numFilters = config->readNumEntry("popfilters",0); mShowLater = config->readNumEntry("popshowDLmsgs",0); group = "PopFilter"; } else { numFilters = config->readNumEntry("filters",0); group = "Filter"; } for (i=0; i<numFilters; i++) { grpName.sprintf("%s #%d", group.latin1(), i); KConfigGroupSaver saver(config, grpName); filter = new KMFilter(config, bPopFilter); filter->purify(); if ( filter->isEmpty() ) { kdDebug(5006) << "KMFilter::readConfig: filter\n" << filter->asString() << "is empty!" << endl; delete filter; } else append(filter); } } //----------------------------------------------------------------------------- void KMFilterMgr::writeConfig(bool withSync) { KConfig* config = kapp->config(); QString grpName; int i = 0; QString group; if (bPopFilter) group = "PopFilter"; else group = "Filter"; QPtrListIterator<KMFilter> it(*this); it.toFirst(); while ( it.current() ) { if ( !(*it)->isEmpty() ) { grpName.sprintf("%s #%d", group.latin1(), i); //grpName.sprintf("Filter #%d", i); KConfigGroupSaver saver(config, grpName); (*it)->writeConfig(config); ++i; } ++it; } KConfigGroupSaver saver(config, "General"); if (bPopFilter) { config->writeEntry("popfilters", i); config->writeEntry("popshowDLmsgs", mShowLater); } else { config->writeEntry("filters", i); } if (withSync) config->sync(); } //----------------------------------------------------------------------------- int KMFilterMgr::process(KMMessage* msg, FilterSet aSet) { if(bPopFilter) { QPtrListIterator<KMFilter> it(*this); for (it.toFirst() ; it.current() ; ++it) { if ((*it)->pattern()->matches(msg)) return (*it)->action(); } return NoAction; } else { if (!aSet) { kdDebug(5006) << "KMFilterMgr: process() called with not filter set selected" << endl; return 1; } bool stopIt = FALSE; int status = -1; QPtrListIterator<KMFilter> it(*this); for (it.toFirst() ; !stopIt && it.current() ; ++it) { if ( ( (aSet&Outbound) && (*it)->applyOnOutbound() ) || ( (aSet&Inbound) && (*it)->applyOnInbound() ) || ( (aSet&Explicit) && (*it)->applyOnExplicit() ) ) { if ((*it)->pattern()->matches(msg)) { switch ( (*it)->execActions(msg, stopIt) ) { case KMFilter::CriticalError: // Critical error - immediate return return 2; case KMFilter::MsgExpropriated: // Message saved in a folder status = 0; default: break; } } } } if (status < 0) // No filters matched, keep copy of message status = 1; return status; } } //----------------------------------------------------------------------------- void KMFilterMgr::cleanup(void) { QPtrListIterator<KMFolder> it(mOpenFolders); for ( it.toFirst() ; it.current() ; ++it ) (*it)->close(); mOpenFolders.clear(); } //----------------------------------------------------------------------------- int KMFilterMgr::tempOpenFolder(KMFolder* aFolder) { assert(aFolder!=NULL); int rc = aFolder->open(); if (rc) return rc; mOpenFolders.append(aFolder); return rc; } //----------------------------------------------------------------------------- void KMFilterMgr::openDialog( QWidget *parent ) { if( !mEditDialog ) { // // We can't use the parent as long as the dialog is modeless // and there is one shared dialog for all top level windows. // (void)parent; mEditDialog = new KMFilterDlg( 0, "filterdialog", bPopFilter ); } mEditDialog->show(); } //----------------------------------------------------------------------------- void KMFilterMgr::createFilter( const QCString field, const QString value ) { openDialog( 0 ); mEditDialog->createFilter( field, value ); } //----------------------------------------------------------------------------- bool KMFilterMgr::folderRemoved(KMFolder* aFolder, KMFolder* aNewFolder) { bool rem = FALSE; QPtrListIterator<KMFilter> it(*this); for ( it.toFirst() ; it.current() ; ++it ) if ( (*it)->folderRemoved(aFolder, aNewFolder) ) rem=TRUE; return rem; } //----------------------------------------------------------------------------- void KMFilterMgr::setShowLaterMsgs(bool aShow) { mShowLater = aShow; } //----------------------------------------------------------------------------- bool KMFilterMgr::showLaterMsgs() { return mShowLater; } //----------------------------------------------------------------------------- void KMFilterMgr::dump(void) { QPtrListIterator<KMFilter> it(*this); for ( it.toFirst() ; it.current() ; ++it ) { kdDebug(5006) << (*it)->asString() << endl; } } <|endoftext|>
<commit_before>/** * @file neons.cpp * * @date Nov 20, 2012 * @author partio */ #include "neons.h" #include "logger_factory.h" #include "plugin_factory.h" #include <thread> #include <sstream> #include "util.h" using namespace std; using namespace himan::plugin; const int MAX_WORKERS = 16; once_flag oflag; neons::neons() : itsInit(false), itsNeonsDB() { itsLogger = unique_ptr<logger> (logger_factory::Instance()->GetLog("neons")); // no lambda functions for gcc 4.4 :( // call_once(oflag, [](){ NFmiNeonsDBPool::MaxWorkers(MAX_WORKERS); }); call_once(oflag, &himan::plugin::neons::InitPool, this); } void neons::InitPool() { NFmiNeonsDBPool::Instance()->MaxWorkers(MAX_WORKERS); char* host; host = getenv("HOSTNAME"); // TODO: a smarter way to check if we are in production server if (host != NULL) { if (string(host) == "gogol.fmi.fi" || string(host) == "tolstoi.fmi.fi") { NFmiNeonsDBPool::Instance()->ExternalAuthentication(true); NFmiNeonsDBPool::Instance()->ReadWriteTransaction(true); } else if (string(host) == "jeera.fmi.fi" || string(host) == "sahrami.fmi.fi") { NFmiNeonsDBPool::Instance()->ReadWriteTransaction(true); NFmiNeonsDBPool::Instance()->Username("wetodb"); NFmiNeonsDBPool::Instance()->Password("3loHRgdio"); } } } vector<string> neons::Files(const search_options& options) { Init(); vector<string> files; string analtime = options.time.OriginDateTime()->String("%Y%m%d%H%M%S"); string levelvalue = boost::lexical_cast<string> (options.level.Value()); string ref_prod = options.configuration->SourceProducer().Name(); //producerInfo["ref_prod"]; // long proddef = options.configuration->SourceProducer().Id(); // producerInfo["producer_id"]; long no_vers = options.configuration->SourceProducer().TableVersion(); // producerInfo["no_vers"]; string level_name = options.level.Name(); vector<vector<string> > gridgeoms = itsNeonsDB->GetGridGeoms(ref_prod, analtime, options.configuration->SourceGeomName()); if (gridgeoms.empty()) { itsLogger->Warning("No geometries found for given search options"); return files; } for (size_t i = 0; i < gridgeoms.size(); i++) { string tablename = gridgeoms[i][1]; string dset = gridgeoms[i][2]; /// @todo GFS (or in fact codetable 2) has wrong temperature parameter defined string parm_name = options.param.Name(); if (parm_name == "T-K" && no_vers == 2) { parm_name = "T-C"; } string query = "SELECT parm_name, lvl_type, lvl1_lvl2, fcst_per, file_location, file_server " "FROM "+tablename+" " "WHERE dset_id = "+dset+" " "AND parm_name = upper('"+parm_name+"') " "AND lvl_type = upper('"+level_name+"') " "AND lvl1_lvl2 = " +levelvalue+" " "AND fcst_per = "+boost::lexical_cast<string> (options.time.Step())+" " "ORDER BY dset_id, fcst_per, lvl_type, lvl1_lvl2"; itsNeonsDB->Query(query); vector<string> values = itsNeonsDB->FetchRow(); if (values.empty()) { continue; } itsLogger->Trace("Found data for parameter " + parm_name + " from neons geometry " + gridgeoms[i][0]); files.push_back(values[4]); } return files; } bool neons::Save(shared_ptr<const info> resultInfo, const string& theFileName) { Init(); stringstream query; /* * 1. Get grid information * 2. Get model information * 3. Get data set information (ie model run) * 4. Insert or update */ himan::point firstGridPoint = resultInfo->Grid()->FirstGridPoint(); /* * pas_latitude and pas_longitude cannot be checked programmatically * since f.ex. in the case for GFS in neons we have value 500 and * by calculating we have value 498. But not check these columns should * not matter as long as row_cnt, col_cnt, lat_orig and lon_orig match * (since pas_latitude and pas_longitude are derived from these anyway) */ query << "SELECT geom_name " << "FROM grid_reg_geom " << "WHERE row_cnt = " << resultInfo->Nj() << " AND col_cnt = " << resultInfo->Ni() << " AND lat_orig = " << (firstGridPoint.Y() * 1e3) << " AND long_orig = " << (firstGridPoint.X() * 1e3); // << " AND pas_latitude = " << static_cast<long> (resultInfo->Dj() * 1e3) // << " AND pas_longitude = " << static_cast<long> (resultInfo->Di() * 1e3); itsNeonsDB->Query(query.str()); vector<string> row; row = itsNeonsDB->FetchRow(); if (row.empty()) { itsLogger->Warning("Grid geometry not found from neons"); return false; } string geom_name = row[0]; query.str(""); query << "SELECT " << "nu.model_id AS process, " << "nu.ident_id AS centre, " << "m.model_name, " << "m.model_type, " << "type_smt " << "FROM " << "grid_num_model_grib nu, " << "grid_model m, " << "grid_model_name na, " << "fmi_producers f " << "WHERE f.producer_id = " << resultInfo->Producer().Id() << " AND m.model_type = f.ref_prod " << " AND nu.model_name = m.model_name " << " AND m.flag_mod = 0 " << " AND nu.model_name = na.model_name " << " AND m.model_name = na.model_name "; itsNeonsDB->Query(query.str()); row = itsNeonsDB->FetchRow(); if (row.empty()) { itsLogger->Warning("Producer definition not found from neons (id: " + boost::lexical_cast<string> (resultInfo->Producer().Id()) + ")"); return false; } string process = row[0]; //string centre = row[1]; //string model_name = row[2]; string model_type = row[3]; /* query << "SELECT " << "m.model_name, " << "model_type, " << "type_smt " << "FROM grid_num_model_grib nu, " << "grid_model m, " << "grid_model_name na " << "WHERE nu.model_id = " << info.process << " AND nu.ident_id = " << info.centre << " AND m.flag_mod = 0 " << " AND nu.model_name = na.model_name " << " AND m.model_name = na.model_name"; */ query.str(""); query << "SELECT " << "dset_id, " << "table_name, " << "rec_cnt_dset " << "FROM as_grid " << "WHERE " << "model_type = '" << model_type << "'" << " AND geom_name = '" << geom_name << "'" << " AND dset_name = 'AF'" << " AND base_date = '" << resultInfo->OriginDateTime().String("%Y%m%d%H%M") << "'"; itsNeonsDB->Query(query.str()); row = itsNeonsDB->FetchRow(); if (row.empty()) { itsLogger->Warning("Data set definition not found from neons"); return false; } string table_name = row[1]; string dset_id = row[0]; string eps_specifier = "0"; query.str(""); query << "UPDATE as_grid " << "SET rec_cnt_dset = " << "rec_cnt_dset + 1, " << "date_maj_dset = sysdate " << "WHERE dset_id = " << dset_id; try { itsNeonsDB->Execute(query.str()); } catch (int e) { itsLogger->Error("Error code: " + boost::lexical_cast<string> (e)); itsLogger->Error("Query: " + query.str()); itsNeonsDB->Rollback(); return false; } query.str(""); string host = "undetermined host"; char* hostname = getenv("HOSTNAME"); if (hostname != NULL) { host = string(hostname); } query << "INSERT INTO " << table_name << " (dset_id, parm_name, lvl_type, lvl1_lvl2, fcst_per, eps_specifier, file_location, file_server) " << "VALUES (" << dset_id << ", " << "'" << resultInfo->Param().Name() << "', " << "upper('" << resultInfo->Level().Name() << "'), " << resultInfo->Level().Value() << ", " << resultInfo->Time().Step() << ", " << "'" << eps_specifier << "', " << "'" << theFileName << "', " << "'" << host << "')"; try { itsNeonsDB->Execute(query.str()); itsNeonsDB->Commit(); } catch (int e) { if (e == 1) { // unique key violation itsLogger->Debug("Unique key violation when inserting to '" + table_name + "' -- data is already loaded"); } else { itsLogger->Error("Error code: " + boost::lexical_cast<string> (e)); itsLogger->Error("Query: " + query.str()); } itsNeonsDB->Rollback(); return false; } itsLogger->Info("Saved information on file '" + theFileName + "' to neons"); return true; } string neons::GribParameterName(const long fmiParameterId, const long codeTableVersion) { Init(); string paramName = itsNeonsDB->GetGridParameterName(fmiParameterId, codeTableVersion, codeTableVersion); return paramName; } string neons::GribParameterName(const long fmiParameterId, const long category, const long discipline, const long producer) { Init(); string paramName = itsNeonsDB->GetGridParameterName(fmiParameterId, category, discipline, producer); return paramName; } <commit_msg>Remove consts from long's ; Use leveltype to determine levelname instead of the levelname variable which might or might not be set<commit_after>/** * @file neons.cpp * * @date Nov 20, 2012 * @author partio */ #include "neons.h" #include "logger_factory.h" #include "plugin_factory.h" #include <thread> #include <sstream> #include "util.h" using namespace std; using namespace himan::plugin; const int MAX_WORKERS = 16; once_flag oflag; neons::neons() : itsInit(false), itsNeonsDB() { itsLogger = unique_ptr<logger> (logger_factory::Instance()->GetLog("neons")); // no lambda functions for gcc 4.4 :( // call_once(oflag, [](){ NFmiNeonsDBPool::MaxWorkers(MAX_WORKERS); }); call_once(oflag, &himan::plugin::neons::InitPool, this); } void neons::InitPool() { NFmiNeonsDBPool::Instance()->MaxWorkers(MAX_WORKERS); char* host; host = getenv("HOSTNAME"); // TODO: a smarter way to check if we are in production server if (host != NULL) { if (string(host) == "gogol.fmi.fi" || string(host) == "tolstoi.fmi.fi") { NFmiNeonsDBPool::Instance()->ExternalAuthentication(true); NFmiNeonsDBPool::Instance()->ReadWriteTransaction(true); } else if (string(host) == "jeera.fmi.fi" || string(host) == "sahrami.fmi.fi") { NFmiNeonsDBPool::Instance()->ReadWriteTransaction(true); NFmiNeonsDBPool::Instance()->Username("wetodb"); NFmiNeonsDBPool::Instance()->Password("3loHRgdio"); } } } vector<string> neons::Files(const search_options& options) { Init(); vector<string> files; string analtime = options.time.OriginDateTime()->String("%Y%m%d%H%M%S"); string levelvalue = boost::lexical_cast<string> (options.level.Value()); string ref_prod = options.configuration->SourceProducer().Name(); //producerInfo["ref_prod"]; // long proddef = options.configuration->SourceProducer().Id(); // producerInfo["producer_id"]; long no_vers = options.configuration->SourceProducer().TableVersion(); // producerInfo["no_vers"]; string level_name = HPLevelTypeToString.at(options.level.Type()); vector<vector<string> > gridgeoms = itsNeonsDB->GetGridGeoms(ref_prod, analtime, options.configuration->SourceGeomName()); if (gridgeoms.empty()) { itsLogger->Warning("No geometries found for given search options"); return files; } for (size_t i = 0; i < gridgeoms.size(); i++) { string tablename = gridgeoms[i][1]; string dset = gridgeoms[i][2]; /// @todo GFS (or in fact codetable 2) has wrong temperature parameter defined string parm_name = options.param.Name(); if (parm_name == "T-K" && no_vers == 2) { parm_name = "T-C"; } string query = "SELECT parm_name, lvl_type, lvl1_lvl2, fcst_per, file_location, file_server " "FROM "+tablename+" " "WHERE dset_id = "+dset+" " "AND parm_name = upper('"+parm_name+"') " "AND lvl_type = upper('"+level_name+"') " "AND lvl1_lvl2 = " +levelvalue+" " "AND fcst_per = "+boost::lexical_cast<string> (options.time.Step())+" " "ORDER BY dset_id, fcst_per, lvl_type, lvl1_lvl2"; itsNeonsDB->Query(query); vector<string> values = itsNeonsDB->FetchRow(); if (values.empty()) { continue; } itsLogger->Trace("Found data for parameter " + parm_name + " from neons geometry " + gridgeoms[i][0]); files.push_back(values[4]); } return files; } bool neons::Save(shared_ptr<const info> resultInfo, const string& theFileName) { Init(); stringstream query; /* * 1. Get grid information * 2. Get model information * 3. Get data set information (ie model run) * 4. Insert or update */ himan::point firstGridPoint = resultInfo->Grid()->FirstGridPoint(); /* * pas_latitude and pas_longitude cannot be checked programmatically * since f.ex. in the case for GFS in neons we have value 500 and * by calculating we have value 498. But not check these columns should * not matter as long as row_cnt, col_cnt, lat_orig and lon_orig match * (since pas_latitude and pas_longitude are derived from these anyway) */ query << "SELECT geom_name " << "FROM grid_reg_geom " << "WHERE row_cnt = " << resultInfo->Nj() << " AND col_cnt = " << resultInfo->Ni() << " AND lat_orig = " << (firstGridPoint.Y() * 1e3) << " AND long_orig = " << (firstGridPoint.X() * 1e3); // << " AND pas_latitude = " << static_cast<long> (resultInfo->Dj() * 1e3) // << " AND pas_longitude = " << static_cast<long> (resultInfo->Di() * 1e3); itsNeonsDB->Query(query.str()); vector<string> row; row = itsNeonsDB->FetchRow(); if (row.empty()) { itsLogger->Warning("Grid geometry not found from neons"); return false; } string geom_name = row[0]; query.str(""); query << "SELECT " << "nu.model_id AS process, " << "nu.ident_id AS centre, " << "m.model_name, " << "m.model_type, " << "type_smt " << "FROM " << "grid_num_model_grib nu, " << "grid_model m, " << "grid_model_name na, " << "fmi_producers f " << "WHERE f.producer_id = " << resultInfo->Producer().Id() << " AND m.model_type = f.ref_prod " << " AND nu.model_name = m.model_name " << " AND m.flag_mod = 0 " << " AND nu.model_name = na.model_name " << " AND m.model_name = na.model_name "; itsNeonsDB->Query(query.str()); row = itsNeonsDB->FetchRow(); if (row.empty()) { itsLogger->Warning("Producer definition not found from neons (id: " + boost::lexical_cast<string> (resultInfo->Producer().Id()) + ")"); return false; } string process = row[0]; //string centre = row[1]; //string model_name = row[2]; string model_type = row[3]; /* query << "SELECT " << "m.model_name, " << "model_type, " << "type_smt " << "FROM grid_num_model_grib nu, " << "grid_model m, " << "grid_model_name na " << "WHERE nu.model_id = " << info.process << " AND nu.ident_id = " << info.centre << " AND m.flag_mod = 0 " << " AND nu.model_name = na.model_name " << " AND m.model_name = na.model_name"; */ query.str(""); query << "SELECT " << "dset_id, " << "table_name, " << "rec_cnt_dset " << "FROM as_grid " << "WHERE " << "model_type = '" << model_type << "'" << " AND geom_name = '" << geom_name << "'" << " AND dset_name = 'AF'" << " AND base_date = '" << resultInfo->OriginDateTime().String("%Y%m%d%H%M") << "'"; itsNeonsDB->Query(query.str()); row = itsNeonsDB->FetchRow(); if (row.empty()) { itsLogger->Warning("Data set definition not found from neons"); return false; } string table_name = row[1]; string dset_id = row[0]; string eps_specifier = "0"; query.str(""); query << "UPDATE as_grid " << "SET rec_cnt_dset = " << "rec_cnt_dset + 1, " << "date_maj_dset = sysdate " << "WHERE dset_id = " << dset_id; try { itsNeonsDB->Execute(query.str()); } catch (int e) { itsLogger->Error("Error code: " + boost::lexical_cast<string> (e)); itsLogger->Error("Query: " + query.str()); itsNeonsDB->Rollback(); return false; } query.str(""); string host = "undetermined host"; char* hostname = getenv("HOSTNAME"); if (hostname != NULL) { host = string(hostname); } query << "INSERT INTO " << table_name << " (dset_id, parm_name, lvl_type, lvl1_lvl2, fcst_per, eps_specifier, file_location, file_server) " << "VALUES (" << dset_id << ", " << "'" << resultInfo->Param().Name() << "', " << "upper('" << resultInfo->Level().Name() << "'), " << resultInfo->Level().Value() << ", " << resultInfo->Time().Step() << ", " << "'" << eps_specifier << "', " << "'" << theFileName << "', " << "'" << host << "')"; try { itsNeonsDB->Execute(query.str()); itsNeonsDB->Commit(); } catch (int e) { if (e == 1) { // unique key violation itsLogger->Debug("Unique key violation when inserting to '" + table_name + "' -- data is already loaded"); } else { itsLogger->Error("Error code: " + boost::lexical_cast<string> (e)); itsLogger->Error("Query: " + query.str()); } itsNeonsDB->Rollback(); return false; } itsLogger->Info("Saved information on file '" + theFileName + "' to neons"); return true; } string neons::GribParameterName(long fmiParameterId, long codeTableVersion) { Init(); string paramName = itsNeonsDB->GetGridParameterName(fmiParameterId, codeTableVersion, codeTableVersion); return paramName; } string neons::GribParameterName(long fmiParameterId, long category, long discipline, long producer) { Init(); string paramName = itsNeonsDB->GetGridParameterName(fmiParameterId, category, discipline, producer); return paramName; } <|endoftext|>
<commit_before>/************************************************************************* * * 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: excel.cxx,v $ * $Revision: 1.26 $ * * 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. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sc.hxx" // ============================================================================ #include <sfx2/docfile.hxx> #include <sfx2/app.hxx> #ifndef _SVSTOR_HXX #include <sot/storage.hxx> #endif #include <sot/exchange.hxx> #include <tools/globname.hxx> #include "scitems.hxx" #include <svtools/stritem.hxx> #include "filter.hxx" #include "document.hxx" #include "xldumper.hxx" #include "xistream.hxx" #include "scerrors.hxx" #include "root.hxx" #include "imp_op.hxx" #include "excimp8.hxx" #include "exp_op.hxx" FltError ScImportExcel( SfxMedium& r, ScDocument* p ) { return ScImportExcel( r, p, EIF_AUTO ); } FltError ScImportExcel( SfxMedium& rMedium, ScDocument* pDocument, const EXCIMPFORMAT eFormat ) { // check the passed Calc document DBG_ASSERT( pDocument, "::ScImportExcel - no document" ); if( !pDocument ) return eERR_INTERN; // should not happen #if SCF_INCL_DUMPER { ::scf::dump::xls::Dumper aDumper( rMedium, pDocument->GetDocumentShell() ); aDumper.Dump(); if( !aDumper.IsImportEnabled() ) return ERRCODE_ABORT; } #endif /* Import all BIFF versions regardless on eFormat, needed for import of external cells (file type detection returns Excel4.0). */ if( (eFormat != EIF_AUTO) && (eFormat != EIF_BIFF_LE4) && (eFormat != EIF_BIFF5) && (eFormat != EIF_BIFF8) ) { DBG_ERRORFILE( "::ScImportExcel - wrong file format specification" ); return eERR_FORMAT; } // check the input stream from medium SvStream* pMedStrm = rMedium.GetInStream(); DBG_ASSERT( pMedStrm, "::ScImportExcel - medium without input stream" ); if( !pMedStrm ) return eERR_OPEN; // should not happen SvStream* pBookStrm = 0; // The "Book"/"Workbook" stream containing main data. XclBiff eBiff = EXC_BIFF_UNKNOWN; // The BIFF version of the main stream. // try to open an OLE storage SotStorageRef xRootStrg; SotStorageStreamRef xStrgStrm; if( SotStorage::IsStorageFile( pMedStrm ) ) { xRootStrg = new SotStorage( pMedStrm, FALSE ); if( xRootStrg->GetError() ) xRootStrg = 0; } // try to open "Book" or "Workbook" stream in OLE storage if( xRootStrg.Is() ) { // try to open the "Book" stream SotStorageStreamRef xBookStrm5 = ScfTools::OpenStorageStreamRead( xRootStrg, EXC_STREAM_BOOK ); XclBiff eBookStrm5Biff = xBookStrm5.Is() ? XclImpStream::DetectBiffVersion( *xBookStrm5 ) : EXC_BIFF_UNKNOWN; // try to open the "Workbook" stream SotStorageStreamRef xBookStrm8 = ScfTools::OpenStorageStreamRead( xRootStrg, EXC_STREAM_WORKBOOK ); XclBiff eBookStrm8Biff = xBookStrm8.Is() ? XclImpStream::DetectBiffVersion( *xBookStrm8 ) : EXC_BIFF_UNKNOWN; // decide which stream to use if( (eBookStrm8Biff != EXC_BIFF_UNKNOWN) && ((eBookStrm5Biff == EXC_BIFF_UNKNOWN) || (eBookStrm8Biff > eBookStrm5Biff)) ) { /* Only "Workbook" stream exists; or both streams exist, and "Workbook" has higher BIFF version than "Book" stream. */ xStrgStrm = xBookStrm8; eBiff = eBookStrm8Biff; } else if( eBookStrm5Biff != EXC_BIFF_UNKNOWN ) { /* Only "Book" stream exists; or both streams exist, and "Book" has higher BIFF version than "Workbook" stream. */ xStrgStrm = xBookStrm5; eBiff = eBookStrm5Biff; } pBookStrm = xStrgStrm; } // no "Book" or "Workbook" stream found, try plain input stream from medium (even for BIFF5+) if( !pBookStrm ) { eBiff = XclImpStream::DetectBiffVersion( *pMedStrm ); if( eBiff != EXC_BIFF_UNKNOWN ) pBookStrm = pMedStrm; } // try to import the file FltError eRet = eERR_UNKN_BIFF; if( pBookStrm ) { pBookStrm->SetBufferSize( 0x8000 ); // still needed? XclImpRootData aImpData( eBiff, rMedium, xRootStrg, *pDocument, RTL_TEXTENCODING_MS_1252 ); ::std::auto_ptr< ImportExcel > xFilter; switch( eBiff ) { case EXC_BIFF2: case EXC_BIFF3: case EXC_BIFF4: case EXC_BIFF5: xFilter.reset( new ImportExcel( aImpData, *pBookStrm ) ); break; case EXC_BIFF8: xFilter.reset( new ImportExcel8( aImpData, *pBookStrm ) ); break; default: DBG_ERROR_BIFF(); } eRet = xFilter.get() ? xFilter->Read() : eERR_INTERN; } return eRet; } FltError ScExportExcel234( SvStream& /*aStream*/, ScDocument* /*pDoc*/, ExportFormatExcel /*eFormat*/, CharSet /*eNach*/ ) { FltError eRet = eERR_NI; return eRet; } FltError ScExportExcel5( SfxMedium& rMedium, ScDocument *pDocument, const BOOL bBiff8, CharSet eNach ) { // check the passed Calc document DBG_ASSERT( pDocument, "::ScImportExcel - no document" ); if( !pDocument ) return eERR_INTERN; // should not happen // check the output stream from medium SvStream* pMedStrm = rMedium.GetOutStream(); DBG_ASSERT( pMedStrm, "::ScExportExcel5 - medium without output stream" ); if( !pMedStrm ) return eERR_OPEN; // should not happen // try to open an OLE storage SotStorageRef xRootStrg = new SotStorage( pMedStrm, FALSE ); if( xRootStrg->GetError() ) return eERR_OPEN; // create BIFF dependent strings String aStrmName, aClipName, aClassName; if( bBiff8 ) { aStrmName = EXC_STREAM_WORKBOOK; aClipName = CREATE_STRING( "Biff8" ); aClassName = CREATE_STRING( "Microsoft Excel 97-Tabelle" ); } else { aStrmName = EXC_STREAM_BOOK; aClipName = CREATE_STRING( "Biff5" ); aClassName = CREATE_STRING( "Microsoft Excel 5.0-Tabelle" ); } // open the "Book"/"Workbook" stream SotStorageStreamRef xStrgStrm = ScfTools::OpenStorageStreamWrite( xRootStrg, aStrmName ); if( !xStrgStrm.Is() || xStrgStrm->GetError() ) return eERR_OPEN; xStrgStrm->SetBufferSize( 0x8000 ); // still needed? FltError eRet = eERR_UNKN_BIFF; XclExpRootData aExpData( bBiff8 ? EXC_BIFF8 : EXC_BIFF5, rMedium, xRootStrg, *pDocument, eNach ); if ( bBiff8 ) { ExportBiff8 aFilter( aExpData, *xStrgStrm ); eRet = aFilter.Write(); } else { ExportBiff5 aFilter( aExpData, *xStrgStrm ); eRet = aFilter.Write(); } if( eRet == eERR_RNGOVRFLW ) eRet = SCWARN_EXPORT_MAXROW; SvGlobalName aGlobName( 0x00020810, 0x0000, 0x0000, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46 ); sal_uInt32 nClip = SotExchange::RegisterFormatName( aClipName ); xRootStrg->SetClass( aGlobName, nClip, aClassName ); xStrgStrm->Commit(); xRootStrg->Commit(); return eRet; } <commit_msg>INTEGRATION: CWS dr61 (1.26.16); FILE MERGED 2008/05/19 12:24:00 dr 1.26.16.1: #i10000# removed remaining include guards<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: excel.cxx,v $ * $Revision: 1.27 $ * * 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. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sc.hxx" #include <sfx2/docfile.hxx> #include <sfx2/app.hxx> #include <sot/storage.hxx> #include <sot/exchange.hxx> #include <tools/globname.hxx> #include "scitems.hxx" #include <svtools/stritem.hxx> #include "filter.hxx" #include "document.hxx" #include "xldumper.hxx" #include "xistream.hxx" #include "scerrors.hxx" #include "root.hxx" #include "imp_op.hxx" #include "excimp8.hxx" #include "exp_op.hxx" FltError ScImportExcel( SfxMedium& r, ScDocument* p ) { return ScImportExcel( r, p, EIF_AUTO ); } FltError ScImportExcel( SfxMedium& rMedium, ScDocument* pDocument, const EXCIMPFORMAT eFormat ) { // check the passed Calc document DBG_ASSERT( pDocument, "::ScImportExcel - no document" ); if( !pDocument ) return eERR_INTERN; // should not happen #if SCF_INCL_DUMPER { ::scf::dump::xls::Dumper aDumper( rMedium, pDocument->GetDocumentShell() ); aDumper.Dump(); if( !aDumper.IsImportEnabled() ) return ERRCODE_ABORT; } #endif /* Import all BIFF versions regardless on eFormat, needed for import of external cells (file type detection returns Excel4.0). */ if( (eFormat != EIF_AUTO) && (eFormat != EIF_BIFF_LE4) && (eFormat != EIF_BIFF5) && (eFormat != EIF_BIFF8) ) { DBG_ERRORFILE( "::ScImportExcel - wrong file format specification" ); return eERR_FORMAT; } // check the input stream from medium SvStream* pMedStrm = rMedium.GetInStream(); DBG_ASSERT( pMedStrm, "::ScImportExcel - medium without input stream" ); if( !pMedStrm ) return eERR_OPEN; // should not happen SvStream* pBookStrm = 0; // The "Book"/"Workbook" stream containing main data. XclBiff eBiff = EXC_BIFF_UNKNOWN; // The BIFF version of the main stream. // try to open an OLE storage SotStorageRef xRootStrg; SotStorageStreamRef xStrgStrm; if( SotStorage::IsStorageFile( pMedStrm ) ) { xRootStrg = new SotStorage( pMedStrm, FALSE ); if( xRootStrg->GetError() ) xRootStrg = 0; } // try to open "Book" or "Workbook" stream in OLE storage if( xRootStrg.Is() ) { // try to open the "Book" stream SotStorageStreamRef xBookStrm5 = ScfTools::OpenStorageStreamRead( xRootStrg, EXC_STREAM_BOOK ); XclBiff eBookStrm5Biff = xBookStrm5.Is() ? XclImpStream::DetectBiffVersion( *xBookStrm5 ) : EXC_BIFF_UNKNOWN; // try to open the "Workbook" stream SotStorageStreamRef xBookStrm8 = ScfTools::OpenStorageStreamRead( xRootStrg, EXC_STREAM_WORKBOOK ); XclBiff eBookStrm8Biff = xBookStrm8.Is() ? XclImpStream::DetectBiffVersion( *xBookStrm8 ) : EXC_BIFF_UNKNOWN; // decide which stream to use if( (eBookStrm8Biff != EXC_BIFF_UNKNOWN) && ((eBookStrm5Biff == EXC_BIFF_UNKNOWN) || (eBookStrm8Biff > eBookStrm5Biff)) ) { /* Only "Workbook" stream exists; or both streams exist, and "Workbook" has higher BIFF version than "Book" stream. */ xStrgStrm = xBookStrm8; eBiff = eBookStrm8Biff; } else if( eBookStrm5Biff != EXC_BIFF_UNKNOWN ) { /* Only "Book" stream exists; or both streams exist, and "Book" has higher BIFF version than "Workbook" stream. */ xStrgStrm = xBookStrm5; eBiff = eBookStrm5Biff; } pBookStrm = xStrgStrm; } // no "Book" or "Workbook" stream found, try plain input stream from medium (even for BIFF5+) if( !pBookStrm ) { eBiff = XclImpStream::DetectBiffVersion( *pMedStrm ); if( eBiff != EXC_BIFF_UNKNOWN ) pBookStrm = pMedStrm; } // try to import the file FltError eRet = eERR_UNKN_BIFF; if( pBookStrm ) { pBookStrm->SetBufferSize( 0x8000 ); // still needed? XclImpRootData aImpData( eBiff, rMedium, xRootStrg, *pDocument, RTL_TEXTENCODING_MS_1252 ); ::std::auto_ptr< ImportExcel > xFilter; switch( eBiff ) { case EXC_BIFF2: case EXC_BIFF3: case EXC_BIFF4: case EXC_BIFF5: xFilter.reset( new ImportExcel( aImpData, *pBookStrm ) ); break; case EXC_BIFF8: xFilter.reset( new ImportExcel8( aImpData, *pBookStrm ) ); break; default: DBG_ERROR_BIFF(); } eRet = xFilter.get() ? xFilter->Read() : eERR_INTERN; } return eRet; } FltError ScExportExcel234( SvStream& /*aStream*/, ScDocument* /*pDoc*/, ExportFormatExcel /*eFormat*/, CharSet /*eNach*/ ) { FltError eRet = eERR_NI; return eRet; } FltError ScExportExcel5( SfxMedium& rMedium, ScDocument *pDocument, const BOOL bBiff8, CharSet eNach ) { // check the passed Calc document DBG_ASSERT( pDocument, "::ScImportExcel - no document" ); if( !pDocument ) return eERR_INTERN; // should not happen // check the output stream from medium SvStream* pMedStrm = rMedium.GetOutStream(); DBG_ASSERT( pMedStrm, "::ScExportExcel5 - medium without output stream" ); if( !pMedStrm ) return eERR_OPEN; // should not happen // try to open an OLE storage SotStorageRef xRootStrg = new SotStorage( pMedStrm, FALSE ); if( xRootStrg->GetError() ) return eERR_OPEN; // create BIFF dependent strings String aStrmName, aClipName, aClassName; if( bBiff8 ) { aStrmName = EXC_STREAM_WORKBOOK; aClipName = CREATE_STRING( "Biff8" ); aClassName = CREATE_STRING( "Microsoft Excel 97-Tabelle" ); } else { aStrmName = EXC_STREAM_BOOK; aClipName = CREATE_STRING( "Biff5" ); aClassName = CREATE_STRING( "Microsoft Excel 5.0-Tabelle" ); } // open the "Book"/"Workbook" stream SotStorageStreamRef xStrgStrm = ScfTools::OpenStorageStreamWrite( xRootStrg, aStrmName ); if( !xStrgStrm.Is() || xStrgStrm->GetError() ) return eERR_OPEN; xStrgStrm->SetBufferSize( 0x8000 ); // still needed? FltError eRet = eERR_UNKN_BIFF; XclExpRootData aExpData( bBiff8 ? EXC_BIFF8 : EXC_BIFF5, rMedium, xRootStrg, *pDocument, eNach ); if ( bBiff8 ) { ExportBiff8 aFilter( aExpData, *xStrgStrm ); eRet = aFilter.Write(); } else { ExportBiff5 aFilter( aExpData, *xStrgStrm ); eRet = aFilter.Write(); } if( eRet == eERR_RNGOVRFLW ) eRet = SCWARN_EXPORT_MAXROW; SvGlobalName aGlobName( 0x00020810, 0x0000, 0x0000, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46 ); sal_uInt32 nClip = SotExchange::RegisterFormatName( aClipName ); xRootStrg->SetClass( aGlobName, nClip, aClassName ); xStrgStrm->Commit(); xRootStrg->Commit(); return eRet; } <|endoftext|>
<commit_before>/*! \copyright (c) RDO-Team, 2012 \file rdolocale.cpp \authors Пройдаков Евгений ([email protected]) \authors Урусов Андрей ([email protected]) \date 20.10.2012 \brief Настройка локали для РДО \indent 4T */ // ----------------------------------------------------------------------- PLATFORM // ----------------------------------------------------------------------- INCLUDES #include <boost/math/special_functions/nonfinite_num_facets.hpp> #include <iostream> // ----------------------------------------------------------------------- SYNOPSIS #include "utils/rdolocale.h" // -------------------------------------------------------------------------------- namespace rdo { void setup_locale() { std::locale default_locale(std::locale::classic()); std::locale C99_out_locale(default_locale, new boost::math::nonfinite_num_put<char>); std::locale C99_in_locale(default_locale, new boost::math::nonfinite_num_get<char>); std::cout.imbue(C99_out_locale); std::cerr.imbue(C99_out_locale); std::clog.imbue(C99_out_locale); std::cin.imbue(C99_in_locale); } void locale::init() { rdo::locale& locale = get(); std::locale sourceCodeLocale = locale.utf8(); std::locale::global(sourceCodeLocale); #ifdef COMPILER_VISUAL_STUDIO setlocale(LC_ALL, ".ACP"); #endif std::locale C99_out_locale(std::locale::classic(), new boost::math::nonfinite_num_put<char>); std::locale C99_in_locale (std::locale::classic(), new boost::math::nonfinite_num_get<char>); std::cout.imbue(C99_out_locale); std::cerr.imbue(C99_out_locale); std::clog.imbue(C99_out_locale); std::cin.imbue (C99_in_locale ); } locale& locale::get() { static rdo::locale locale; return locale; } locale::locale() { m_generator.locale_cache_enabled(true); system(); cp1251(); utf8 (); } std::locale locale::generate(const std::string& name) { return m_generator.generate(name); } std::locale locale::system() { return generate(""); } std::locale locale::cp1251() { return generate("ru_RU.CP1251"); } std::locale locale::utf8() { return generate("ru_RU.UTF-8"); } std::locale locale::c() { return generate(setlocale(LC_ALL, NULL)); } std::string locale::convert(const std::string& txt, const std::locale& to, const std::locale& from) { return convert(txt, std::use_facet<boost::locale::info>(to).encoding(), std::use_facet<boost::locale::info>(from).encoding()); } std::string locale::convert(const std::string& txt, const std::string& to, const std::string& from) { std::string result; try { result = boost::locale::conv::between(txt, to, from); } catch (const boost::locale::conv::conversion_error&) {} catch (const boost::locale::conv::invalid_charset_error&) {} return result; } std::string locale::convertToCLocale(const std::string& txt, const std::locale& from) { return convert(txt, getCLocaleName(), std::use_facet<boost::locale::info>(from).encoding()); } std::string locale::convertFromCLocale(const std::string& txt, const std::locale& to) { return convert(txt, std::use_facet<boost::locale::info>(to).encoding(), getCLocaleName()); } std::string locale::getCLocaleName() { std::string cLocale = setlocale(LC_ALL, NULL); #ifdef COMPILER_VISUAL_STUDIO std::string::size_type pos = cLocale.find('.'); if (pos != std::string::npos) { cLocale = "CP" + cLocale.substr(pos + 1); } #endif return cLocale; } } // namespace rdo <commit_msg> - новая инициализация локали<commit_after>/*! \copyright (c) RDO-Team, 2012 \file rdolocale.cpp \authors Пройдаков Евгений ([email protected]) \authors Урусов Андрей ([email protected]) \date 20.10.2012 \brief Настройка локали для РДО \indent 4T */ // ----------------------------------------------------------------------- PLATFORM // ----------------------------------------------------------------------- INCLUDES #include <boost/math/special_functions/nonfinite_num_facets.hpp> #include <iostream> // ----------------------------------------------------------------------- SYNOPSIS #include "utils/rdolocale.h" // -------------------------------------------------------------------------------- namespace rdo { void setup_locale() { std::locale default_locale(std::locale::classic()); std::locale C99_out_locale(default_locale, new boost::math::nonfinite_num_put<char>); std::locale C99_in_locale(default_locale, new boost::math::nonfinite_num_get<char>); std::cout.imbue(C99_out_locale); std::cerr.imbue(C99_out_locale); std::clog.imbue(C99_out_locale); std::cin.imbue(C99_in_locale); } void locale::init() { rdo::locale& locale = get(); std::locale sourceCodeLocale = locale.utf8(); std::locale::global(sourceCodeLocale); #ifdef COMPILER_VISUAL_STUDIO setlocale(LC_ALL, ".ACP"); #endif std::locale C99_out_locale(sourceCodeLocale, new boost::math::nonfinite_num_put<char>); std::locale C99_in_locale (sourceCodeLocale, new boost::math::nonfinite_num_get<char>); std::cout.imbue(sourceCodeLocale); std::cerr.imbue(sourceCodeLocale); std::clog.imbue(sourceCodeLocale); std::cin.imbue (sourceCodeLocale); } locale& locale::get() { static rdo::locale locale; return locale; } locale::locale() { m_generator.locale_cache_enabled(true); system(); cp1251(); utf8 (); } std::locale locale::generate(const std::string& name) { return m_generator.generate(name); } std::locale locale::system() { return generate(""); } std::locale locale::cp1251() { return generate("ru_RU.CP1251"); } std::locale locale::utf8() { return generate("ru_RU.UTF-8"); } std::locale locale::c() { return generate(setlocale(LC_ALL, NULL)); } std::string locale::convert(const std::string& txt, const std::locale& to, const std::locale& from) { return convert(txt, std::use_facet<boost::locale::info>(to).encoding(), std::use_facet<boost::locale::info>(from).encoding()); } std::string locale::convert(const std::string& txt, const std::string& to, const std::string& from) { std::string result; try { result = boost::locale::conv::between(txt, to, from); } catch (const boost::locale::conv::conversion_error&) {} catch (const boost::locale::conv::invalid_charset_error&) {} return result; } std::string locale::convertToCLocale(const std::string& txt, const std::locale& from) { return convert(txt, getCLocaleName(), std::use_facet<boost::locale::info>(from).encoding()); } std::string locale::convertFromCLocale(const std::string& txt, const std::locale& to) { return convert(txt, std::use_facet<boost::locale::info>(to).encoding(), getCLocaleName()); } std::string locale::getCLocaleName() { std::string cLocale = setlocale(LC_ALL, NULL); #ifdef COMPILER_VISUAL_STUDIO std::string::size_type pos = cLocale.find('.'); if (pos != std::string::npos) { cLocale = "CP" + cLocale.substr(pos + 1); } #endif return cLocale; } } // namespace rdo <|endoftext|>
<commit_before><commit_msg>Let's make this more consistent / readable.<commit_after><|endoftext|>
<commit_before>#include "nsearch/TextReader.h" #include "nsearch/Utils.h" #include <fcntl.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> /* * TextStreamReader */ TextStreamReader::TextStreamReader( std::istream& is ) : mInput( is ) { mInput.seekg( 0, mInput.end ); mTotalBytes = mInput.tellg(); mInput.seekg( 0, mInput.beg ); } size_t TextStreamReader::NumBytesRead() const { std::streampos pos = mInput.tellg(); return pos < 0 ? mTotalBytes : pos; } size_t TextStreamReader::NumBytesTotal() const { return mTotalBytes; } bool TextStreamReader::EndOfFile() const { return !mInput || mInput.peek() == EOF; } inline bool IsBlank( const std::string& str ) { return str.empty() || std::all_of( str.begin(), str.end(), isspace ); } void TextStreamReader::operator>>( std::string& str ) { do { getline( mInput, str ); } while( !EndOfFile() && IsBlank( str ) ); } /* * TextFileReader */ void TextFileReader::NextBuffer() { #ifdef USE_ZLIB if( mGzFile ) { mBufferSize = gzread( mGzFile, mBuffer, mTotalBufferSize ); } else #endif { mBufferSize = read( mFd, mBuffer, mTotalBufferSize ); } mBufferPos = 0; } TextFileReader::TextFileReader( const std::string& fileName, const size_t totalBufferSize ) : mBufferPos( -1 ), mBufferSize( 0 ), mTotalBufferSize( totalBufferSize ), mBuffer( NULL ) { mFd = open( fileName.c_str(), O_RDONLY ); // orly? if( mFd != -1 ) { #ifdef USE_ZLIB mGzFile = NULL; // Check for GZ magic number uint8_t magic[ 2 ] = { 0, 0 }; read( mFd, magic, 2 ); lseek( mFd, 0, SEEK_SET ); if( magic[ 0 ] == 0x1F && magic[ 1 ] == 0x8B ) { mGzFile = gzdopen( mFd, "rb" ); } #endif mBuffer = new char[ totalBufferSize ]; mTotalBytes = lseek( mFd, 0, SEEK_END ); lseek( mFd, 0, SEEK_SET ); NextBuffer(); } } TextFileReader::~TextFileReader() { delete[] mBuffer; close( mFd ); } void TextFileReader::operator>>( std::string& str ) { str.clear(); ReadLine: while( !EndOfFile() ) { char* pos = ( char* ) memchr( mBuffer + mBufferPos, '\n', mBufferSize - mBufferPos ); if( pos == NULL ) { str += std::string( mBuffer + mBufferPos, mBufferSize - mBufferPos ); NextBuffer(); } else { size_t numBytes = pos - ( mBuffer + mBufferPos ); str += std::string( mBuffer + mBufferPos, numBytes ); mBufferPos += numBytes + 1; // skip '\n' if( mBufferPos >= mBufferSize ) NextBuffer(); break; } } if( IsBlank( str ) && !EndOfFile() ) goto ReadLine; } bool TextFileReader::EndOfFile() const { return mFd == -1 || mBufferSize <= 0; } size_t TextFileReader::NumBytesRead() const { if( EndOfFile() ) { return mTotalBytes; } else { #ifdef USE_ZLIB if( mGzFile ) { return gzseek( mGzFile, 0, SEEK_CUR ); } else #endif { return lseek( mFd, 0, SEEK_CUR ); } } } size_t TextFileReader::NumBytesTotal() const { return mTotalBytes; } <commit_msg>Fix gz read stat<commit_after>#include "nsearch/TextReader.h" #include "nsearch/Utils.h" #include <fcntl.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> /* * TextStreamReader */ TextStreamReader::TextStreamReader( std::istream& is ) : mInput( is ) { mInput.seekg( 0, mInput.end ); mTotalBytes = mInput.tellg(); mInput.seekg( 0, mInput.beg ); } size_t TextStreamReader::NumBytesRead() const { std::streampos pos = mInput.tellg(); return pos < 0 ? mTotalBytes : pos; } size_t TextStreamReader::NumBytesTotal() const { return mTotalBytes; } bool TextStreamReader::EndOfFile() const { return !mInput || mInput.peek() == EOF; } inline bool IsBlank( const std::string& str ) { return str.empty() || std::all_of( str.begin(), str.end(), isspace ); } void TextStreamReader::operator>>( std::string& str ) { do { getline( mInput, str ); } while( !EndOfFile() && IsBlank( str ) ); } /* * TextFileReader */ void TextFileReader::NextBuffer() { #ifdef USE_ZLIB if( mGzFile ) { mBufferSize = gzread( mGzFile, mBuffer, mTotalBufferSize ); } else #endif { mBufferSize = read( mFd, mBuffer, mTotalBufferSize ); } mBufferPos = 0; } TextFileReader::TextFileReader( const std::string& fileName, const size_t totalBufferSize ) : mBufferPos( -1 ), mBufferSize( 0 ), mTotalBufferSize( totalBufferSize ), mBuffer( NULL ) { mFd = open( fileName.c_str(), O_RDONLY ); // orly? if( mFd != -1 ) { #ifdef USE_ZLIB mGzFile = NULL; // Check for GZ magic number uint8_t magic[ 2 ] = { 0, 0 }; read( mFd, magic, 2 ); lseek( mFd, 0, SEEK_SET ); if( magic[ 0 ] == 0x1F && magic[ 1 ] == 0x8B ) { mGzFile = gzdopen( mFd, "rb" ); } #endif mBuffer = new char[ totalBufferSize ]; mTotalBytes = lseek( mFd, 0, SEEK_END ); lseek( mFd, 0, SEEK_SET ); NextBuffer(); } } TextFileReader::~TextFileReader() { delete[] mBuffer; close( mFd ); } void TextFileReader::operator>>( std::string& str ) { str.clear(); ReadLine: while( !EndOfFile() ) { char* pos = ( char* ) memchr( mBuffer + mBufferPos, '\n', mBufferSize - mBufferPos ); if( pos == NULL ) { str += std::string( mBuffer + mBufferPos, mBufferSize - mBufferPos ); NextBuffer(); } else { size_t numBytes = pos - ( mBuffer + mBufferPos ); str += std::string( mBuffer + mBufferPos, numBytes ); mBufferPos += numBytes + 1; // skip '\n' if( mBufferPos >= mBufferSize ) NextBuffer(); break; } } if( IsBlank( str ) && !EndOfFile() ) goto ReadLine; } bool TextFileReader::EndOfFile() const { return mFd == -1 || mBufferSize <= 0; } size_t TextFileReader::NumBytesRead() const { if( EndOfFile() ) { return mTotalBytes; } else { return lseek( mFd, 0, SEEK_CUR ); } } size_t TextFileReader::NumBytesTotal() const { return mTotalBytes; } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: xltools.hxx,v $ * * $Revision: 1.20 $ * * last change: $Author: rt $ $Date: 2005-01-28 17:21:49 $ * * 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 SC_XLTOOLS_HXX #define SC_XLTOOLS_HXX #ifndef _LANG_HXX #include <tools/lang.hxx> #endif #ifndef SC_ADDRESS_HXX #include "address.hxx" #endif #ifndef SC_FTOOLS_HXX #include "ftools.hxx" #endif // BIFF versions ============================================================== #define DBG_ERROR_BIFF() DBG_ERRORFILE( "Unknown BIFF type!" ) #define DBG_ASSERT_BIFF( c ) DBG_ASSERT( c, "Unknown BIFF type!" ) // Enumerations =============================================================== /** An enumeration for all Excel error codes and the values true and false. */ enum XclBoolError { xlErrNull, /// The error code #NULL! xlErrDiv0, /// The error code #DIV/0! xlErrValue, /// The error code #VALUE! xlErrRef, /// The error code #REF! xlErrName, /// The error code #NAME? xlErrNum, /// The error code #NUM! xlErrNA, /// The error code #N/A! xlErrTrue, /// The Boolean value true. xlErrFalse, /// The Boolean value false. xlErrUnknown /// For unknown codes and values. }; // GUID import/export ========================================================= class XclImpStream; class XclExpStream; /** This struct stores a GUID (class ID) and supports reading, writing and comparison. */ struct XclGuid { sal_uInt8 mpnData[ 16 ]; /// Stores GUID always in little endian. explicit XclGuid(); explicit XclGuid( sal_uInt32 nData1, sal_uInt16 nData2, sal_uInt16 nData3, sal_uInt8 nData41, sal_uInt8 nData42, sal_uInt8 nData43, sal_uInt8 nData44, sal_uInt8 nData45, sal_uInt8 nData46, sal_uInt8 nData47, sal_uInt8 nData48 ); }; bool operator==( const XclGuid& rCmp1, const XclGuid& rCmp2 ); inline bool operator!=( const XclGuid& rCmp1, const XclGuid& rCmp2 ) { return !(rCmp1 == rCmp2); } XclImpStream& operator>>( XclImpStream& rStrm, XclGuid& rGuid ); XclExpStream& operator<<( XclExpStream& rStrm, const XclGuid& rGuid ); // Excel Tools ================================================================ class SvStream; class ScDocument; class ScAddress; class ScRange; class ScRangeList; /** This class contains static helper methods for the Excel import and export filters. */ class XclTools : ScfNoInstance { public: // GUID's --------------------------------------------------------------------- static const XclGuid maGuidStdLink; /// GUID of StdLink (HLINK record). static const XclGuid maGuidUrlMoniker; /// GUID of URL moniker (HLINK record). static const XclGuid maGuidFileMoniker; /// GUID of file moniker (HLINK record). // numeric conversion --------------------------------------------------------- /** Calculates the double value from an RK value (encoded integer or double). */ static double GetDoubleFromRK( sal_Int32 nRKValue ); /** Calculates an RK value (encoded integer or double) from a double value. @param rnRKValue Returns the calculated RK value. @param fValue The double value. @return true = An RK value could be created. */ static bool GetRKFromDouble( sal_Int32& rnRKValue, double fValue ); /** Calculates an angle (in 1/100 of degrees) from an Excel angle value. @param nRotForStacked This value will be returned, if nXclRot contains 'stacked'. */ static sal_Int32 GetScRotation( sal_uInt16 nXclRot, sal_Int32 nRotForStacked ); /** Calculates the Excel angle value from an angle in 1/100 of degrees. */ static sal_uInt8 GetXclRotation( sal_Int32 nScRot ); /** Converts a Calc error code to an Excel error code. */ static sal_uInt8 GetXclErrorCode( USHORT nScError ); /** Converts an Excel error code to a Calc error code. */ static USHORT GetScErrorCode( sal_uInt8 nXclError ); /** Gets a translated error code or Boolean value from Excel error codes. @param rfDblValue Returns 0.0 for error codes or the value of a Boolean (0.0 or 1.0). @param bErrorOrBool false = nError is a Boolean value; true = is an error value. @param nValue The error code or Boolean value. */ static XclBoolError ErrorToEnum( double& rfDblValue, sal_uInt8 bErrOrBool, sal_uInt8 nValue ); /** Returns the length in twips calculated from a length in inches. */ static sal_uInt16 GetTwipsFromInch( double fInches ); /** Returns the length in twips calculated from a length in 1/100 mm. */ static sal_uInt16 GetTwipsFromHmm( sal_Int32 nHmm ); /** Returns the length in inches calculated from a length in twips. */ static double GetInchFromTwips( sal_Int32 nTwips ); /** Returns the length in inches calculated from a length in 1/100 mm. */ static double GetInchFromHmm( sal_Int32 nHmm ); /** Returns the length in 1/100 mm calculated from a length in inches. */ static sal_Int32 GetHmmFromInch( double fInches ); /** Returns the length in 1/100 mm calculated from a length in twips. */ static sal_Int32 GetHmmFromTwips( sal_Int32 nTwips ); /** Returns the Calc column width (twips) for the passed Excel width. @param nScCharWidth Width of the '0' character in Calc (twips). */ static USHORT GetScColumnWidth( sal_uInt16 nXclWidth, long nScCharWidth ); /** Returns the Excel column width for the passed Calc width (twips). @param nScCharWidth Width of the '0' character in Calc (twips). */ static sal_uInt16 GetXclColumnWidth( USHORT nScWidth, long nScCharWidth ); /** Returns a correction value to convert column widths from/to default column widths. @param nXclDefFontHeight Excel height of application default font. */ static double GetXclDefColWidthCorrection( long nXclDefFontHeight ); // cell/range addresses ------------------------------------------------------- /** Creates an ScAddress object from the passed Excel cell address. */ static ScAddress MakeScAddress( sal_uInt16 nXclCol, sal_uInt16 nXclRow, SCTAB nScTab ); /** Creates an ScRange object from the passed Excel cell range address. */ static ScRange MakeScRange( sal_uInt16 nStartXclCol, sal_uInt16 nStartXclRow, SCTAB nStartScTab, sal_uInt16 nEndXclCol, sal_uInt16 nEndXclRow, SCTAB nEndScTab ); /** Writes a cell range list using an index and count. @descr The list has the following format (all values 16 bit): (range count); n * (first row; last row; first column; last column). @param nFirstRange is the index to the start of the list. @param nRangeCount is the cell range count to be written. */ static void WriteRangeList( XclExpStream& rStrm, const ScRangeList& rRanges, ULONG nFirstRange, ULONG nRangeCount); // text encoding -------------------------------------------------------------- /** Returns a text encoding from an Excel code page. @return The corresponding text encoding or RTL_TEXTENCODING_DONTKNOW. */ static rtl_TextEncoding GetTextEncoding( sal_uInt16 nCodePage ); /** Returns an Excel code page from a text encoding. */ static sal_uInt16 GetXclCodePage( rtl_TextEncoding eTextEnc ); // font names ----------------------------------------------------------------- /** Returns the matching Excel font name for a passed Calc font name. */ static String GetXclFontName( const String& rFontName ); // built-in defined names ----------------------------------------------------- /** Returns the raw English UI representation of a built-in defined name used in NAME records. @param cBuiltIn Excel index of the built-in name. */ static String GetXclBuiltInDefName( sal_Unicode cBuiltIn ); /** Returns the Calc UI representation of a built-in defined name used in NAME records. @descr Adds a prefix to the representation returned by GetXclBuiltInDefName(). @param cBuiltIn Excel index of the built-in name. */ static String GetBuiltInDefName( sal_Unicode cBuiltIn ); /** Returns the Excel built-in name index of the passed defined name from Calc. @descr Ignores any characters following a valid representation of a built-in name. @param pcBuiltIn (out-param) If not 0, the index of the built-in name will be returned here. @return true = passed string is a built-in name; false = user-defined name. */ static sal_Unicode GetBuiltInDefNameIndex( const String& rDefName ); // built-in style names ------------------------------------------------------- /** Returns the specified built-in cell style name. @param nStyleId The identifier of the built-in style. @param nLevel The zero-based outline level for RowLevel and ColLevel styles. @return The style name or an empty string, if the parameters are not valid. */ static String GetBuiltInStyleName( sal_uInt8 nStyleId, sal_uInt8 nLevel ); /** Returns true, if the passed string is a name of an Excel built-in style. @param pnStyleId If not 0, the found style identifier will be returned here. @param pnNextChar If not 0, the index of the char after the evaluated substring will be returned here. */ static bool IsBuiltInStyleName( const String& rStyleName, sal_uInt8* pnStyleId = 0, xub_StrLen* pnNextChar = 0 ); /** Returns the Excel built-in style identifier of a passed style name. @param rnStyleId The style identifier is returned here. @param rnLevel The zero-based outline level for RowLevel and ColLevel styles is returned here. @param rStyleName The style name to examine. @return true = passed string is a built-in style name, false = user style. */ static bool GetBuiltInStyleId( sal_uInt8& rnStyleId, sal_uInt8& rnLevel, const String& rStyleName ); // conditional formatting style names ----------------------------------------- /** Returns the style name for a single condition of a conditional formatting. @param nScTab The current Calc sheet index. @param nFormat The zero-based index of the conditional formatting. @param nCondition The zero-based index of the condition. @return A style sheet name in the form "Excel_CondFormat_<sheet>_<format>_<condition>". */ static String GetCondFormatStyleName( SCTAB nScTab, sal_Int32 nFormat, sal_uInt16 nCondition ); /** Returns true, if the passed string is a name of a conditional format style created by Excel import. @param pnNextChar If not 0, the index of the char after the evaluated substring will be returned here. */ static bool IsCondFormatStyleName( const String& rStyleName, xub_StrLen* pnNextChar = 0 ); // ---------------------------------------------------------------------------- private: static const String maDefNamePrefix; /// Prefix for built-in defined names. static const String maStyleNamePrefix; /// Prefix for built-in cell style names. static const String maCFStyleNamePrefix; /// Prefix for cond. formatting style names. }; // read/write range lists ----------------------------------------------------- /** Reads a cell range list. @descr The list has the following format (all values 16 bit): (range count); n * (first row; last row; first column; last column). The new ranges are appended to the cell range list. */ XclImpStream& operator>>( XclImpStream& rStrm, ScRangeList& rRanges ); /** Writes a cell range list. @descr The list has the following format (all values 16 bit): (range count); n * (first row; last row; first column; last column). */ XclExpStream& operator<<( XclExpStream& rStrm, const ScRangeList& rRanges ); // Rich-string formatting runs ================================================ /** Represents a formatting run for rich-strings. @descr An Excel formatting run stores the first formatted character in a rich-string and the index of a font used to format this and the following characters. */ struct XclFormatRun { sal_uInt16 mnChar; /// First character this format applies to. sal_uInt16 mnXclFont; /// Excel font index for the next characters. explicit inline XclFormatRun() : mnChar( 0 ), mnXclFont( 0 ) {} explicit inline XclFormatRun( sal_uInt16 nChar, sal_uInt16 nXclFont ) : mnChar( nChar ), mnXclFont( nXclFont ) {} }; inline bool operator==( const XclFormatRun& rLeft, const XclFormatRun& rRight ) { return (rLeft.mnChar == rRight.mnChar) && (rLeft.mnXclFont == rRight.mnXclFont); } inline bool operator<( const XclFormatRun& rLeft, const XclFormatRun& rRight ) { return (rLeft.mnChar < rRight.mnChar) || ((rLeft.mnChar == rRight.mnChar) && (rLeft.mnXclFont < rRight.mnXclFont)); } // ---------------------------------------------------------------------------- /** A vector with all formatting runs for a rich-string. */ typedef ::std::vector< XclFormatRun > XclFormatRunVec; // ============================================================================ #endif <commit_msg>INTEGRATION: CWS dr32 (1.19.2); FILE MERGED 2005/02/02 14:14:23 dr 1.19.2.3: #b6219324# #i23079# #i27871# #i35812# #i37725# new address converter, import/export of view settings 2005/01/31 14:07:42 dr 1.19.2.2: #b6219324# #i23079# #i27871# #i35812# #i37725# new ScExtDocOptions, new Excel import/export of view settings 2005/01/19 15:03:07 dr 1.19.2.1: #i40570# removed/changed constants and enums<commit_after>/************************************************************************* * * $RCSfile: xltools.hxx,v $ * * $Revision: 1.21 $ * * last change: $Author: vg $ $Date: 2005-02-21 13:47:48 $ * * 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 SC_XLTOOLS_HXX #define SC_XLTOOLS_HXX #ifndef _LANG_HXX #include <tools/lang.hxx> #endif #ifndef SC_ADDRESS_HXX #include "address.hxx" #endif #ifndef SC_FTOOLS_HXX #include "ftools.hxx" #endif // BIFF versions ============================================================== #define DBG_ERROR_BIFF() DBG_ERRORFILE( "Unknown BIFF type!" ) #define DBG_ASSERT_BIFF( c ) DBG_ASSERT( c, "Unknown BIFF type!" ) // Enumerations =============================================================== /** An enumeration for all Excel error codes and the values true and false. */ enum XclBoolError { xlErrNull, /// The error code #NULL! xlErrDiv0, /// The error code #DIV/0! xlErrValue, /// The error code #VALUE! xlErrRef, /// The error code #REF! xlErrName, /// The error code #NAME? xlErrNum, /// The error code #NUM! xlErrNA, /// The error code #N/A! xlErrTrue, /// The Boolean value true. xlErrFalse, /// The Boolean value false. xlErrUnknown /// For unknown codes and values. }; // GUID import/export ========================================================= class XclImpStream; class XclExpStream; /** This struct stores a GUID (class ID) and supports reading, writing and comparison. */ struct XclGuid { sal_uInt8 mpnData[ 16 ]; /// Stores GUID always in little endian. explicit XclGuid(); explicit XclGuid( sal_uInt32 nData1, sal_uInt16 nData2, sal_uInt16 nData3, sal_uInt8 nData41, sal_uInt8 nData42, sal_uInt8 nData43, sal_uInt8 nData44, sal_uInt8 nData45, sal_uInt8 nData46, sal_uInt8 nData47, sal_uInt8 nData48 ); }; bool operator==( const XclGuid& rCmp1, const XclGuid& rCmp2 ); inline bool operator!=( const XclGuid& rCmp1, const XclGuid& rCmp2 ) { return !(rCmp1 == rCmp2); } XclImpStream& operator>>( XclImpStream& rStrm, XclGuid& rGuid ); XclExpStream& operator<<( XclExpStream& rStrm, const XclGuid& rGuid ); // Excel Tools ================================================================ class SvStream; class ScDocument; /** This class contains static helper methods for the Excel import and export filters. */ class XclTools : ScfNoInstance { public: // GUID's ----------------------------------------------------------------- static const XclGuid maGuidStdLink; /// GUID of StdLink (HLINK record). static const XclGuid maGuidUrlMoniker; /// GUID of URL moniker (HLINK record). static const XclGuid maGuidFileMoniker; /// GUID of file moniker (HLINK record). // numeric conversion ----------------------------------------------------- /** Calculates the double value from an RK value (encoded integer or double). */ static double GetDoubleFromRK( sal_Int32 nRKValue ); /** Calculates an RK value (encoded integer or double) from a double value. @param rnRKValue Returns the calculated RK value. @param fValue The double value. @return true = An RK value could be created. */ static bool GetRKFromDouble( sal_Int32& rnRKValue, double fValue ); /** Calculates an angle (in 1/100 of degrees) from an Excel angle value. @param nRotForStacked This value will be returned, if nXclRot contains 'stacked'. */ static sal_Int32 GetScRotation( sal_uInt16 nXclRot, sal_Int32 nRotForStacked ); /** Calculates the Excel angle value from an angle in 1/100 of degrees. */ static sal_uInt8 GetXclRotation( sal_Int32 nScRot ); /** Converts a Calc error code to an Excel error code. */ static sal_uInt8 GetXclErrorCode( USHORT nScError ); /** Converts an Excel error code to a Calc error code. */ static USHORT GetScErrorCode( sal_uInt8 nXclError ); /** Gets a translated error code or Boolean value from Excel error codes. @param rfDblValue Returns 0.0 for error codes or the value of a Boolean (0.0 or 1.0). @param bErrorOrBool false = nError is a Boolean value; true = is an error value. @param nValue The error code or Boolean value. */ static XclBoolError ErrorToEnum( double& rfDblValue, sal_uInt8 bErrOrBool, sal_uInt8 nValue ); /** Returns the length in twips calculated from a length in inches. */ static sal_uInt16 GetTwipsFromInch( double fInches ); /** Returns the length in twips calculated from a length in 1/100 mm. */ static sal_uInt16 GetTwipsFromHmm( sal_Int32 nHmm ); /** Returns the length in inches calculated from a length in twips. */ static double GetInchFromTwips( sal_Int32 nTwips ); /** Returns the length in inches calculated from a length in 1/100 mm. */ static double GetInchFromHmm( sal_Int32 nHmm ); /** Returns the length in 1/100 mm calculated from a length in inches. */ static sal_Int32 GetHmmFromInch( double fInches ); /** Returns the length in 1/100 mm calculated from a length in twips. */ static sal_Int32 GetHmmFromTwips( sal_Int32 nTwips ); /** Returns the Calc column width (twips) for the passed Excel width. @param nScCharWidth Width of the '0' character in Calc (twips). */ static USHORT GetScColumnWidth( sal_uInt16 nXclWidth, long nScCharWidth ); /** Returns the Excel column width for the passed Calc width (twips). @param nScCharWidth Width of the '0' character in Calc (twips). */ static sal_uInt16 GetXclColumnWidth( USHORT nScWidth, long nScCharWidth ); /** Returns a correction value to convert column widths from/to default column widths. @param nXclDefFontHeight Excel height of application default font. */ static double GetXclDefColWidthCorrection( long nXclDefFontHeight ); // text encoding ---------------------------------------------------------- /** Returns a text encoding from an Excel code page. @return The corresponding text encoding or RTL_TEXTENCODING_DONTKNOW. */ static rtl_TextEncoding GetTextEncoding( sal_uInt16 nCodePage ); /** Returns an Excel code page from a text encoding. */ static sal_uInt16 GetXclCodePage( rtl_TextEncoding eTextEnc ); // font names ------------------------------------------------------------- /** Returns the matching Excel font name for a passed Calc font name. */ static String GetXclFontName( const String& rFontName ); // built-in defined names ------------------------------------------------- /** Returns the raw English UI representation of a built-in defined name used in NAME records. @param cBuiltIn Excel index of the built-in name. */ static String GetXclBuiltInDefName( sal_Unicode cBuiltIn ); /** Returns the Calc UI representation of a built-in defined name used in NAME records. @descr Adds a prefix to the representation returned by GetXclBuiltInDefName(). @param cBuiltIn Excel index of the built-in name. */ static String GetBuiltInDefName( sal_Unicode cBuiltIn ); /** Returns the Excel built-in name index of the passed defined name from Calc. @descr Ignores any characters following a valid representation of a built-in name. @param pcBuiltIn (out-param) If not 0, the index of the built-in name will be returned here. @return true = passed string is a built-in name; false = user-defined name. */ static sal_Unicode GetBuiltInDefNameIndex( const String& rDefName ); // built-in style names --------------------------------------------------- /** Returns the specified built-in cell style name. @param nStyleId The identifier of the built-in style. @param nLevel The zero-based outline level for RowLevel and ColLevel styles. @return The style name or an empty string, if the parameters are not valid. */ static String GetBuiltInStyleName( sal_uInt8 nStyleId, sal_uInt8 nLevel ); /** Returns true, if the passed string is a name of an Excel built-in style. @param pnStyleId If not 0, the found style identifier will be returned here. @param pnNextChar If not 0, the index of the char after the evaluated substring will be returned here. */ static bool IsBuiltInStyleName( const String& rStyleName, sal_uInt8* pnStyleId = 0, xub_StrLen* pnNextChar = 0 ); /** Returns the Excel built-in style identifier of a passed style name. @param rnStyleId The style identifier is returned here. @param rnLevel The zero-based outline level for RowLevel and ColLevel styles is returned here. @param rStyleName The style name to examine. @return true = passed string is a built-in style name, false = user style. */ static bool GetBuiltInStyleId( sal_uInt8& rnStyleId, sal_uInt8& rnLevel, const String& rStyleName ); // conditional formatting style names ------------------------------------- /** Returns the style name for a single condition of a conditional formatting. @param nScTab The current Calc sheet index. @param nFormat The zero-based index of the conditional formatting. @param nCondition The zero-based index of the condition. @return A style sheet name in the form "Excel_CondFormat_<sheet>_<format>_<condition>". */ static String GetCondFormatStyleName( SCTAB nScTab, sal_Int32 nFormat, sal_uInt16 nCondition ); /** Returns true, if the passed string is a name of a conditional format style created by Excel import. @param pnNextChar If not 0, the index of the char after the evaluated substring will be returned here. */ static bool IsCondFormatStyleName( const String& rStyleName, xub_StrLen* pnNextChar = 0 ); // ------------------------------------------------------------------------ private: static const String maDefNamePrefix; /// Prefix for built-in defined names. static const String maStyleNamePrefix; /// Prefix for built-in cell style names. static const String maCFStyleNamePrefix; /// Prefix for cond. formatting style names. }; // read/write colors ---------------------------------------------------------- /** Reads a color from the passed stream. @descr The color has the format (all values 8-bit): Red, Green, Blue, 0. */ XclImpStream& operator>>( XclImpStream& rStrm, Color& rColor ); /** Reads a color to the passed stream. @descr The color has the format (all values 8-bit): Red, Green, Blue, 0. */ XclExpStream& operator<<( XclExpStream& rStrm, const Color& rColor ); // ============================================================================ #endif <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: expbase.cxx,v $ * * $Revision: 1.9 $ * * last change: $Author: rt $ $Date: 2007-07-06 12:39:36 $ * * 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 * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sc.hxx" #include "expbase.hxx" #include "document.hxx" #include "editutil.hxx" //------------------------------------------------------------------ #if defined(UNX) const sal_Char __FAR_DATA ScExportBase::sNewLine = '\012'; #else const sal_Char __FAR_DATA ScExportBase::sNewLine[] = "\015\012"; #endif ScExportBase::ScExportBase( SvStream& rStrmP, ScDocument* pDocP, const ScRange& rRangeP ) : rStrm( rStrmP ), aRange( rRangeP ), pDoc( pDocP ), pFormatter( pDocP->GetFormatTable() ), pEditEngine( NULL ) { } ScExportBase::~ScExportBase() { delete pEditEngine; } BOOL ScExportBase::GetDataArea( SCTAB nTab, SCCOL& nStartCol, SCROW& nStartRow, SCCOL& nEndCol, SCROW& nEndRow ) const { pDoc->GetDataStart( nTab, nStartCol, nStartRow ); pDoc->GetPrintArea( nTab, nEndCol, nEndRow, TRUE ); return TrimDataArea( nTab, nStartCol, nStartRow, nEndCol, nEndRow ); } BOOL ScExportBase::TrimDataArea( SCTAB nTab, SCCOL& nStartCol, SCROW& nStartRow, SCCOL& nEndCol, SCROW& nEndRow ) const { while ( nStartCol <= nEndCol && pDoc->GetColFlags( nStartCol, nTab ) & CR_HIDDEN ) ++nStartCol; while ( nStartCol <= nEndCol && pDoc->GetColFlags( nEndCol, nTab ) & CR_HIDDEN ) --nEndCol; nStartRow = pDoc->GetRowFlagsArray( nTab).GetFirstForCondition( nStartRow, nEndRow, CR_HIDDEN, 0); nEndRow = pDoc->GetRowFlagsArray( nTab).GetLastForCondition( nStartRow, nEndRow, CR_HIDDEN, 0); return nStartCol <= nEndCol && nStartRow <= nEndRow && nEndRow != ::std::numeric_limits<SCROW>::max(); } BOOL ScExportBase::IsEmptyTable( SCTAB nTab ) const { if ( !pDoc->HasTable( nTab ) || !pDoc->IsVisible( nTab ) ) return TRUE; SCCOL nStartCol, nEndCol; SCROW nStartRow, nEndRow; return !GetDataArea( nTab, nStartCol, nStartRow, nEndCol, nEndRow ); } ScFieldEditEngine& ScExportBase::GetEditEngine() const { if ( !pEditEngine ) ((ScExportBase*)this)->pEditEngine = new ScFieldEditEngine( pDoc->GetEditPool() ); return *pEditEngine; } <commit_msg>INTEGRATION: CWS changefileheader (1.9.240); FILE MERGED 2008/03/31 17:14:50 rt 1.9.240.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: expbase.cxx,v $ * $Revision: 1.10 $ * * 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. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sc.hxx" #include "expbase.hxx" #include "document.hxx" #include "editutil.hxx" //------------------------------------------------------------------ #if defined(UNX) const sal_Char __FAR_DATA ScExportBase::sNewLine = '\012'; #else const sal_Char __FAR_DATA ScExportBase::sNewLine[] = "\015\012"; #endif ScExportBase::ScExportBase( SvStream& rStrmP, ScDocument* pDocP, const ScRange& rRangeP ) : rStrm( rStrmP ), aRange( rRangeP ), pDoc( pDocP ), pFormatter( pDocP->GetFormatTable() ), pEditEngine( NULL ) { } ScExportBase::~ScExportBase() { delete pEditEngine; } BOOL ScExportBase::GetDataArea( SCTAB nTab, SCCOL& nStartCol, SCROW& nStartRow, SCCOL& nEndCol, SCROW& nEndRow ) const { pDoc->GetDataStart( nTab, nStartCol, nStartRow ); pDoc->GetPrintArea( nTab, nEndCol, nEndRow, TRUE ); return TrimDataArea( nTab, nStartCol, nStartRow, nEndCol, nEndRow ); } BOOL ScExportBase::TrimDataArea( SCTAB nTab, SCCOL& nStartCol, SCROW& nStartRow, SCCOL& nEndCol, SCROW& nEndRow ) const { while ( nStartCol <= nEndCol && pDoc->GetColFlags( nStartCol, nTab ) & CR_HIDDEN ) ++nStartCol; while ( nStartCol <= nEndCol && pDoc->GetColFlags( nEndCol, nTab ) & CR_HIDDEN ) --nEndCol; nStartRow = pDoc->GetRowFlagsArray( nTab).GetFirstForCondition( nStartRow, nEndRow, CR_HIDDEN, 0); nEndRow = pDoc->GetRowFlagsArray( nTab).GetLastForCondition( nStartRow, nEndRow, CR_HIDDEN, 0); return nStartCol <= nEndCol && nStartRow <= nEndRow && nEndRow != ::std::numeric_limits<SCROW>::max(); } BOOL ScExportBase::IsEmptyTable( SCTAB nTab ) const { if ( !pDoc->HasTable( nTab ) || !pDoc->IsVisible( nTab ) ) return TRUE; SCCOL nStartCol, nEndCol; SCROW nStartRow, nEndRow; return !GetDataArea( nTab, nStartCol, nStartRow, nEndCol, nEndRow ); } ScFieldEditEngine& ScExportBase::GetEditEngine() const { if ( !pEditEngine ) ((ScExportBase*)this)->pEditEngine = new ScFieldEditEngine( pDoc->GetEditPool() ); return *pEditEngine; } <|endoftext|>
<commit_before>/* ATT_IOT.cpp - SmartLiving.io Arduino library */ #define DEBUG //turns on debugging in the IOT library. comment out this line to save memory. #include "ATT_IOT.h" #define RETRYDELAY 5000 //the nr of milliseconds that we pause before retrying to create the connection #define ETHERNETDELAY 1000 //the nr of milliseconds that we pause to give the ethernet board time to start #define MQTTPORT 1883 #ifdef DEBUG char HTTPSERVTEXT[] = "connection HTTP Server"; char MQTTSERVTEXT[] = "connection MQTT Server"; char FAILED_RETRY[] = " failed,retry"; char SUCCESTXT[] = " established"; #endif //create the object ATTDevice::ATTDevice(String deviceId, String clientId, String clientKey): _client(NULL), _mqttclient(NULL) { _deviceId = deviceId; _clientId = clientId; _clientKey = clientKey; } //connect with the http server bool ATTDevice::Connect(Client* httpClient, char httpServer[]) { _client = httpClient; _serverName = httpServer; //keep track of this value while working with the http server. #ifdef DEBUG Serial.print("Connecting to "); Serial.println(httpServer); #endif if (!_client->connect(httpServer, 80)) // if you get a connection, report back via serial: { #ifdef DEBUG Serial.print(HTTPSERVTEXT); Serial.println(FAILED_RETRY); #endif return false; //we have created a connection succesfully. } else{ #ifdef DEBUG Serial.print(HTTPSERVTEXT); Serial.println(SUCCESTXT); #endif delay(ETHERNETDELAY); // another small delay: sometimes the card is not yet ready to send the asset info. return true; //we have created a connection succesfully. } } //closes any open connections (http & mqtt) and resets the device. After this call, you //can call connect and/or subscribe again. Credentials remain stored. void ATTDevice::Close() { CloseHTTP(); _mqttUserName = NULL; _mqttpwd = NULL; if(_mqttclient){ _mqttclient->disconnect(); _mqttclient = NULL; } } //closes the http connection, if any. void ATTDevice::CloseHTTP() { if(_client){ #ifdef DEBUG Serial.println(F("Stopping HTTP")); #endif _client->flush(); _client->stop(); _client = NULL; } } //create or update the specified asset. void ATTDevice::AddAsset(int id, String name, String description, bool isActuator, String type) { // Make a HTTP request: { String idStr(id); _client->println("PUT /device/" + _deviceId + "/asset/" + idStr + " HTTP/1.1"); } _client->print(F("Host: ")); _client->println(_serverName); _client->println(F("Content-Type: application/json")); _client->print(F("Auth-ClientKey: "));_client->println(_clientKey); _client->print(F("Auth-ClientId: "));_client->println(_clientId); int typeLength = type.length(); _client->print(F("Content-Length: ")); { //make every mem op local, so it is unloaded asap int length = name.length() + description.length() + typeLength; if(isActuator) length += 8; else length += 6; if (typeLength == 0) length += 39; else if(type[0] == '{') length += 49; else length += 62; _client->println(length); } _client->println(); _client->print(F("{\"name\":\"")); _client->print(name); _client->print(F("\",\"description\":\"")); _client->print(description); _client->print(F("\",\"is\":\"")); if(isActuator) _client->print(F("actuator")); else _client->print(F("sensor")); if(typeLength == 0) _client->print(F("\"")); else if(type[0] == '{'){ _client->print(F("\",\"profile\": ")); _client->print(type); } else{ _client->print(F("\",\"profile\": { \"type\":\"")); _client->print(type); _client->print(F("\" }")); } _client->print(F("}")); _client->println(); _client->println(); unsigned long maxTime = millis() + 1000; while(millis() < maxTime) //wait, but for the minimum amount of time. { if(_client->available()) break; else delay(10); } GetHTTPResult(); //get the response from the server and show it. } //connect with the http server and broker bool ATTDevice::Subscribe(PubSubClient& mqttclient) { if(_clientId && _clientKey){ String brokerId = _clientId + ":" + _clientId; return Subscribe(mqttclient, brokerId.c_str(), _clientKey.c_str()); } else{ #ifdef DEBUG Serial.print(MQTTSERVTEXT); Serial.println("failed: invalid credentials"); #endif return false; } } /*Stop http processing & make certain that we can receive data from the mqtt server, given the specified username and pwd. This Subscribe function can be used to connect to a fog gateway returns true when successful, false otherwise*/ bool ATTDevice::Subscribe(PubSubClient& mqttclient, const char* username, const char* pwd) { _mqttclient = &mqttclient; _serverName = ""; //no longer need this reference. CloseHTTP(); _mqttUserName = username; _mqttpwd = pwd; return MqttConnect(); } //tries to create a connection with the mqtt broker. also used to try and reconnect. bool ATTDevice::MqttConnect() { char mqttId[23]; // Or something long enough to hold the longest file name you will ever use. int length = _deviceId.length(); length = length > 22 ? 22 : length; _deviceId.toCharArray(mqttId, length); mqttId[length] = 0; if(_mqttUserName && _mqttpwd){ if (!_mqttclient->connect(mqttId, (char*)_mqttUserName, (char*)_mqttpwd)) { #ifdef DEBUG Serial.print(MQTTSERVTEXT); Serial.println(FAILED_RETRY); #endif return false; } #ifdef DEBUG Serial.print(MQTTSERVTEXT); Serial.println(SUCCESTXT); #endif MqttSubscribe(); return true; } else{ #ifdef DEBUG Serial.print(MQTTSERVTEXT); Serial.println("failed: invalid credentials"); #endif return false; } } //check for any new mqtt messages. void ATTDevice::Process() { _mqttclient->loop(); } //builds the content that has to be sent to the cloud using mqtt (either a csv value or a json string) char* ATTDevice::BuildContent(String value) { char* message_buff; int length; if(value[0] == '[' || value[0] == '{'){ length = value.length() + 16; message_buff = new char[length]; sprintf(message_buff, "{\"value\":%s}", value.c_str()); } else{ length = value.length() + 3; message_buff = new char[length]; sprintf(message_buff, "0|%s", value.c_str()); } message_buff[length-1] = 0; return message_buff; } //send a data value to the cloud server for the sensor with the specified id. void ATTDevice::Send(String value, int id) { if(_mqttclient->connected() == false) { #ifdef DEBUG Serial.println(F("Lost broker connection,restarting")); #endif MqttConnect(); } char* message_buff = BuildContent(value); #ifdef DEBUG //don't need to write all of this if not debugging. Serial.print(F("Publish to ")); Serial.print(id); Serial.print(" : "); Serial.println(message_buff); #endif char* Mqttstring_buff; { int length = _clientId.length() + _deviceId.length() + 34; Mqttstring_buff = new char[length]; sprintf(Mqttstring_buff, "client/%s/out/device/%s/asset/%d/state", _clientId.c_str(), _deviceId.c_str(), id); Mqttstring_buff[length-1] = 0; } _mqttclient->publish(Mqttstring_buff, message_buff); delay(100); //give some time to the ethernet shield so it can process everything. delete(message_buff); delete(Mqttstring_buff); } //subscribe to the mqtt topic so we can receive data from the server. void ATTDevice::MqttSubscribe() { String MqttString = "client/" + _clientId + "/in/device/" + _deviceId + "/asset/+/command"; //the arduino is only interested in the actuator commands, no management commands char Mqttstring_buff[MqttString.length()+1]; MqttString.toCharArray(Mqttstring_buff, MqttString.length()+1); _mqttclient->subscribe(Mqttstring_buff); #ifdef DEBUG Serial.println("MQTT Client subscribed"); #endif } //returns the pin nr found in the topic int ATTDevice::GetPinNr(char* topic, int topicLength) { char digitOffset = 9; //skip the '/command' at the end of the topic int result = topic[topicLength - digitOffset] - 48; // - 48 to convert digit-char to integer digitOffset++; while(topic[topicLength - digitOffset] != '/'){ int nextDigit = topic[topicLength - digitOffset] - 48; for(int i = 9; i < digitOffset; i++) nextDigit *= 10; result += nextDigit; digitOffset++; } return result; } void ATTDevice::GetHTTPResult() { // If there's incoming data from the net connection, send it out the serial port // This is for debugging purposes only if(_client->available()){ while (_client->available()) { char c = _client->read(); #ifdef DEBUG Serial.print(c); #endif } #ifdef DEBUG Serial.println(); #endif } } <commit_msg>fixes sending state values for assets with multi digit id's<commit_after>/* ATT_IOT.cpp - SmartLiving.io Arduino library */ #define DEBUG //turns on debugging in the IOT library. comment out this line to save memory. #include "ATT_IOT.h" #define RETRYDELAY 5000 //the nr of milliseconds that we pause before retrying to create the connection #define ETHERNETDELAY 1000 //the nr of milliseconds that we pause to give the ethernet board time to start #define MQTTPORT 1883 #ifdef DEBUG char HTTPSERVTEXT[] = "connection HTTP Server"; char MQTTSERVTEXT[] = "connection MQTT Server"; char FAILED_RETRY[] = " failed,retry"; char SUCCESTXT[] = " established"; #endif //create the object ATTDevice::ATTDevice(String deviceId, String clientId, String clientKey): _client(NULL), _mqttclient(NULL) { _deviceId = deviceId; _clientId = clientId; _clientKey = clientKey; } //connect with the http server bool ATTDevice::Connect(Client* httpClient, char httpServer[]) { _client = httpClient; _serverName = httpServer; //keep track of this value while working with the http server. #ifdef DEBUG Serial.print("Connecting to "); Serial.println(httpServer); #endif if (!_client->connect(httpServer, 80)) // if you get a connection, report back via serial: { #ifdef DEBUG Serial.print(HTTPSERVTEXT); Serial.println(FAILED_RETRY); #endif return false; //we have created a connection succesfully. } else{ #ifdef DEBUG Serial.print(HTTPSERVTEXT); Serial.println(SUCCESTXT); #endif delay(ETHERNETDELAY); // another small delay: sometimes the card is not yet ready to send the asset info. return true; //we have created a connection succesfully. } } //closes any open connections (http & mqtt) and resets the device. After this call, you //can call connect and/or subscribe again. Credentials remain stored. void ATTDevice::Close() { CloseHTTP(); _mqttUserName = NULL; _mqttpwd = NULL; if(_mqttclient){ _mqttclient->disconnect(); _mqttclient = NULL; } } //closes the http connection, if any. void ATTDevice::CloseHTTP() { if(_client){ #ifdef DEBUG Serial.println(F("Stopping HTTP")); #endif _client->flush(); _client->stop(); _client = NULL; } } //create or update the specified asset. void ATTDevice::AddAsset(int id, String name, String description, bool isActuator, String type) { // Make a HTTP request: { String idStr(id); _client->println("PUT /device/" + _deviceId + "/asset/" + idStr + " HTTP/1.1"); } _client->print(F("Host: ")); _client->println(_serverName); _client->println(F("Content-Type: application/json")); _client->print(F("Auth-ClientKey: "));_client->println(_clientKey); _client->print(F("Auth-ClientId: "));_client->println(_clientId); int typeLength = type.length(); _client->print(F("Content-Length: ")); { //make every mem op local, so it is unloaded asap int length = name.length() + description.length() + typeLength; if(isActuator) length += 8; else length += 6; if (typeLength == 0) length += 39; else if(type[0] == '{') length += 49; else length += 62; _client->println(length); } _client->println(); _client->print(F("{\"name\":\"")); _client->print(name); _client->print(F("\",\"description\":\"")); _client->print(description); _client->print(F("\",\"is\":\"")); if(isActuator) _client->print(F("actuator")); else _client->print(F("sensor")); if(typeLength == 0) _client->print(F("\"")); else if(type[0] == '{'){ _client->print(F("\",\"profile\": ")); _client->print(type); } else{ _client->print(F("\",\"profile\": { \"type\":\"")); _client->print(type); _client->print(F("\" }")); } _client->print(F("}")); _client->println(); _client->println(); unsigned long maxTime = millis() + 1000; while(millis() < maxTime) //wait, but for the minimum amount of time. { if(_client->available()) break; else delay(10); } GetHTTPResult(); //get the response from the server and show it. } //connect with the http server and broker bool ATTDevice::Subscribe(PubSubClient& mqttclient) { if(_clientId && _clientKey){ String brokerId = _clientId + ":" + _clientId; return Subscribe(mqttclient, brokerId.c_str(), _clientKey.c_str()); } else{ #ifdef DEBUG Serial.print(MQTTSERVTEXT); Serial.println("failed: invalid credentials"); #endif return false; } } /*Stop http processing & make certain that we can receive data from the mqtt server, given the specified username and pwd. This Subscribe function can be used to connect to a fog gateway returns true when successful, false otherwise*/ bool ATTDevice::Subscribe(PubSubClient& mqttclient, const char* username, const char* pwd) { _mqttclient = &mqttclient; _serverName = ""; //no longer need this reference. CloseHTTP(); _mqttUserName = username; _mqttpwd = pwd; return MqttConnect(); } //tries to create a connection with the mqtt broker. also used to try and reconnect. bool ATTDevice::MqttConnect() { char mqttId[23]; // Or something long enough to hold the longest file name you will ever use. int length = _deviceId.length(); length = length > 22 ? 22 : length; _deviceId.toCharArray(mqttId, length); mqttId[length] = 0; if(_mqttUserName && _mqttpwd){ if (!_mqttclient->connect(mqttId, (char*)_mqttUserName, (char*)_mqttpwd)) { #ifdef DEBUG Serial.print(MQTTSERVTEXT); Serial.println(FAILED_RETRY); #endif return false; } #ifdef DEBUG Serial.print(MQTTSERVTEXT); Serial.println(SUCCESTXT); #endif MqttSubscribe(); return true; } else{ #ifdef DEBUG Serial.print(MQTTSERVTEXT); Serial.println("failed: invalid credentials"); #endif return false; } } //check for any new mqtt messages. void ATTDevice::Process() { _mqttclient->loop(); } //builds the content that has to be sent to the cloud using mqtt (either a csv value or a json string) char* ATTDevice::BuildContent(String value) { char* message_buff; int length; if(value[0] == '[' || value[0] == '{'){ length = value.length() + 16; message_buff = new char[length]; sprintf(message_buff, "{\"value\":%s}", value.c_str()); } else{ length = value.length() + 3; message_buff = new char[length]; sprintf(message_buff, "0|%s", value.c_str()); } message_buff[length-1] = 0; return message_buff; } //send a data value to the cloud server for the sensor with the specified id. void ATTDevice::Send(String value, int id) { if(_mqttclient->connected() == false) { #ifdef DEBUG Serial.println(F("Lost broker connection,restarting")); #endif MqttConnect(); } char* message_buff = BuildContent(value); #ifdef DEBUG //don't need to write all of this if not debugging. Serial.print(F("Publish to ")); Serial.print(id); Serial.print(" : "); Serial.println(message_buff); #endif char* Mqttstring_buff; { String idStr(id); //turn it into a string, so we can easily calculate the nr of characters that the nr requires. int length = _clientId.length() + _deviceId.length() + 33 + idStr.length(); Mqttstring_buff = new char[length]; sprintf(Mqttstring_buff, "client/%s/out/device/%s/asset/%s/state", _clientId.c_str(), _deviceId.c_str(), idStr.c_str()); Mqttstring_buff[length-1] = 0; } _mqttclient->publish(Mqttstring_buff, message_buff); delay(100); //give some time to the ethernet shield so it can process everything. delete(message_buff); delete(Mqttstring_buff); } //subscribe to the mqtt topic so we can receive data from the server. void ATTDevice::MqttSubscribe() { String MqttString = "client/" + _clientId + "/in/device/" + _deviceId + "/asset/+/command"; //the arduino is only interested in the actuator commands, no management commands char Mqttstring_buff[MqttString.length()+1]; MqttString.toCharArray(Mqttstring_buff, MqttString.length()+1); _mqttclient->subscribe(Mqttstring_buff); #ifdef DEBUG Serial.println("MQTT Client subscribed"); #endif } //returns the pin nr found in the topic int ATTDevice::GetPinNr(char* topic, int topicLength) { char digitOffset = 9; //skip the '/command' at the end of the topic int result = topic[topicLength - digitOffset] - 48; // - 48 to convert digit-char to integer digitOffset++; while(topic[topicLength - digitOffset] != '/'){ int nextDigit = topic[topicLength - digitOffset] - 48; for(int i = 9; i < digitOffset; i++) nextDigit *= 10; result += nextDigit; digitOffset++; } return result; } void ATTDevice::GetHTTPResult() { // If there's incoming data from the net connection, send it out the serial port // This is for debugging purposes only if(_client->available()){ while (_client->available()) { char c = _client->read(); #ifdef DEBUG Serial.print(c); #endif } #ifdef DEBUG Serial.println(); #endif } } <|endoftext|>
<commit_before><commit_msg>simplify SwClient::GoEnd()<commit_after><|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * Version: MPL 1.1 / GPLv3+ / LGPLv3+ * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License or as specified alternatively below. You may obtain a copy of * the License at http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * Major Contributor(s): * Copyright (C) 2012 Michael Meeks <[email protected]> (initial developer) * * All Rights Reserved. * * For minor contributions see the git repository. * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 3 or later (the "GPLv3+"), or * the GNU Lesser General Public License Version 3 or later (the "LGPLv3+"), * in which case the provisions of the GPLv3+ or the LGPLv3+ are applicable * instead of those above. */ #include "sal/config.h" #include <vector> #include "contacts.hrc" #include "sendfunc.hxx" #include "docsh.hxx" #include "scresid.hxx" #include <svtools/filter.hxx> #include <tubes/manager.hxx> #include <vcl/fixed.hxx> #include <vcl/dialog.hxx> #include <svx/simptabl.hxx> #define CONTACTS_DLG #ifdef CONTACTS_DLG namespace { class TubeContacts : public ModelessDialog { FixedLine maLabel; PushButton maBtnConnect; PushButton maBtnListen; SvxSimpleTableContainer maListContainer; SvxSimpleTable maList; DECL_LINK( BtnConnectHdl, void * ); DECL_LINK( BtnListenHdl, void * ); struct AccountContact { TpAccount* mpAccount; TpContact* mpContact; AccountContact( TpAccount* pAccount, TpContact* pContact ): mpAccount(pAccount), mpContact(pContact) {} }; boost::ptr_vector<AccountContact> maACs; void Listen() { ScDocShell *pScDocShell = dynamic_cast<ScDocShell*> (SfxObjectShell::Current()); ScDocFunc *pDocFunc = pScDocShell ? &pScDocShell->GetDocFunc() : NULL; ScDocFuncSend *pSender = dynamic_cast<ScDocFuncSend*> (pDocFunc); if (!pSender) { delete pDocFunc; boost::shared_ptr<ScDocFuncDirect> pDirect( new ScDocFuncDirect( *pScDocShell ) ); boost::shared_ptr<ScDocFuncRecv> pReceiver( new ScDocFuncRecv( pDirect ) ); pSender = new ScDocFuncSend( *pScDocShell, pReceiver ); pDocFunc = pSender; } pSender->InitTeleManager( false ); } void StartBuddySession() { AccountContact *pAC = NULL; if (maList.FirstSelected()) pAC = static_cast<AccountContact*> (maList.FirstSelected()->GetUserData()); if (pAC) { TpAccount* pAccount = pAC->mpAccount; TpContact* pContact = pAC->mpContact; fprintf( stderr, "picked %s\n", tp_contact_get_identifier( pContact ) ); TeleManager *pManager = TeleManager::get(); if (!pManager->startBuddySession( pAccount, pContact )) fprintf( stderr, "could not start session with %s\n", tp_contact_get_identifier( pContact ) ); } } public: TubeContacts() : ModelessDialog( NULL, ScResId( RID_SCDLG_CONTACTS ) ), maLabel( this, ScResId( FL_LABEL ) ), maBtnConnect( this, ScResId( BTN_CONNECT ) ), maBtnListen( this, ScResId( BTN_LISTEN ) ), maListContainer( this, ScResId( CTL_LIST ) ), maList( maListContainer ) { maBtnConnect.SetClickHdl( LINK( this, TubeContacts, BtnConnectHdl ) ); maBtnListen.SetClickHdl( LINK( this, TubeContacts, BtnListenHdl ) ); static long aStaticTabs[]= { 3 /* count */, 0, 20, 100, 150, 200 }; maList.SvxSimpleTable::SetTabs( aStaticTabs ); String sHeader( '\t' ); sHeader += String( ScResId( STR_HEADER_ALIAS ) ); sHeader += '\t'; sHeader += String( ScResId( STR_HEADER_NAME ) ); sHeader += '\t'; maList.InsertHeaderEntry( sHeader, HEADERBAR_APPEND, HIB_LEFT ); Show(); } virtual ~TubeContacts() {} static rtl::OUString fromUTF8( const char *pStr ) { return rtl::OStringToOUString( rtl::OString( pStr, strlen( pStr ) ), RTL_TEXTENCODING_UTF8 ); } void Populate( const TeleManager *pManager ) { if (!pManager) return ; ContactList *pContacts = pManager->getContactList(); if ( pContacts ) { fprintf( stderr, "contacts !\n" ); AccountContactPairV aPairs = pContacts->getContacts(); AccountContactPairV::iterator it; for( it = aPairs.begin(); it != aPairs.end(); it++ ) { Image aImage; GFile *pAvatarFile = tp_contact_get_avatar_file( it->second ); if( pAvatarFile ) { const rtl::OUString sAvatarFileUrl = fromUTF8( g_file_get_path ( pAvatarFile ) ); Graphic aGraphic; if( GRFILTER_OK == GraphicFilter::LoadGraphic( sAvatarFileUrl, rtl::OUString(""), aGraphic ) ) { BitmapEx aBitmap = aGraphic.GetBitmapEx(); double fScale = 30.0 / aBitmap.GetSizePixel().Height(); aBitmap.Scale( fScale, fScale ); aImage = Image( aBitmap ); } } fprintf( stderr, "'%s' => '%s' '%s'\n", tp_account_get_display_name( it->first ), tp_contact_get_alias( it->second ), tp_contact_get_identifier( it->second ) ); rtl::OUStringBuffer aEntry( 128 ); aEntry.append( sal_Unicode( '\t' ) ); aEntry.append( fromUTF8 ( tp_contact_get_alias( it->second ) ) ); aEntry.append( sal_Unicode( '\t' ) ); aEntry.append( fromUTF8 ( tp_contact_get_identifier( it->second ) ) ); aEntry.append( sal_Unicode( '\t' ) ); SvLBoxEntry* pEntry = maList.InsertEntry( aEntry.makeStringAndClear(), aImage, aImage ); // FIXME: ref the TpAccount, TpContact ... maACs.push_back( new AccountContact( it->first, it->second ) ); pEntry->SetUserData( &maACs.back() ); } } } }; IMPL_LINK_NOARG( TubeContacts, BtnConnectHdl ) { StartBuddySession(); Close(); return 0; } IMPL_LINK_NOARG( TubeContacts, BtnListenHdl ) { Listen(); Close(); return 0; } } // anonymous namespace #endif namespace tubes { void createContacts( const TeleManager *pManager ) { #ifdef CONTACTS_DLG TubeContacts *pContacts = new TubeContacts(); pContacts->Populate( pManager ); #endif } } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>tubes: fallback to master mode when not possible to init TeleManager as slave<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * Version: MPL 1.1 / GPLv3+ / LGPLv3+ * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License or as specified alternatively below. You may obtain a copy of * the License at http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * Major Contributor(s): * Copyright (C) 2012 Michael Meeks <[email protected]> (initial developer) * * All Rights Reserved. * * For minor contributions see the git repository. * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 3 or later (the "GPLv3+"), or * the GNU Lesser General Public License Version 3 or later (the "LGPLv3+"), * in which case the provisions of the GPLv3+ or the LGPLv3+ are applicable * instead of those above. */ #include "sal/config.h" #include <vector> #include "contacts.hrc" #include "sendfunc.hxx" #include "docsh.hxx" #include "scresid.hxx" #include <svtools/filter.hxx> #include <tubes/manager.hxx> #include <vcl/fixed.hxx> #include <vcl/dialog.hxx> #include <svx/simptabl.hxx> #define CONTACTS_DLG #ifdef CONTACTS_DLG namespace { class TubeContacts : public ModelessDialog { FixedLine maLabel; PushButton maBtnConnect; PushButton maBtnListen; SvxSimpleTableContainer maListContainer; SvxSimpleTable maList; DECL_LINK( BtnConnectHdl, void * ); DECL_LINK( BtnListenHdl, void * ); struct AccountContact { TpAccount* mpAccount; TpContact* mpContact; AccountContact( TpAccount* pAccount, TpContact* pContact ): mpAccount(pAccount), mpContact(pContact) {} }; boost::ptr_vector<AccountContact> maACs; void Listen() { ScDocShell *pScDocShell = dynamic_cast<ScDocShell*> (SfxObjectShell::Current()); ScDocFunc *pDocFunc = pScDocShell ? &pScDocShell->GetDocFunc() : NULL; ScDocFuncSend *pSender = dynamic_cast<ScDocFuncSend*> (pDocFunc); if (!pSender) { delete pDocFunc; boost::shared_ptr<ScDocFuncDirect> pDirect( new ScDocFuncDirect( *pScDocShell ) ); boost::shared_ptr<ScDocFuncRecv> pReceiver( new ScDocFuncRecv( pDirect ) ); pSender = new ScDocFuncSend( *pScDocShell, pReceiver ); pDocFunc = pSender; } // This is a hack to work around: // `error registering client handler: Name // 'org.freedesktop.Telepathy.Client.LibreOffice' already in use by another process` // This happens when there is already slave instance running, // so we try to init TeleManager as master. bool bIsMaster = false; if (!pSender->InitTeleManager( bIsMaster )) { fprintf( stderr, "Trying to initialize TeleManager as master..\n" ); bIsMaster = true; pSender->InitTeleManager( bIsMaster ); } } void StartBuddySession() { AccountContact *pAC = NULL; if (maList.FirstSelected()) pAC = static_cast<AccountContact*> (maList.FirstSelected()->GetUserData()); if (pAC) { TpAccount* pAccount = pAC->mpAccount; TpContact* pContact = pAC->mpContact; fprintf( stderr, "picked %s\n", tp_contact_get_identifier( pContact ) ); TeleManager *pManager = TeleManager::get(); if (!pManager->startBuddySession( pAccount, pContact )) fprintf( stderr, "could not start session with %s\n", tp_contact_get_identifier( pContact ) ); } } public: TubeContacts() : ModelessDialog( NULL, ScResId( RID_SCDLG_CONTACTS ) ), maLabel( this, ScResId( FL_LABEL ) ), maBtnConnect( this, ScResId( BTN_CONNECT ) ), maBtnListen( this, ScResId( BTN_LISTEN ) ), maListContainer( this, ScResId( CTL_LIST ) ), maList( maListContainer ) { maBtnConnect.SetClickHdl( LINK( this, TubeContacts, BtnConnectHdl ) ); maBtnListen.SetClickHdl( LINK( this, TubeContacts, BtnListenHdl ) ); static long aStaticTabs[]= { 3 /* count */, 0, 20, 100, 150, 200 }; maList.SvxSimpleTable::SetTabs( aStaticTabs ); String sHeader( '\t' ); sHeader += String( ScResId( STR_HEADER_ALIAS ) ); sHeader += '\t'; sHeader += String( ScResId( STR_HEADER_NAME ) ); sHeader += '\t'; maList.InsertHeaderEntry( sHeader, HEADERBAR_APPEND, HIB_LEFT ); Show(); } virtual ~TubeContacts() {} static rtl::OUString fromUTF8( const char *pStr ) { return rtl::OStringToOUString( rtl::OString( pStr, strlen( pStr ) ), RTL_TEXTENCODING_UTF8 ); } void Populate( const TeleManager *pManager ) { if (!pManager) return ; ContactList *pContacts = pManager->getContactList(); if ( pContacts ) { fprintf( stderr, "contacts !\n" ); AccountContactPairV aPairs = pContacts->getContacts(); AccountContactPairV::iterator it; for( it = aPairs.begin(); it != aPairs.end(); it++ ) { Image aImage; GFile *pAvatarFile = tp_contact_get_avatar_file( it->second ); if( pAvatarFile ) { const rtl::OUString sAvatarFileUrl = fromUTF8( g_file_get_path ( pAvatarFile ) ); Graphic aGraphic; if( GRFILTER_OK == GraphicFilter::LoadGraphic( sAvatarFileUrl, rtl::OUString(""), aGraphic ) ) { BitmapEx aBitmap = aGraphic.GetBitmapEx(); double fScale = 30.0 / aBitmap.GetSizePixel().Height(); aBitmap.Scale( fScale, fScale ); aImage = Image( aBitmap ); } } fprintf( stderr, "'%s' => '%s' '%s'\n", tp_account_get_display_name( it->first ), tp_contact_get_alias( it->second ), tp_contact_get_identifier( it->second ) ); rtl::OUStringBuffer aEntry( 128 ); aEntry.append( sal_Unicode( '\t' ) ); aEntry.append( fromUTF8 ( tp_contact_get_alias( it->second ) ) ); aEntry.append( sal_Unicode( '\t' ) ); aEntry.append( fromUTF8 ( tp_contact_get_identifier( it->second ) ) ); aEntry.append( sal_Unicode( '\t' ) ); SvLBoxEntry* pEntry = maList.InsertEntry( aEntry.makeStringAndClear(), aImage, aImage ); // FIXME: ref the TpAccount, TpContact ... maACs.push_back( new AccountContact( it->first, it->second ) ); pEntry->SetUserData( &maACs.back() ); } } } }; IMPL_LINK_NOARG( TubeContacts, BtnConnectHdl ) { StartBuddySession(); Close(); return 0; } IMPL_LINK_NOARG( TubeContacts, BtnListenHdl ) { Listen(); Close(); return 0; } } // anonymous namespace #endif namespace tubes { void createContacts( const TeleManager *pManager ) { #ifdef CONTACTS_DLG TubeContacts *pContacts = new TubeContacts(); pContacts->Populate( pManager ); #endif } } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before><commit_msg>Hopefully fix Android build<commit_after><|endoftext|>
<commit_before><commit_msg>CID#736509 memleaks on early exit<commit_after><|endoftext|>
<commit_before>#include "editor/editor_config.hpp" #include "base/stl_helpers.hpp" #include "std/algorithm.hpp" #include "std/cstring.hpp" #include "std/unordered_map.hpp" namespace { using EType = feature::Metadata::EType; // TODO(mgsergio): It would be nice to have this map generated from editor.config. static unordered_map<string, EType> const kNamesToFMD = { {"cuisine", feature::Metadata::FMD_CUISINE}, {"opening_hours", feature::Metadata::FMD_OPEN_HOURS}, {"phone", feature::Metadata::FMD_PHONE_NUMBER}, {"fax", feature::Metadata::FMD_FAX_NUMBER}, {"stars", feature::Metadata::FMD_STARS}, {"operator", feature::Metadata::FMD_OPERATOR}, // {"", feature::Metadata::FMD_URL}, {"website", feature::Metadata::FMD_WEBSITE}, {"internet", feature::Metadata::FMD_INTERNET}, {"ele", feature::Metadata::FMD_ELE}, // {"", feature::Metadata::FMD_TURN_LANES}, // {"", feature::Metadata::FMD_TURN_LANES_FORWARD}, // {"", feature::Metadata::FMD_TURN_LANES_BACKWARD}, {"email", feature::Metadata::FMD_EMAIL}, {"postcode", feature::Metadata::FMD_POSTCODE}, {"wikipedia", feature::Metadata::FMD_WIKIPEDIA}, // {"", feature::Metadata::FMD_MAXSPEED}, {"flats", feature::Metadata::FMD_FLATS}, {"height", feature::Metadata::FMD_HEIGHT}, // {"", feature::Metadata::FMD_MIN_HEIGHT}, {"denomination", feature::Metadata::FMD_DENOMINATION}, {"building:levels", feature::Metadata::FMD_BUILDING_LEVELS}, {"level", feature::Metadata::FMD_LEVEL} // description }; unordered_map<string, int> const kPriorityWeights = {{"high", 0}, {"", 1}, {"low", 2}}; bool TypeDescriptionFromXml(pugi::xml_node const & root, pugi::xml_node const & node, editor::TypeAggregatedDescription & outDesc) { if (!node || strcmp(node.attribute("editable").value(), "no") == 0) return false; auto const handleField = [&outDesc](string const & fieldName) { if (fieldName == "name") { outDesc.m_name = true; return; } if (fieldName == "street" || fieldName == "housenumber" || fieldName == "housename") { outDesc.m_address = true; return; } // TODO(mgsergio): Add support for non-metadata fields like atm, wheelchair, toilet etc. auto const it = kNamesToFMD.find(fieldName); ASSERT(it != end(kNamesToFMD), ("Wrong field:", fieldName)); outDesc.m_editableFields.push_back(it->second); }; for (auto const xNode : node.select_nodes("include[@group]")) { auto const node = xNode.node(); string const groupName = node.attribute("group").value(); string const xpath = "/mapsme/editor/fields/field_group[@name='" + groupName + "']"; auto const group = root.select_node(xpath.data()).node(); ASSERT(group, ("No such group", groupName)); for (auto const fieldRefXName : group.select_nodes("field_ref/@name")) { auto const fieldName = fieldRefXName.attribute().value(); handleField(fieldName); } } for (auto const xNode : node.select_nodes("include[@field]")) { auto const node = xNode.node(); string const fieldName = node.attribute("field").value(); handleField(fieldName); } my::SortUnique(outDesc.m_editableFields); return true; } /// The priority is defined by elems order, except elements with priority="high". vector<pugi::xml_node> GetPrioritizedTypes(pugi::xml_node const & node) { vector<pugi::xml_node> result; for (auto const xNode : node.select_nodes("/mapsme/editor/types/type[@id]")) result.push_back(xNode.node()); stable_sort(begin(result), end(result), [](pugi::xml_node const & lhs, pugi::xml_node const & rhs) { auto const lhsWeight = kPriorityWeights.find(lhs.attribute("priority").value()); auto const rhsWeight = kPriorityWeights.find(rhs.attribute("priority").value()); CHECK(lhsWeight != kPriorityWeights.end(), ("")); CHECK(rhsWeight != kPriorityWeights.end(), ("")); return lhsWeight->second < rhsWeight->second; }); return result; } } // namespace namespace editor { bool EditorConfig::GetTypeDescription(vector<string> classificatorTypes, TypeAggregatedDescription & outDesc) const { bool isBuilding = false; vector<string> addTypes; for (auto it = classificatorTypes.begin(); it != classificatorTypes.end(); ++it) { if (*it == "building") { outDesc.m_address = isBuilding = true; outDesc.m_editableFields.push_back(feature::Metadata::FMD_BUILDING_LEVELS); outDesc.m_editableFields.push_back(feature::Metadata::FMD_POSTCODE); classificatorTypes.erase(it); break; } // Adding partial types for 2..N-1 parts of a N-part type. auto hyphenPos = it->find('-'); while ((hyphenPos = it->find('-', hyphenPos+1)) != string::npos) { addTypes.push_back(it->substr(0, hyphenPos)); } } classificatorTypes.insert(classificatorTypes.end(), addTypes.begin(), addTypes.end()); auto const typeNodes = GetPrioritizedTypes(m_document); auto const it = find_if(begin(typeNodes), end(typeNodes), [&classificatorTypes](pugi::xml_node const & node) { return find(begin(classificatorTypes), end(classificatorTypes), node.attribute("id").value()) != end(classificatorTypes); }); if (it == end(typeNodes)) return isBuilding; return TypeDescriptionFromXml(m_document, *it, outDesc); } vector<string> EditorConfig::GetTypesThatCanBeAdded() const { auto const xpathResult = m_document.select_nodes("/mapsme/editor/types/type[not(@can_add='no' or @editable='no')]"); vector<string> result; for (auto const xNode : xpathResult) result.emplace_back(xNode.node().attribute("id").value()); return result; } void EditorConfig::SetConfig(pugi::xml_document const & doc) { m_document.reset(doc); } } // namespace editor <commit_msg>[editor] clang-format editor_config.cpp<commit_after>#include "editor/editor_config.hpp" #include "base/stl_helpers.hpp" #include "std/algorithm.hpp" #include "std/cstring.hpp" #include "std/unordered_map.hpp" namespace { using EType = feature::Metadata::EType; // TODO(mgsergio): It would be nice to have this map generated from editor.config. static unordered_map<string, EType> const kNamesToFMD = { {"cuisine", feature::Metadata::FMD_CUISINE}, {"opening_hours", feature::Metadata::FMD_OPEN_HOURS}, {"phone", feature::Metadata::FMD_PHONE_NUMBER}, {"fax", feature::Metadata::FMD_FAX_NUMBER}, {"stars", feature::Metadata::FMD_STARS}, {"operator", feature::Metadata::FMD_OPERATOR}, // {"", feature::Metadata::FMD_URL}, {"website", feature::Metadata::FMD_WEBSITE}, {"internet", feature::Metadata::FMD_INTERNET}, {"ele", feature::Metadata::FMD_ELE}, // {"", feature::Metadata::FMD_TURN_LANES}, // {"", feature::Metadata::FMD_TURN_LANES_FORWARD}, // {"", feature::Metadata::FMD_TURN_LANES_BACKWARD}, {"email", feature::Metadata::FMD_EMAIL}, {"postcode", feature::Metadata::FMD_POSTCODE}, {"wikipedia", feature::Metadata::FMD_WIKIPEDIA}, // {"", feature::Metadata::FMD_MAXSPEED}, {"flats", feature::Metadata::FMD_FLATS}, {"height", feature::Metadata::FMD_HEIGHT}, // {"", feature::Metadata::FMD_MIN_HEIGHT}, {"denomination", feature::Metadata::FMD_DENOMINATION}, {"building:levels", feature::Metadata::FMD_BUILDING_LEVELS}, {"level", feature::Metadata::FMD_LEVEL} // description }; unordered_map<string, int> const kPriorityWeights = {{"high", 0}, {"", 1}, {"low", 2}}; bool TypeDescriptionFromXml(pugi::xml_node const & root, pugi::xml_node const & node, editor::TypeAggregatedDescription & outDesc) { if (!node || strcmp(node.attribute("editable").value(), "no") == 0) return false; auto const handleField = [&outDesc](string const & fieldName) { if (fieldName == "name") { outDesc.m_name = true; return; } if (fieldName == "street" || fieldName == "housenumber" || fieldName == "housename") { outDesc.m_address = true; return; } // TODO(mgsergio): Add support for non-metadata fields like atm, wheelchair, toilet etc. auto const it = kNamesToFMD.find(fieldName); ASSERT(it != end(kNamesToFMD), ("Wrong field:", fieldName)); outDesc.m_editableFields.push_back(it->second); }; for (auto const xNode : node.select_nodes("include[@group]")) { auto const node = xNode.node(); string const groupName = node.attribute("group").value(); string const xpath = "/mapsme/editor/fields/field_group[@name='" + groupName + "']"; auto const group = root.select_node(xpath.data()).node(); ASSERT(group, ("No such group", groupName)); for (auto const fieldRefXName : group.select_nodes("field_ref/@name")) { auto const fieldName = fieldRefXName.attribute().value(); handleField(fieldName); } } for (auto const xNode : node.select_nodes("include[@field]")) { auto const node = xNode.node(); string const fieldName = node.attribute("field").value(); handleField(fieldName); } my::SortUnique(outDesc.m_editableFields); return true; } /// The priority is defined by elems order, except elements with priority="high". vector<pugi::xml_node> GetPrioritizedTypes(pugi::xml_node const & node) { vector<pugi::xml_node> result; for (auto const xNode : node.select_nodes("/mapsme/editor/types/type[@id]")) result.push_back(xNode.node()); stable_sort(begin(result), end(result), [](pugi::xml_node const & lhs, pugi::xml_node const & rhs) { auto const lhsWeight = kPriorityWeights.find(lhs.attribute("priority").value()); auto const rhsWeight = kPriorityWeights.find(rhs.attribute("priority").value()); CHECK(lhsWeight != kPriorityWeights.end(), ("")); CHECK(rhsWeight != kPriorityWeights.end(), ("")); return lhsWeight->second < rhsWeight->second; }); return result; } } // namespace namespace editor { bool EditorConfig::GetTypeDescription(vector<string> classificatorTypes, TypeAggregatedDescription & outDesc) const { bool isBuilding = false; vector<string> addTypes; for (auto it = classificatorTypes.begin(); it != classificatorTypes.end(); ++it) { if (*it == "building") { outDesc.m_address = isBuilding = true; outDesc.m_editableFields.push_back(feature::Metadata::FMD_BUILDING_LEVELS); outDesc.m_editableFields.push_back(feature::Metadata::FMD_POSTCODE); classificatorTypes.erase(it); break; } // Adding partial types for 2..N-1 parts of a N-part type. auto hyphenPos = it->find('-'); while ((hyphenPos = it->find('-', hyphenPos + 1)) != string::npos) { addTypes.push_back(it->substr(0, hyphenPos)); } } classificatorTypes.insert(classificatorTypes.end(), addTypes.begin(), addTypes.end()); auto const typeNodes = GetPrioritizedTypes(m_document); auto const it = find_if(begin(typeNodes), end(typeNodes), [&classificatorTypes](pugi::xml_node const & node) { return find(begin(classificatorTypes), end(classificatorTypes), node.attribute("id").value()) != end(classificatorTypes); }); if (it == end(typeNodes)) return isBuilding; return TypeDescriptionFromXml(m_document, *it, outDesc); } vector<string> EditorConfig::GetTypesThatCanBeAdded() const { auto const xpathResult = m_document.select_nodes("/mapsme/editor/types/type[not(@can_add='no' or @editable='no')]"); vector<string> result; for (auto const xNode : xpathResult) result.emplace_back(xNode.node().attribute("id").value()); return result; } void EditorConfig::SetConfig(pugi::xml_document const & doc) { m_document.reset(doc); } } // namespace editor <|endoftext|>
<commit_before>/* * drakeUtil.cpp * * Created on: Jun 19, 2013 * Author: russt */ #include "drakeUtil.h" #include <string.h> #include <string> #include <math.h> #include <limits> #include <Eigen/Dense> using namespace std; bool isa(const mxArray* mxa, const char* class_str) // mxIsClass seems to not be able to handle derived classes. so i'll implement what I need by calling back to matlab { mxArray* plhs; mxArray* prhs[2]; prhs[0] = const_cast<mxArray*>(mxa); prhs[1] = mxCreateString(class_str); mexCallMATLAB(1, &plhs, 2, prhs, "isa"); bool tf = *mxGetLogicals(plhs); mxDestroyArray(plhs); mxDestroyArray(prhs[1]); return tf; } bool mexCallMATLABsafe(int nlhs, mxArray* plhs[], int nrhs, mxArray* prhs[], const char* filename) { int i; mxArray* ex = mexCallMATLABWithTrap(nlhs, plhs, nrhs, prhs, filename); if (ex) { mexPrintf("DrakeSystem S-Function: error when calling ''%s'' with the following arguments:\n", filename); for (i = 0; i < nrhs; i++) mexCallMATLAB(0, NULL, 1, &prhs[i], "disp"); mxArray *report; mexCallMATLAB(1, &report, 1, &ex, "getReport"); char *errmsg = mxArrayToString(report); mexPrintf(errmsg); mxFree(errmsg); mxDestroyArray(report); mexErrMsgIdAndTxt("Drake:mexCallMATLABsafe:CallbackError", "Error in MATLAB callback.\nSee additional debugging information above"); mxDestroyArray(ex); return true; } for (i = 0; i < nlhs; i++) if (!plhs[i]) { mexPrintf("Drake mexCallMATLABsafe: error when calling ''%s'' with the following arguments:\n", filename); for (i = 0; i < nrhs; i++) mexCallMATLAB(0, NULL, 1, &prhs[i], "disp"); mexErrMsgIdAndTxt("Drake:mexCallMATLABsafe:NotEnoughOutputs", "Asked for %d outputs, but function only returned %d\n", nrhs, i); return true; } return false; } /* * @param subclass_name (optional) if you want to call a class that derives from * DrakeMexPointer (e.g. so that you can refer to it as something more specific in * your matlab code), then you can pass in the alternative name here. The constructor * for this class must take the same inputs as the DrakeMexPointer constructor. */ mxArray* createDrakeMexPointer(void* ptr, const char* name, int num_additional_inputs, mxArray* delete_fcn_additional_inputs[], const char* subclass_name) { mxClassID cid; if (sizeof(ptr) == 4) cid = mxUINT32_CLASS; else if (sizeof(ptr) == 8) cid = mxUINT64_CLASS; else mexErrMsgIdAndTxt("Drake:constructDrakeMexPointer:PointerSize", "Are you on a 32-bit machine or 64-bit machine??"); int nrhs = 3 + num_additional_inputs; mxArray *plhs[1]; mxArray **prhs; prhs = new mxArray*[nrhs]; prhs[0] = mxCreateNumericMatrix(1, 1, cid, mxREAL); memcpy(mxGetData(prhs[0]), &ptr, sizeof(ptr)); prhs[1] = mxCreateString(mexFunctionName()); prhs[2] = mxCreateString(name); for (int i = 0; i < num_additional_inputs; i++) prhs[3+i] = delete_fcn_additional_inputs[i]; // mexPrintf("deleteMethod = %s\n name =%s\n", deleteMethod,name); // call matlab to construct mex pointer object if (subclass_name) { mexCallMATLABsafe(1, plhs, nrhs, prhs, subclass_name); if (!isa(plhs[0], "DrakeMexPointer")) { mxDestroyArray(plhs[0]); mexErrMsgIdAndTxt("Drake:createDrakeMexPointer:InvalidSubclass", "subclass_name is not a valid subclass of DrakeMexPointer"); } } else mexCallMATLABsafe(1, plhs, nrhs, prhs, "DrakeMexPointer"); mexLock(); // mexPrintf("incrementing lock count\n"); delete[] prhs; return plhs[0]; } void* getDrakeMexPointer(const mxArray* mx) { void* ptr = NULL; // todo: optimize this by caching the pointer values, as described in // http://groups.csail.mit.edu/locomotion/bugs/show_bug.cgi?id=1590 mxArray* ptrArray = mxGetProperty(mx, 0, "ptr"); if (!ptrArray) mexErrMsgIdAndTxt("Drake:getDrakeMexPointer:BadInputs", "cannot retrieve 'ptr' field from this mxArray. are you sure it's a valid DrakeMexPointer object?"); switch (sizeof(void*)) { case 4: if (!mxIsUint32(ptrArray)) mexErrMsgIdAndTxt("Drake:getDrakeMexPointer:BadPointerSize", "DrakeMexPointer expected a 32-bit ptr field but got something else"); break; case 8: if (!mxIsUint64(ptrArray)) mexErrMsgIdAndTxt("Drake:getDrakeMexPointer:BadPointerSize", "DrakeMexPointer expected a 64-bit ptr field but got something else"); break; default: mexErrMsgIdAndTxt("Drake:getDrakeMexPointer:BadPointerSize", "DrakeMexPointer got a pointer that was neither 32-bit nor 64-bit."); } if (!mxIsNumeric(ptrArray) || mxGetNumberOfElements(ptrArray) != 1) mexErrMsgIdAndTxt("Drake:getDrakeMexPointer:BadInputs","the ptr property of this DrakeMexPointer does not appear to contain a valid pointer"); memcpy(&ptr, mxGetData(ptrArray), sizeof(ptr)); // note: could use a reinterpret_cast here instead return ptr; } double angleAverage(double theta1, double theta2) { // Computes the average between two angles by averaging points on the unit // circle and taking the arctan of the result. // see: http://en.wikipedia.org/wiki/Mean_of_circular_quantities // theta1 is a scalar or column vector of angles (rad) // theta2 is a scalar or column vector of angles (rad) double x_mean = 0.5 * (cos(theta1) + cos(theta2)); double y_mean = 0.5 * (sin(theta1) + sin(theta2)); double angle_mean = atan2(y_mean, x_mean); return angle_mean; } std::pair<Eigen::Vector3d, double> resolveCenterOfPressure(Eigen::Vector3d torque, Eigen::Vector3d force, Eigen::Vector3d normal, Eigen::Vector3d point_on_contact_plane) { // TODO: implement multi-column version using namespace Eigen; if (abs(normal.squaredNorm() - 1.0) > 1e-12) { mexErrMsgIdAndTxt("Drake:resolveCenterOfPressure:BadInputs", "normal should be a unit vector"); } Vector3d cop; double normal_torque_at_cop; double fz = normal.dot(force); bool cop_exists = abs(fz) > 1e-12; if (cop_exists) { auto torque_at_point_on_contact_plane = torque - point_on_contact_plane.cross(force); double normal_torque_at_point_on_contact_plane = normal.dot(torque_at_point_on_contact_plane); auto tangential_torque = torque_at_point_on_contact_plane - normal * normal_torque_at_point_on_contact_plane; cop = normal.cross(tangential_torque) / fz + point_on_contact_plane; auto torque_at_cop = torque - cop.cross(force); normal_torque_at_cop = normal.dot(torque_at_cop); } else { cop.setConstant(std::numeric_limits<double>::quiet_NaN()); normal_torque_at_cop = std::numeric_limits<double>::quiet_NaN(); } return std::pair<Vector3d, double>(cop, normal_torque_at_cop); } double * mxGetPrSafe(const mxArray *pobj) { if (!mxIsDouble(pobj)) mexErrMsgIdAndTxt("Drake:mxGetPrSafe:BadInputs", "mxGetPr can only be called on arguments which correspond to Matlab doubles"); return mxGetPr(pobj); } mxArray* mxGetFieldSafe(const mxArray* array, size_t index, std::string const& field_name) { mxArray* ret = mxGetField(array, index, field_name.c_str()); if (!ret) { mexErrMsgIdAndTxt("Drake::mxGetFieldSafe", ("Field not found: " + field_name).c_str()); } return ret; } void mxSetFieldSafe(mxArray* array, size_t index, std::string const & fieldname, mxArray* data) { int fieldnum; fieldnum = mxGetFieldNumber(array, fieldname.c_str()); if (fieldnum < 0) { fieldnum = mxAddField(array, fieldname.c_str()); } mxSetFieldByNumber(array, index, fieldnum, data); } const std::vector<double> matlabToStdVector(const mxArray* in) { // works for both row vectors and column vectors if (mxGetM(in) != 1 && mxGetN(in) != 1) throw runtime_error("Not a vector"); double* data = mxGetPrSafe(in); return std::vector<double>(data, data + mxGetNumberOfElements(in)); } int sub2ind(mwSize ndims, const mwSize* dims, const mwSize* sub) { int stride = 1; int ret = 0; for (int i = 0; i < ndims; i++) { ret += sub[i] * stride; stride *= dims[i]; } return ret; } void sizecheck(const mxArray* mat, int M, int N) { if (mxGetM(mat) != M) { mexErrMsgIdAndTxt("Drake:WrongSize", "wrong number of rows. Expected: %d but got: %d", M, mxGetM(mat)); } if (mxGetN(mat) != N) { mexErrMsgIdAndTxt("Drake:WrongSize", "wrong number of columns. Expected: %d but got: %d", N, mxGetN(mat)); } return; } <commit_msg>added missing include<commit_after>/* * drakeUtil.cpp * * Created on: Jun 19, 2013 * Author: russt */ #include "drakeUtil.h" #include <string.h> #include <string> #include <math.h> #include <limits> #include <Eigen/Dense> #include <stdexcept> using namespace std; bool isa(const mxArray* mxa, const char* class_str) // mxIsClass seems to not be able to handle derived classes. so i'll implement what I need by calling back to matlab { mxArray* plhs; mxArray* prhs[2]; prhs[0] = const_cast<mxArray*>(mxa); prhs[1] = mxCreateString(class_str); mexCallMATLAB(1, &plhs, 2, prhs, "isa"); bool tf = *mxGetLogicals(plhs); mxDestroyArray(plhs); mxDestroyArray(prhs[1]); return tf; } bool mexCallMATLABsafe(int nlhs, mxArray* plhs[], int nrhs, mxArray* prhs[], const char* filename) { int i; mxArray* ex = mexCallMATLABWithTrap(nlhs, plhs, nrhs, prhs, filename); if (ex) { mexPrintf("DrakeSystem S-Function: error when calling ''%s'' with the following arguments:\n", filename); for (i = 0; i < nrhs; i++) mexCallMATLAB(0, NULL, 1, &prhs[i], "disp"); mxArray *report; mexCallMATLAB(1, &report, 1, &ex, "getReport"); char *errmsg = mxArrayToString(report); mexPrintf(errmsg); mxFree(errmsg); mxDestroyArray(report); mexErrMsgIdAndTxt("Drake:mexCallMATLABsafe:CallbackError", "Error in MATLAB callback.\nSee additional debugging information above"); mxDestroyArray(ex); return true; } for (i = 0; i < nlhs; i++) if (!plhs[i]) { mexPrintf("Drake mexCallMATLABsafe: error when calling ''%s'' with the following arguments:\n", filename); for (i = 0; i < nrhs; i++) mexCallMATLAB(0, NULL, 1, &prhs[i], "disp"); mexErrMsgIdAndTxt("Drake:mexCallMATLABsafe:NotEnoughOutputs", "Asked for %d outputs, but function only returned %d\n", nrhs, i); return true; } return false; } /* * @param subclass_name (optional) if you want to call a class that derives from * DrakeMexPointer (e.g. so that you can refer to it as something more specific in * your matlab code), then you can pass in the alternative name here. The constructor * for this class must take the same inputs as the DrakeMexPointer constructor. */ mxArray* createDrakeMexPointer(void* ptr, const char* name, int num_additional_inputs, mxArray* delete_fcn_additional_inputs[], const char* subclass_name) { mxClassID cid; if (sizeof(ptr) == 4) cid = mxUINT32_CLASS; else if (sizeof(ptr) == 8) cid = mxUINT64_CLASS; else mexErrMsgIdAndTxt("Drake:constructDrakeMexPointer:PointerSize", "Are you on a 32-bit machine or 64-bit machine??"); int nrhs = 3 + num_additional_inputs; mxArray *plhs[1]; mxArray **prhs; prhs = new mxArray*[nrhs]; prhs[0] = mxCreateNumericMatrix(1, 1, cid, mxREAL); memcpy(mxGetData(prhs[0]), &ptr, sizeof(ptr)); prhs[1] = mxCreateString(mexFunctionName()); prhs[2] = mxCreateString(name); for (int i = 0; i < num_additional_inputs; i++) prhs[3+i] = delete_fcn_additional_inputs[i]; // mexPrintf("deleteMethod = %s\n name =%s\n", deleteMethod,name); // call matlab to construct mex pointer object if (subclass_name) { mexCallMATLABsafe(1, plhs, nrhs, prhs, subclass_name); if (!isa(plhs[0], "DrakeMexPointer")) { mxDestroyArray(plhs[0]); mexErrMsgIdAndTxt("Drake:createDrakeMexPointer:InvalidSubclass", "subclass_name is not a valid subclass of DrakeMexPointer"); } } else mexCallMATLABsafe(1, plhs, nrhs, prhs, "DrakeMexPointer"); mexLock(); // mexPrintf("incrementing lock count\n"); delete[] prhs; return plhs[0]; } void* getDrakeMexPointer(const mxArray* mx) { void* ptr = NULL; // todo: optimize this by caching the pointer values, as described in // http://groups.csail.mit.edu/locomotion/bugs/show_bug.cgi?id=1590 mxArray* ptrArray = mxGetProperty(mx, 0, "ptr"); if (!ptrArray) mexErrMsgIdAndTxt("Drake:getDrakeMexPointer:BadInputs", "cannot retrieve 'ptr' field from this mxArray. are you sure it's a valid DrakeMexPointer object?"); switch (sizeof(void*)) { case 4: if (!mxIsUint32(ptrArray)) mexErrMsgIdAndTxt("Drake:getDrakeMexPointer:BadPointerSize", "DrakeMexPointer expected a 32-bit ptr field but got something else"); break; case 8: if (!mxIsUint64(ptrArray)) mexErrMsgIdAndTxt("Drake:getDrakeMexPointer:BadPointerSize", "DrakeMexPointer expected a 64-bit ptr field but got something else"); break; default: mexErrMsgIdAndTxt("Drake:getDrakeMexPointer:BadPointerSize", "DrakeMexPointer got a pointer that was neither 32-bit nor 64-bit."); } if (!mxIsNumeric(ptrArray) || mxGetNumberOfElements(ptrArray) != 1) mexErrMsgIdAndTxt("Drake:getDrakeMexPointer:BadInputs","the ptr property of this DrakeMexPointer does not appear to contain a valid pointer"); memcpy(&ptr, mxGetData(ptrArray), sizeof(ptr)); // note: could use a reinterpret_cast here instead return ptr; } double angleAverage(double theta1, double theta2) { // Computes the average between two angles by averaging points on the unit // circle and taking the arctan of the result. // see: http://en.wikipedia.org/wiki/Mean_of_circular_quantities // theta1 is a scalar or column vector of angles (rad) // theta2 is a scalar or column vector of angles (rad) double x_mean = 0.5 * (cos(theta1) + cos(theta2)); double y_mean = 0.5 * (sin(theta1) + sin(theta2)); double angle_mean = atan2(y_mean, x_mean); return angle_mean; } std::pair<Eigen::Vector3d, double> resolveCenterOfPressure(Eigen::Vector3d torque, Eigen::Vector3d force, Eigen::Vector3d normal, Eigen::Vector3d point_on_contact_plane) { // TODO: implement multi-column version using namespace Eigen; if (abs(normal.squaredNorm() - 1.0) > 1e-12) { mexErrMsgIdAndTxt("Drake:resolveCenterOfPressure:BadInputs", "normal should be a unit vector"); } Vector3d cop; double normal_torque_at_cop; double fz = normal.dot(force); bool cop_exists = abs(fz) > 1e-12; if (cop_exists) { auto torque_at_point_on_contact_plane = torque - point_on_contact_plane.cross(force); double normal_torque_at_point_on_contact_plane = normal.dot(torque_at_point_on_contact_plane); auto tangential_torque = torque_at_point_on_contact_plane - normal * normal_torque_at_point_on_contact_plane; cop = normal.cross(tangential_torque) / fz + point_on_contact_plane; auto torque_at_cop = torque - cop.cross(force); normal_torque_at_cop = normal.dot(torque_at_cop); } else { cop.setConstant(std::numeric_limits<double>::quiet_NaN()); normal_torque_at_cop = std::numeric_limits<double>::quiet_NaN(); } return std::pair<Vector3d, double>(cop, normal_torque_at_cop); } double * mxGetPrSafe(const mxArray *pobj) { if (!mxIsDouble(pobj)) mexErrMsgIdAndTxt("Drake:mxGetPrSafe:BadInputs", "mxGetPr can only be called on arguments which correspond to Matlab doubles"); return mxGetPr(pobj); } mxArray* mxGetFieldSafe(const mxArray* array, size_t index, std::string const& field_name) { mxArray* ret = mxGetField(array, index, field_name.c_str()); if (!ret) { mexErrMsgIdAndTxt("Drake::mxGetFieldSafe", ("Field not found: " + field_name).c_str()); } return ret; } void mxSetFieldSafe(mxArray* array, size_t index, std::string const & fieldname, mxArray* data) { int fieldnum; fieldnum = mxGetFieldNumber(array, fieldname.c_str()); if (fieldnum < 0) { fieldnum = mxAddField(array, fieldname.c_str()); } mxSetFieldByNumber(array, index, fieldnum, data); } const std::vector<double> matlabToStdVector(const mxArray* in) { // works for both row vectors and column vectors if (mxGetM(in) != 1 && mxGetN(in) != 1) throw runtime_error("Not a vector"); double* data = mxGetPrSafe(in); return std::vector<double>(data, data + mxGetNumberOfElements(in)); } int sub2ind(mwSize ndims, const mwSize* dims, const mwSize* sub) { int stride = 1; int ret = 0; for (int i = 0; i < ndims; i++) { ret += sub[i] * stride; stride *= dims[i]; } return ret; } void sizecheck(const mxArray* mat, int M, int N) { if (mxGetM(mat) != M) { mexErrMsgIdAndTxt("Drake:WrongSize", "wrong number of rows. Expected: %d but got: %d", M, mxGetM(mat)); } if (mxGetN(mat) != N) { mexErrMsgIdAndTxt("Drake:WrongSize", "wrong number of columns. Expected: %d but got: %d", N, mxGetN(mat)); } return; } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: drdefuno.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: rt $ $Date: 2005-09-08 22:45:47 $ * * 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 * ************************************************************************/ #ifdef PCH #include "ui_pch.hxx" #endif #pragma hdrstop #include "drdefuno.hxx" #include "docsh.hxx" #include "drwlayer.hxx" using namespace ::com::sun::star; //------------------------------------------------------------------------ ScDrawDefaultsObj::ScDrawDefaultsObj(ScDocShell* pDocSh) : SvxUnoDrawPool( NULL ), pDocShell( pDocSh ) { // SvxUnoDrawPool is initialized without model, // draw layer is created on demand in getModelPool pDocShell->GetDocument()->AddUnoObject(*this); } ScDrawDefaultsObj::~ScDrawDefaultsObj() throw () { if (pDocShell) pDocShell->GetDocument()->RemoveUnoObject(*this); } void ScDrawDefaultsObj::Notify( SfxBroadcaster& rBC, const SfxHint& rHint ) { if ( rHint.ISA( SfxSimpleHint ) && ((const SfxSimpleHint&)rHint).GetId() == SFX_HINT_DYING ) { pDocShell = NULL; // document gone } } SfxItemPool* ScDrawDefaultsObj::getModelPool( sal_Bool bReadOnly ) throw() { SfxItemPool* pRet = NULL; if ( pDocShell ) { ScDrawLayer* pModel = bReadOnly ? pDocShell->GetDocument()->GetDrawLayer() : pDocShell->MakeDrawLayer(); if ( pModel ) pRet = &pModel->GetItemPool(); } if ( !pRet ) pRet = SvxUnoDrawPool::getModelPool( bReadOnly ); // uses default pool return pRet; } <commit_msg>INTEGRATION: CWS pchfix01 (1.3.214); FILE MERGED 2006/07/12 10:02:56 kaib 1.3.214.1: #i67080# Converted cxx files in sc, added initial project level pch and stripped old PCH definitions.<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: drdefuno.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: kz $ $Date: 2006-07-21 14:36:42 $ * * 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 * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sc.hxx" #include "drdefuno.hxx" #include "docsh.hxx" #include "drwlayer.hxx" using namespace ::com::sun::star; //------------------------------------------------------------------------ ScDrawDefaultsObj::ScDrawDefaultsObj(ScDocShell* pDocSh) : SvxUnoDrawPool( NULL ), pDocShell( pDocSh ) { // SvxUnoDrawPool is initialized without model, // draw layer is created on demand in getModelPool pDocShell->GetDocument()->AddUnoObject(*this); } ScDrawDefaultsObj::~ScDrawDefaultsObj() throw () { if (pDocShell) pDocShell->GetDocument()->RemoveUnoObject(*this); } void ScDrawDefaultsObj::Notify( SfxBroadcaster& rBC, const SfxHint& rHint ) { if ( rHint.ISA( SfxSimpleHint ) && ((const SfxSimpleHint&)rHint).GetId() == SFX_HINT_DYING ) { pDocShell = NULL; // document gone } } SfxItemPool* ScDrawDefaultsObj::getModelPool( sal_Bool bReadOnly ) throw() { SfxItemPool* pRet = NULL; if ( pDocShell ) { ScDrawLayer* pModel = bReadOnly ? pDocShell->GetDocument()->GetDrawLayer() : pDocShell->MakeDrawLayer(); if ( pModel ) pRet = &pModel->GetItemPool(); } if ( !pRet ) pRet = SvxUnoDrawPool::getModelPool( bReadOnly ); // uses default pool return pRet; } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: paratr.cxx,v $ * * $Revision: 1.5 $ * * last change: $Author: os $ $Date: 2002-07-04 14:46:09 $ * * 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): _______________________________________ * * ************************************************************************/ #ifdef PRECOMPILED #include "core_pch.hxx" #endif #pragma hdrstop #include "hintids.hxx" #include <swtypes.hxx> #include "unomid.h" #ifndef _COM_SUN_STAR_STYLE_LINESPACINGMODE_HPP_ #include <com/sun/star/style/LineSpacingMode.hpp> #endif #ifndef _COM_SUN_STAR_STYLE_PARAGRAPHADJUST_HPP_ #include <com/sun/star/style/ParagraphAdjust.hpp> #endif #ifndef _COM_SUN_STAR_STYLE_DROPCAPFORMAT_HPP_ #include <com/sun/star/style/DropCapFormat.hpp> #endif #ifndef _COM_SUN_STAR_STYLE_LINESPACING_HPP_ #include <com/sun/star/style/LineSpacing.hpp> #endif #ifndef _COM_SUN_STAR_TEXT_RELORIENTATION_HPP_ #include <com/sun/star/text/RelOrientation.hpp> #endif #ifndef _COM_SUN_STAR_TEXT_VERTORIENTATION_HPP_ #include <com/sun/star/text/VertOrientation.hpp> #endif #ifndef _COM_SUN_STAR_TEXT_HORIZONTALADJUST_HPP_ #include <com/sun/star/text/HorizontalAdjust.hpp> #endif #ifndef _COM_SUN_STAR_TEXT_DOCUMENTSTATISTIC_HPP_ #include <com/sun/star/text/DocumentStatistic.hpp> #endif #ifndef _COM_SUN_STAR_TEXT_HORIORIENTATION_HPP_ #include <com/sun/star/text/HoriOrientation.hpp> #endif #ifndef _COM_SUN_STAR_TEXT_HORIORIENTATIONFORMAT_HPP_ #include <com/sun/star/text/HoriOrientationFormat.hpp> #endif #ifndef _COM_SUN_STAR_TEXT_NOTEPRINTMODE_HPP_ #include <com/sun/star/text/NotePrintMode.hpp> #endif #ifndef _COM_SUN_STAR_TEXT_SIZETYPE_HPP_ #include <com/sun/star/text/SizeType.hpp> #endif #ifndef _COM_SUN_STAR_TEXT_VERTORIENTATIONFORMAT_HPP_ #include <com/sun/star/text/VertOrientationFormat.hpp> #endif #ifndef _COM_SUN_STAR_TEXT_WRAPTEXTMODE_HPP_ #include <com/sun/star/text/WrapTextMode.hpp> #endif #ifndef _UNOSTYLE_HXX #include <unostyle.hxx> #endif #ifndef _SWSTYLENAMEMAPPER_HXX #include <SwStyleNameMapper.hxx> #endif #include "errhdl.hxx" #include "paratr.hxx" #include "charfmt.hxx" #include "cmdid.h" using namespace ::com::sun::star; TYPEINIT2_AUTOFACTORY( SwFmtDrop, SfxPoolItem, SwClient); TYPEINIT1_AUTOFACTORY( SwRegisterItem, SfxBoolItem); TYPEINIT1_AUTOFACTORY( SwNumRuleItem, SfxStringItem); /************************************************************************* |* Beschreibung Methoden von SwFmtDrop |* Ersterstellung MS 19.02.91 |* Letzte Aenderung JP 08.08.94 *************************************************************************/ SwFmtDrop::SwFmtDrop() : SfxPoolItem( RES_PARATR_DROP ), SwClient( 0 ), nLines( 0 ), nChars( 0 ), nDistance( 0 ), pDefinedIn( 0 ), bWholeWord( sal_False ), nReadFmt( USHRT_MAX ) { } SwFmtDrop::SwFmtDrop( const SwFmtDrop &rCpy ) : SfxPoolItem( RES_PARATR_DROP ), SwClient( rCpy.pRegisteredIn ), nLines( rCpy.GetLines() ), nChars( rCpy.GetChars() ), nDistance( rCpy.GetDistance() ), bWholeWord( rCpy.GetWholeWord() ), pDefinedIn( 0 ), nReadFmt( rCpy.nReadFmt ) { } SwFmtDrop::~SwFmtDrop() { } void SwFmtDrop::SetCharFmt( SwCharFmt *pNew ) { //Ummelden if ( pRegisteredIn ) pRegisteredIn->Remove( this ); if(pNew) pNew->Add( this ); nReadFmt = USHRT_MAX; } void SwFmtDrop::Modify( SfxPoolItem *pA, SfxPoolItem *pB ) { if( pDefinedIn ) { if( !pDefinedIn->ISA( SwFmt )) pDefinedIn->Modify( this, this ); else if( pDefinedIn->GetDepends() && !pDefinedIn->IsModifyLocked() ) { // selbst den Abhaengigen vom Format bescheid sagen. Das // Format selbst wuerde es nicht weitergeben, weil es ueber // die Abpruefung nicht hinauskommt. SwClientIter aIter( *pDefinedIn ); SwClient * pLast = aIter.GoStart(); if( pLast ) // konnte zum Anfang gesprungen werden ?? do { pLast->Modify( this, this ); if( !pDefinedIn->GetDepends() ) // Baum schon Weg ?? break; } while( 0 != ( pLast = aIter++ )); } } } sal_Bool SwFmtDrop::GetInfo( SfxPoolItem& rInfo ) const { // fuers UNDO: pruefe ob das Attribut wirklich in diesem Format steht #ifdef USED_30 if( pDefinedIn ) { if( IS_TYPE( SwTxtNode, pDefinedIn ) && ((SwTxtNode*)pDefinedIn)->....... ) ; else if( IS_TYPE( SwTxtFmtColl, pDefinedIn ) && ((SwTxtFmtColl*)pDefinedIn)->....... ) ; // this == pFmt->GetAttr( RES_PARATR_DROP, sal_False )) // return pFmt->GetInfo( rInfo ); } #endif return sal_True; // weiter } int SwFmtDrop::operator==( const SfxPoolItem& rAttr ) const { ASSERT( SfxPoolItem::operator==( rAttr ), "keine gleichen Attribute" ); return ( nLines == ((SwFmtDrop&)rAttr).GetLines() && nChars == ((SwFmtDrop&)rAttr).GetChars() && nDistance == ((SwFmtDrop&)rAttr).GetDistance() && bWholeWord == ((SwFmtDrop&)rAttr).GetWholeWord() && GetCharFmt() == ((SwFmtDrop&)rAttr).GetCharFmt() && pDefinedIn == ((SwFmtDrop&)rAttr).pDefinedIn ); } SfxPoolItem* SwFmtDrop::Clone( SfxItemPool* ) const { return new SwFmtDrop( *this ); } sal_Bool SwFmtDrop::QueryValue( uno::Any& rVal, sal_uInt8 nMemberId ) const { switch(nMemberId&~CONVERT_TWIPS) { case MID_DROPCAP_LINES : rVal <<= (sal_Int16)nLines; break; case MID_DROPCAP_COUNT : rVal <<= (sal_Int16)nChars; break; case MID_DROPCAP_DISTANCE : rVal <<= (sal_Int16) TWIP_TO_MM100(nDistance); break; case MID_DROPCAP_FORMAT: { style::DropCapFormat aDrop; aDrop.Lines = nLines ; aDrop.Count = nChars ; aDrop.Distance = TWIP_TO_MM100(nDistance); rVal.setValue(&aDrop, ::getCppuType((const style::DropCapFormat*)0)); } break; case MID_DROPCAP_WHOLE_WORD: rVal.setValue(&bWholeWord, ::getBooleanCppuType()); break; case MID_DROPCAP_CHAR_STYLE_NAME : { rtl::OUString sName; if(GetCharFmt()) sName = SwStyleNameMapper::GetProgName( GetCharFmt()->GetName(), GET_POOLID_CHRFMT ); rVal <<= sName; } break; } return sal_True; } sal_Bool SwFmtDrop::PutValue( const uno::Any& rVal, sal_uInt8 nMemberId ) { switch(nMemberId&~CONVERT_TWIPS) { case MID_DROPCAP_LINES : { sal_Int8 nTemp; rVal >>= nTemp; if(nTemp >=1 && nTemp < 0x7f) nLines = (BYTE)nTemp; } break; case MID_DROPCAP_COUNT : { sal_Int16 nTemp; rVal >>= nTemp; if(nTemp >=1 && nTemp < 0x7f) nChars = (BYTE)nTemp; } break; case MID_DROPCAP_DISTANCE : { sal_Int16 nVal; if ( rVal >>= nVal ) nDistance = (sal_Int16) MM100_TO_TWIP((sal_Int32)nVal); else return sal_False; break; } case MID_DROPCAP_FORMAT: { if(rVal.getValueType() == ::getCppuType((const style::DropCapFormat*)0)) { const style::DropCapFormat* pDrop = (const style::DropCapFormat*)rVal.getValue(); nLines = pDrop->Lines; nChars = pDrop->Count; nDistance = MM100_TO_TWIP(pDrop->Distance); } else //exception( wrong_type) ; } break; case MID_DROPCAP_WHOLE_WORD: bWholeWord = *(sal_Bool*)rVal.getValue(); break; case MID_DROPCAP_CHAR_STYLE_NAME : DBG_ERROR("char format cannot be set in PutValue()!") break; } return sal_True; } // class SwRegisterItem ------------------------------------------------- SfxPoolItem* SwRegisterItem::Clone( SfxItemPool * ) const { return new SwRegisterItem( *this ); } // class SwNumRuleItem ------------------------------------------------- SfxPoolItem* SwNumRuleItem::Clone( SfxItemPool *pPool ) const { return new SwNumRuleItem( *this ); } int SwNumRuleItem::operator==( const SfxPoolItem& rAttr ) const { ASSERT( SfxPoolItem::operator==( rAttr ), "keine gleichen Attribute" ); return GetValue() == ((SwNumRuleItem&)rAttr).GetValue() && GetDefinedIn() == ((SwNumRuleItem&)rAttr).GetDefinedIn(); } /* -----------------------------27.06.00 11:05-------------------------------- ---------------------------------------------------------------------------*/ BOOL SwNumRuleItem::QueryValue( com::sun::star::uno::Any& rVal, BYTE nMemberId ) const { rtl::OUString sRet = SwStyleNameMapper::GetProgName(GetValue(), GET_POOLID_NUMRULE ); rVal <<= sRet; return TRUE; } /* -----------------------------27.06.00 11:05-------------------------------- ---------------------------------------------------------------------------*/ BOOL SwNumRuleItem::PutValue( const com::sun::star::uno::Any& rVal, BYTE nMemberId ) { rtl::OUString uName; rVal >>= uName; SetValue(SwStyleNameMapper::GetUIName(uName, GET_POOLID_NUMRULE)); return TRUE; } <commit_msg>INTEGRATION: CWS os8 (1.5.146); FILE MERGED 2003/04/03 07:11:12 os 1.5.146.1: #108583# precompiled headers removed<commit_after>/************************************************************************* * * $RCSfile: paratr.cxx,v $ * * $Revision: 1.6 $ * * last change: $Author: vg $ $Date: 2003-04-17 14:17:33 $ * * 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): _______________________________________ * * ************************************************************************/ #pragma hdrstop #include "hintids.hxx" #include <swtypes.hxx> #include "unomid.h" #ifndef _COM_SUN_STAR_STYLE_LINESPACINGMODE_HPP_ #include <com/sun/star/style/LineSpacingMode.hpp> #endif #ifndef _COM_SUN_STAR_STYLE_PARAGRAPHADJUST_HPP_ #include <com/sun/star/style/ParagraphAdjust.hpp> #endif #ifndef _COM_SUN_STAR_STYLE_DROPCAPFORMAT_HPP_ #include <com/sun/star/style/DropCapFormat.hpp> #endif #ifndef _COM_SUN_STAR_STYLE_LINESPACING_HPP_ #include <com/sun/star/style/LineSpacing.hpp> #endif #ifndef _COM_SUN_STAR_TEXT_RELORIENTATION_HPP_ #include <com/sun/star/text/RelOrientation.hpp> #endif #ifndef _COM_SUN_STAR_TEXT_VERTORIENTATION_HPP_ #include <com/sun/star/text/VertOrientation.hpp> #endif #ifndef _COM_SUN_STAR_TEXT_HORIZONTALADJUST_HPP_ #include <com/sun/star/text/HorizontalAdjust.hpp> #endif #ifndef _COM_SUN_STAR_TEXT_DOCUMENTSTATISTIC_HPP_ #include <com/sun/star/text/DocumentStatistic.hpp> #endif #ifndef _COM_SUN_STAR_TEXT_HORIORIENTATION_HPP_ #include <com/sun/star/text/HoriOrientation.hpp> #endif #ifndef _COM_SUN_STAR_TEXT_HORIORIENTATIONFORMAT_HPP_ #include <com/sun/star/text/HoriOrientationFormat.hpp> #endif #ifndef _COM_SUN_STAR_TEXT_NOTEPRINTMODE_HPP_ #include <com/sun/star/text/NotePrintMode.hpp> #endif #ifndef _COM_SUN_STAR_TEXT_SIZETYPE_HPP_ #include <com/sun/star/text/SizeType.hpp> #endif #ifndef _COM_SUN_STAR_TEXT_VERTORIENTATIONFORMAT_HPP_ #include <com/sun/star/text/VertOrientationFormat.hpp> #endif #ifndef _COM_SUN_STAR_TEXT_WRAPTEXTMODE_HPP_ #include <com/sun/star/text/WrapTextMode.hpp> #endif #ifndef _UNOSTYLE_HXX #include <unostyle.hxx> #endif #ifndef _SWSTYLENAMEMAPPER_HXX #include <SwStyleNameMapper.hxx> #endif #include "errhdl.hxx" #include "paratr.hxx" #include "charfmt.hxx" #include "cmdid.h" using namespace ::com::sun::star; TYPEINIT2_AUTOFACTORY( SwFmtDrop, SfxPoolItem, SwClient); TYPEINIT1_AUTOFACTORY( SwRegisterItem, SfxBoolItem); TYPEINIT1_AUTOFACTORY( SwNumRuleItem, SfxStringItem); /************************************************************************* |* Beschreibung Methoden von SwFmtDrop |* Ersterstellung MS 19.02.91 |* Letzte Aenderung JP 08.08.94 *************************************************************************/ SwFmtDrop::SwFmtDrop() : SfxPoolItem( RES_PARATR_DROP ), SwClient( 0 ), nLines( 0 ), nChars( 0 ), nDistance( 0 ), pDefinedIn( 0 ), bWholeWord( sal_False ), nReadFmt( USHRT_MAX ) { } SwFmtDrop::SwFmtDrop( const SwFmtDrop &rCpy ) : SfxPoolItem( RES_PARATR_DROP ), SwClient( rCpy.pRegisteredIn ), nLines( rCpy.GetLines() ), nChars( rCpy.GetChars() ), nDistance( rCpy.GetDistance() ), bWholeWord( rCpy.GetWholeWord() ), pDefinedIn( 0 ), nReadFmt( rCpy.nReadFmt ) { } SwFmtDrop::~SwFmtDrop() { } void SwFmtDrop::SetCharFmt( SwCharFmt *pNew ) { //Ummelden if ( pRegisteredIn ) pRegisteredIn->Remove( this ); if(pNew) pNew->Add( this ); nReadFmt = USHRT_MAX; } void SwFmtDrop::Modify( SfxPoolItem *pA, SfxPoolItem *pB ) { if( pDefinedIn ) { if( !pDefinedIn->ISA( SwFmt )) pDefinedIn->Modify( this, this ); else if( pDefinedIn->GetDepends() && !pDefinedIn->IsModifyLocked() ) { // selbst den Abhaengigen vom Format bescheid sagen. Das // Format selbst wuerde es nicht weitergeben, weil es ueber // die Abpruefung nicht hinauskommt. SwClientIter aIter( *pDefinedIn ); SwClient * pLast = aIter.GoStart(); if( pLast ) // konnte zum Anfang gesprungen werden ?? do { pLast->Modify( this, this ); if( !pDefinedIn->GetDepends() ) // Baum schon Weg ?? break; } while( 0 != ( pLast = aIter++ )); } } } sal_Bool SwFmtDrop::GetInfo( SfxPoolItem& rInfo ) const { // fuers UNDO: pruefe ob das Attribut wirklich in diesem Format steht #ifdef USED_30 if( pDefinedIn ) { if( IS_TYPE( SwTxtNode, pDefinedIn ) && ((SwTxtNode*)pDefinedIn)->....... ) ; else if( IS_TYPE( SwTxtFmtColl, pDefinedIn ) && ((SwTxtFmtColl*)pDefinedIn)->....... ) ; // this == pFmt->GetAttr( RES_PARATR_DROP, sal_False )) // return pFmt->GetInfo( rInfo ); } #endif return sal_True; // weiter } int SwFmtDrop::operator==( const SfxPoolItem& rAttr ) const { ASSERT( SfxPoolItem::operator==( rAttr ), "keine gleichen Attribute" ); return ( nLines == ((SwFmtDrop&)rAttr).GetLines() && nChars == ((SwFmtDrop&)rAttr).GetChars() && nDistance == ((SwFmtDrop&)rAttr).GetDistance() && bWholeWord == ((SwFmtDrop&)rAttr).GetWholeWord() && GetCharFmt() == ((SwFmtDrop&)rAttr).GetCharFmt() && pDefinedIn == ((SwFmtDrop&)rAttr).pDefinedIn ); } SfxPoolItem* SwFmtDrop::Clone( SfxItemPool* ) const { return new SwFmtDrop( *this ); } sal_Bool SwFmtDrop::QueryValue( uno::Any& rVal, sal_uInt8 nMemberId ) const { switch(nMemberId&~CONVERT_TWIPS) { case MID_DROPCAP_LINES : rVal <<= (sal_Int16)nLines; break; case MID_DROPCAP_COUNT : rVal <<= (sal_Int16)nChars; break; case MID_DROPCAP_DISTANCE : rVal <<= (sal_Int16) TWIP_TO_MM100(nDistance); break; case MID_DROPCAP_FORMAT: { style::DropCapFormat aDrop; aDrop.Lines = nLines ; aDrop.Count = nChars ; aDrop.Distance = TWIP_TO_MM100(nDistance); rVal.setValue(&aDrop, ::getCppuType((const style::DropCapFormat*)0)); } break; case MID_DROPCAP_WHOLE_WORD: rVal.setValue(&bWholeWord, ::getBooleanCppuType()); break; case MID_DROPCAP_CHAR_STYLE_NAME : { rtl::OUString sName; if(GetCharFmt()) sName = SwStyleNameMapper::GetProgName( GetCharFmt()->GetName(), GET_POOLID_CHRFMT ); rVal <<= sName; } break; } return sal_True; } sal_Bool SwFmtDrop::PutValue( const uno::Any& rVal, sal_uInt8 nMemberId ) { switch(nMemberId&~CONVERT_TWIPS) { case MID_DROPCAP_LINES : { sal_Int8 nTemp; rVal >>= nTemp; if(nTemp >=1 && nTemp < 0x7f) nLines = (BYTE)nTemp; } break; case MID_DROPCAP_COUNT : { sal_Int16 nTemp; rVal >>= nTemp; if(nTemp >=1 && nTemp < 0x7f) nChars = (BYTE)nTemp; } break; case MID_DROPCAP_DISTANCE : { sal_Int16 nVal; if ( rVal >>= nVal ) nDistance = (sal_Int16) MM100_TO_TWIP((sal_Int32)nVal); else return sal_False; break; } case MID_DROPCAP_FORMAT: { if(rVal.getValueType() == ::getCppuType((const style::DropCapFormat*)0)) { const style::DropCapFormat* pDrop = (const style::DropCapFormat*)rVal.getValue(); nLines = pDrop->Lines; nChars = pDrop->Count; nDistance = MM100_TO_TWIP(pDrop->Distance); } else //exception( wrong_type) ; } break; case MID_DROPCAP_WHOLE_WORD: bWholeWord = *(sal_Bool*)rVal.getValue(); break; case MID_DROPCAP_CHAR_STYLE_NAME : DBG_ERROR("char format cannot be set in PutValue()!") break; } return sal_True; } // class SwRegisterItem ------------------------------------------------- SfxPoolItem* SwRegisterItem::Clone( SfxItemPool * ) const { return new SwRegisterItem( *this ); } // class SwNumRuleItem ------------------------------------------------- SfxPoolItem* SwNumRuleItem::Clone( SfxItemPool *pPool ) const { return new SwNumRuleItem( *this ); } int SwNumRuleItem::operator==( const SfxPoolItem& rAttr ) const { ASSERT( SfxPoolItem::operator==( rAttr ), "keine gleichen Attribute" ); return GetValue() == ((SwNumRuleItem&)rAttr).GetValue() && GetDefinedIn() == ((SwNumRuleItem&)rAttr).GetDefinedIn(); } /* -----------------------------27.06.00 11:05-------------------------------- ---------------------------------------------------------------------------*/ BOOL SwNumRuleItem::QueryValue( com::sun::star::uno::Any& rVal, BYTE nMemberId ) const { rtl::OUString sRet = SwStyleNameMapper::GetProgName(GetValue(), GET_POOLID_NUMRULE ); rVal <<= sRet; return TRUE; } /* -----------------------------27.06.00 11:05-------------------------------- ---------------------------------------------------------------------------*/ BOOL SwNumRuleItem::PutValue( const com::sun::star::uno::Any& rVal, BYTE nMemberId ) { rtl::OUString uName; rVal >>= uName; SetValue(SwStyleNameMapper::GetUIName(uName, GET_POOLID_NUMRULE)); return TRUE; } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: frminf.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: rt $ $Date: 2003-12-01 17:21:56 $ * * 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): _______________________________________ * * ************************************************************************/ #pragma hdrstop #ifndef _PAM_HXX #include <pam.hxx> // GetSpaces #endif #ifndef _TXTCFG_HXX #include <txtcfg.hxx> #endif #ifndef _FRMINF_HXX #include <frminf.hxx> // SwTxtFrminfo #endif #ifndef _ITRTXT_HXX #include <itrtxt.hxx> // SwTxtMargin #endif #ifndef _SWFONT_HXX #include <swfont.hxx> // IsBullet() #endif /************************************************************************* * SwTxtMargin::GetTxtStart() *************************************************************************/ xub_StrLen SwTxtMargin::GetTxtStart() const { const XubString &rTxt = GetInfo().GetTxt(); const xub_StrLen nPos = nStart; const xub_StrLen nEnd = nPos + pCurr->GetLen(); xub_StrLen i; for( i = nPos; i < nEnd; ++i ) { const xub_Unicode aChar = rTxt.GetChar( i ); if( CH_TAB != aChar && ' ' != aChar ) return i; } return i; } /************************************************************************* * SwTxtMargin::GetTxtEnd() *************************************************************************/ xub_StrLen SwTxtMargin::GetTxtEnd() const { const XubString &rTxt = GetInfo().GetTxt(); const xub_StrLen nPos = nStart; const xub_StrLen nEnd = nPos + pCurr->GetLen(); long i; for( i = nEnd - 1; i >= nPos; --i ) { xub_Unicode aChar = rTxt.GetChar( i ); if( CH_TAB != aChar && CH_BREAK != aChar && ' ' != aChar ) return i + 1; } return i + 1; } /************************************************************************* * SwTxtFrmInfo::IsOneLine() *************************************************************************/ // Passt der Absatz in eine Zeile? sal_Bool SwTxtFrmInfo::IsOneLine() const { const SwLineLayout *pLay = pFrm->GetPara(); if( !pLay ) return sal_False; else { // 6575: bei Follows natuerlich sal_False if( pFrm->GetFollow() ) return sal_False; pLay = pLay->GetNext(); while( pLay ) { if( pLay->GetLen() ) return sal_False; pLay = pLay->GetNext(); } return sal_True; } } /************************************************************************* * SwTxtFrmInfo::IsFilled() *************************************************************************/ // Ist die Zeile zu X% gefuellt? sal_Bool SwTxtFrmInfo::IsFilled( const sal_uInt8 nPercent ) const { const SwLineLayout *pLay = pFrm->GetPara(); if( !pLay ) return sal_False; else { long nWidth = pFrm->Prt().Width(); nWidth *= nPercent; nWidth /= 100; return KSHORT(nWidth) <= pLay->Width(); } } /************************************************************************* * SwTxtFrmInfo::GetLineStart() *************************************************************************/ // Wo beginnt der Text (ohne whitespaces)? ( Dokument global ) SwTwips SwTxtFrmInfo::GetLineStart( const SwTxtCursor &rLine ) const { SwTwips nTxtStart = rLine.GetTxtStart(); SwTwips nStart; if( rLine.GetStart() == nTxtStart ) nStart = rLine.GetLineStart(); else { SwRect aRect; if( ((SwTxtCursor&)rLine).GetCharRect( &aRect, nTxtStart ) ) nStart = aRect.Left(); else nStart = rLine.GetLineStart(); } return nStart; } /************************************************************************* * SwTxtFrmInfo::GetLineStart() *************************************************************************/ // Wo beginnt der Text (ohne whitespaces)? (rel. im Frame) SwTwips SwTxtFrmInfo::GetLineStart() const { SwTxtSizeInfo aInf( (SwTxtFrm*)pFrm ); SwTxtCursor aLine( (SwTxtFrm*)pFrm, &aInf ); return GetLineStart( aLine ) - pFrm->Frm().Left() - pFrm->Prt().Left(); } // errechne die Position des Zeichens und gebe die Mittelposition zurueck SwTwips SwTxtFrmInfo::GetCharPos( xub_StrLen nChar, sal_Bool bCenter ) const { SWRECTFN( pFrm ) SwFrmSwapper aSwapper( pFrm, sal_True ); SwTxtSizeInfo aInf( (SwTxtFrm*)pFrm ); SwTxtCursor aLine( (SwTxtFrm*)pFrm, &aInf ); SwTwips nStt, nNext; SwRect aRect; if( ((SwTxtCursor&)aLine).GetCharRect( &aRect, nChar ) ) { if ( bVert ) pFrm->SwitchHorizontalToVertical( aRect ); nStt = (aRect.*fnRect->fnGetLeft)(); } else nStt = aLine.GetLineStart(); if( !bCenter ) return nStt - (pFrm->Frm().*fnRect->fnGetLeft)(); if( ((SwTxtCursor&)aLine).GetCharRect( &aRect, nChar+1 ) ) { if ( bVert ) pFrm->SwitchHorizontalToVertical( aRect ); nNext = (aRect.*fnRect->fnGetLeft)(); } else nNext = aLine.GetLineStart(); return (( nNext + nStt ) / 2 ) - (pFrm->Frm().*fnRect->fnGetLeft)(); } /************************************************************************* * SwTxtFrmInfo::GetSpaces() *************************************************************************/ SwPaM *AddPam( SwPaM *pPam, const SwTxtFrm* pTxtFrm, const xub_StrLen nPos, const xub_StrLen nLen ) { if( nLen ) { // Es koennte auch der erste sein. if( pPam->HasMark() ) { // liegt die neue Position genau hinter der aktuellen, dann // erweiter den Pam einfach if( nPos == pPam->GetPoint()->nContent.GetIndex() ) { pPam->GetPoint()->nContent += nLen; return pPam; } pPam = new SwPaM( *pPam ); } SwIndex &rContent = pPam->GetPoint()->nContent; rContent.Assign( (SwTxtNode*)pTxtFrm->GetTxtNode(), nPos ); pPam->SetMark(); rContent += nLen; } return pPam; } // Sammelt die whitespaces am Zeilenbeginn und -ende im Pam void SwTxtFrmInfo::GetSpaces( SwPaM &rPam, sal_Bool bWithLineBreak ) const { SwTxtSizeInfo aInf( (SwTxtFrm*)pFrm ); SwTxtMargin aLine( (SwTxtFrm*)pFrm, &aInf ); SwPaM *pPam = &rPam; sal_Bool bFirstLine = sal_True; do { if( aLine.GetCurr()->GetLen() ) { xub_StrLen nPos = aLine.GetTxtStart(); // Bug 49649: von der ersten Line die Blanks/Tabs NICHT // mit selektieren if( !bFirstLine && nPos > aLine.GetStart() ) pPam = AddPam( pPam, pFrm, aLine.GetStart(), nPos - aLine.GetStart() ); // Bug 49649: von der letzten Line die Blanks/Tabs NICHT // mit selektieren if( aLine.GetNext() ) { nPos = aLine.GetTxtEnd(); if( nPos < aLine.GetEnd() ) { MSHORT nOff = !bWithLineBreak && CH_BREAK == aLine.GetInfo().GetChar( aLine.GetEnd() - 1 ) ? 1 : 0; pPam = AddPam( pPam, pFrm, nPos, aLine.GetEnd() - nPos - nOff ); } } } bFirstLine = sal_False; } while( aLine.Next() ); } /************************************************************************* * SwTxtFrmInfo::IsBullet() *************************************************************************/ // Ist an der Textposition ein Bullet/Symbol etc? // Fonts: CharSet, SYMBOL und DONTKNOW sal_Bool SwTxtFrmInfo::IsBullet( xub_StrLen nTxtStart ) const { SwTxtSizeInfo aInf( (SwTxtFrm*)pFrm ); SwTxtMargin aLine( (SwTxtFrm*)pFrm, &aInf ); aInf.SetIdx( nTxtStart ); return aLine.IsSymbol( nTxtStart ); } /************************************************************************* * SwTxtFrmInfo::GetFirstIndent() *************************************************************************/ // Ermittelt Erstzeileneinzug // Voraussetzung fuer pos. oder neg. EZE ist, dass alle // Zeilen ausser der ersten Zeile den selben linken Rand haben. // Wir wollen nicht so knauserig sein und arbeiten mit einer Toleranz // von TOLERANCE Twips. #define TOLERANCE 20 SwTwips SwTxtFrmInfo::GetFirstIndent() const { SwTxtSizeInfo aInf( (SwTxtFrm*)pFrm ); SwTxtCursor aLine( (SwTxtFrm*)pFrm, &aInf ); const SwTwips nFirst = GetLineStart( aLine ); if( !aLine.Next() ) return 0; SwTwips nLeft = GetLineStart( aLine ); while( aLine.Next() ) { if( aLine.GetCurr()->GetLen() ) { const SwTwips nCurrLeft = GetLineStart( aLine ); if( nLeft + TOLERANCE < nCurrLeft || nLeft - TOLERANCE > nCurrLeft ) return 0; } } // Vorerst wird nur +1, -1 und 0 returnt. if( nLeft == nFirst ) return 0; else if( nLeft > nFirst ) return -1; else return +1; } /************************************************************************* * SwTxtFrmInfo::GetBigIndent() *************************************************************************/ KSHORT SwTxtFrmInfo::GetBigIndent( xub_StrLen& rFndPos, const SwTxtFrm *pNextFrm ) const { SwTxtSizeInfo aInf( (SwTxtFrm*)pFrm ); SwTxtCursor aLine( (SwTxtFrm*)pFrm, &aInf ); SwTwips nNextIndent = 0; if( pNextFrm ) { // ich bin einzeilig SwTxtSizeInfo aNxtInf( (SwTxtFrm*)pNextFrm ); SwTxtCursor aNxtLine( (SwTxtFrm*)pNextFrm, &aNxtInf ); nNextIndent = GetLineStart( aNxtLine ); } else { // ich bin mehrzeilig if( aLine.Next() ) { nNextIndent = GetLineStart( aLine ); aLine.Prev(); } } if( nNextIndent <= GetLineStart( aLine ) ) return 0; const Point aPoint( nNextIndent, aLine.Y() ); rFndPos = aLine.GetCrsrOfst( 0, aPoint, sal_False ); if( 1 >= rFndPos ) return 0; // steht vor einem "nicht Space" const XubString& rTxt = aInf.GetTxt(); xub_Unicode aChar = rTxt.GetChar( rFndPos ); if( CH_TAB == aChar || CH_BREAK == aChar || ' ' == aChar || (( CH_TXTATR_BREAKWORD == aChar || CH_TXTATR_INWORD == aChar ) && aInf.HasHint( rFndPos ) ) ) return 0; // und hinter einem "Space" aChar = rTxt.GetChar( rFndPos - 1 ); if( CH_TAB != aChar && CH_BREAK != aChar && ( ( CH_TXTATR_BREAKWORD != aChar && CH_TXTATR_INWORD != aChar ) || !aInf.HasHint( rFndPos - 1 ) ) && // mehr als 2 Blanks !! ( ' ' != aChar || ' ' != rTxt.GetChar( rFndPos - 2 ) ) ) return 0; SwRect aRect; return aLine.GetCharRect( &aRect, rFndPos ) ? KSHORT( aRect.Left() - pFrm->Frm().Left() - pFrm->Prt().Left()) : 0; } <commit_msg>INTEGRATION: CWS thaiblocksatz (1.4.682); FILE MERGED 2005/04/06 06:30:25 fme 1.4.682.1: #i41860# Thai justified alignment needs some more precision to prevent rounding errors<commit_after>/************************************************************************* * * $RCSfile: frminf.cxx,v $ * * $Revision: 1.5 $ * * last change: $Author: obo $ $Date: 2005-04-18 14:34:23 $ * * 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): _______________________________________ * * ************************************************************************/ #pragma hdrstop #ifndef _PAM_HXX #include <pam.hxx> // GetSpaces #endif #ifndef _TXTCFG_HXX #include <txtcfg.hxx> #endif #ifndef _FRMINF_HXX #include <frminf.hxx> // SwTxtFrminfo #endif #ifndef _ITRTXT_HXX #include <itrtxt.hxx> // SwTxtMargin #endif #ifndef _SWFONT_HXX #include <swfont.hxx> // IsBullet() #endif /************************************************************************* * SwTxtMargin::GetTxtStart() *************************************************************************/ xub_StrLen SwTxtMargin::GetTxtStart() const { const XubString &rTxt = GetInfo().GetTxt(); const xub_StrLen nPos = nStart; const xub_StrLen nEnd = nPos + pCurr->GetLen(); xub_StrLen i; for( i = nPos; i < nEnd; ++i ) { const xub_Unicode aChar = rTxt.GetChar( i ); if( CH_TAB != aChar && ' ' != aChar ) return i; } return i; } /************************************************************************* * SwTxtMargin::GetTxtEnd() *************************************************************************/ xub_StrLen SwTxtMargin::GetTxtEnd() const { const XubString &rTxt = GetInfo().GetTxt(); const xub_StrLen nPos = nStart; const xub_StrLen nEnd = nPos + pCurr->GetLen(); long i; for( i = nEnd - 1; i >= nPos; --i ) { xub_Unicode aChar = rTxt.GetChar( static_cast<xub_StrLen>(i) ); if( CH_TAB != aChar && CH_BREAK != aChar && ' ' != aChar ) return static_cast<xub_StrLen>(i + 1); } return static_cast<xub_StrLen>(i + 1); } /************************************************************************* * SwTxtFrmInfo::IsOneLine() *************************************************************************/ // Passt der Absatz in eine Zeile? sal_Bool SwTxtFrmInfo::IsOneLine() const { const SwLineLayout *pLay = pFrm->GetPara(); if( !pLay ) return sal_False; else { // 6575: bei Follows natuerlich sal_False if( pFrm->GetFollow() ) return sal_False; pLay = pLay->GetNext(); while( pLay ) { if( pLay->GetLen() ) return sal_False; pLay = pLay->GetNext(); } return sal_True; } } /************************************************************************* * SwTxtFrmInfo::IsFilled() *************************************************************************/ // Ist die Zeile zu X% gefuellt? sal_Bool SwTxtFrmInfo::IsFilled( const sal_uInt8 nPercent ) const { const SwLineLayout *pLay = pFrm->GetPara(); if( !pLay ) return sal_False; else { long nWidth = pFrm->Prt().Width(); nWidth *= nPercent; nWidth /= 100; return KSHORT(nWidth) <= pLay->Width(); } } /************************************************************************* * SwTxtFrmInfo::GetLineStart() *************************************************************************/ // Wo beginnt der Text (ohne whitespaces)? ( Dokument global ) SwTwips SwTxtFrmInfo::GetLineStart( const SwTxtCursor &rLine ) const { xub_StrLen nTxtStart = rLine.GetTxtStart(); SwTwips nStart; if( rLine.GetStart() == nTxtStart ) nStart = rLine.GetLineStart(); else { SwRect aRect; if( ((SwTxtCursor&)rLine).GetCharRect( &aRect, nTxtStart ) ) nStart = aRect.Left(); else nStart = rLine.GetLineStart(); } return nStart; } /************************************************************************* * SwTxtFrmInfo::GetLineStart() *************************************************************************/ // Wo beginnt der Text (ohne whitespaces)? (rel. im Frame) SwTwips SwTxtFrmInfo::GetLineStart() const { SwTxtSizeInfo aInf( (SwTxtFrm*)pFrm ); SwTxtCursor aLine( (SwTxtFrm*)pFrm, &aInf ); return GetLineStart( aLine ) - pFrm->Frm().Left() - pFrm->Prt().Left(); } // errechne die Position des Zeichens und gebe die Mittelposition zurueck SwTwips SwTxtFrmInfo::GetCharPos( xub_StrLen nChar, sal_Bool bCenter ) const { SWRECTFN( pFrm ) SwFrmSwapper aSwapper( pFrm, sal_True ); SwTxtSizeInfo aInf( (SwTxtFrm*)pFrm ); SwTxtCursor aLine( (SwTxtFrm*)pFrm, &aInf ); SwTwips nStt, nNext; SwRect aRect; if( ((SwTxtCursor&)aLine).GetCharRect( &aRect, nChar ) ) { if ( bVert ) pFrm->SwitchHorizontalToVertical( aRect ); nStt = (aRect.*fnRect->fnGetLeft)(); } else nStt = aLine.GetLineStart(); if( !bCenter ) return nStt - (pFrm->Frm().*fnRect->fnGetLeft)(); if( ((SwTxtCursor&)aLine).GetCharRect( &aRect, nChar+1 ) ) { if ( bVert ) pFrm->SwitchHorizontalToVertical( aRect ); nNext = (aRect.*fnRect->fnGetLeft)(); } else nNext = aLine.GetLineStart(); return (( nNext + nStt ) / 2 ) - (pFrm->Frm().*fnRect->fnGetLeft)(); } /************************************************************************* * SwTxtFrmInfo::GetSpaces() *************************************************************************/ SwPaM *AddPam( SwPaM *pPam, const SwTxtFrm* pTxtFrm, const xub_StrLen nPos, const xub_StrLen nLen ) { if( nLen ) { // Es koennte auch der erste sein. if( pPam->HasMark() ) { // liegt die neue Position genau hinter der aktuellen, dann // erweiter den Pam einfach if( nPos == pPam->GetPoint()->nContent.GetIndex() ) { pPam->GetPoint()->nContent += nLen; return pPam; } pPam = new SwPaM( *pPam ); } SwIndex &rContent = pPam->GetPoint()->nContent; rContent.Assign( (SwTxtNode*)pTxtFrm->GetTxtNode(), nPos ); pPam->SetMark(); rContent += nLen; } return pPam; } // Sammelt die whitespaces am Zeilenbeginn und -ende im Pam void SwTxtFrmInfo::GetSpaces( SwPaM &rPam, sal_Bool bWithLineBreak ) const { SwTxtSizeInfo aInf( (SwTxtFrm*)pFrm ); SwTxtMargin aLine( (SwTxtFrm*)pFrm, &aInf ); SwPaM *pPam = &rPam; sal_Bool bFirstLine = sal_True; do { if( aLine.GetCurr()->GetLen() ) { xub_StrLen nPos = aLine.GetTxtStart(); // Bug 49649: von der ersten Line die Blanks/Tabs NICHT // mit selektieren if( !bFirstLine && nPos > aLine.GetStart() ) pPam = AddPam( pPam, pFrm, aLine.GetStart(), nPos - aLine.GetStart() ); // Bug 49649: von der letzten Line die Blanks/Tabs NICHT // mit selektieren if( aLine.GetNext() ) { nPos = aLine.GetTxtEnd(); if( nPos < aLine.GetEnd() ) { MSHORT nOff = !bWithLineBreak && CH_BREAK == aLine.GetInfo().GetChar( aLine.GetEnd() - 1 ) ? 1 : 0; pPam = AddPam( pPam, pFrm, nPos, aLine.GetEnd() - nPos - nOff ); } } } bFirstLine = sal_False; } while( aLine.Next() ); } /************************************************************************* * SwTxtFrmInfo::IsBullet() *************************************************************************/ // Ist an der Textposition ein Bullet/Symbol etc? // Fonts: CharSet, SYMBOL und DONTKNOW sal_Bool SwTxtFrmInfo::IsBullet( xub_StrLen nTxtStart ) const { SwTxtSizeInfo aInf( (SwTxtFrm*)pFrm ); SwTxtMargin aLine( (SwTxtFrm*)pFrm, &aInf ); aInf.SetIdx( nTxtStart ); return aLine.IsSymbol( nTxtStart ); } /************************************************************************* * SwTxtFrmInfo::GetFirstIndent() *************************************************************************/ // Ermittelt Erstzeileneinzug // Voraussetzung fuer pos. oder neg. EZE ist, dass alle // Zeilen ausser der ersten Zeile den selben linken Rand haben. // Wir wollen nicht so knauserig sein und arbeiten mit einer Toleranz // von TOLERANCE Twips. #define TOLERANCE 20 SwTwips SwTxtFrmInfo::GetFirstIndent() const { SwTxtSizeInfo aInf( (SwTxtFrm*)pFrm ); SwTxtCursor aLine( (SwTxtFrm*)pFrm, &aInf ); const SwTwips nFirst = GetLineStart( aLine ); if( !aLine.Next() ) return 0; SwTwips nLeft = GetLineStart( aLine ); while( aLine.Next() ) { if( aLine.GetCurr()->GetLen() ) { const SwTwips nCurrLeft = GetLineStart( aLine ); if( nLeft + TOLERANCE < nCurrLeft || nLeft - TOLERANCE > nCurrLeft ) return 0; } } // Vorerst wird nur +1, -1 und 0 returnt. if( nLeft == nFirst ) return 0; else if( nLeft > nFirst ) return -1; else return +1; } /************************************************************************* * SwTxtFrmInfo::GetBigIndent() *************************************************************************/ KSHORT SwTxtFrmInfo::GetBigIndent( xub_StrLen& rFndPos, const SwTxtFrm *pNextFrm ) const { SwTxtSizeInfo aInf( (SwTxtFrm*)pFrm ); SwTxtCursor aLine( (SwTxtFrm*)pFrm, &aInf ); SwTwips nNextIndent = 0; if( pNextFrm ) { // ich bin einzeilig SwTxtSizeInfo aNxtInf( (SwTxtFrm*)pNextFrm ); SwTxtCursor aNxtLine( (SwTxtFrm*)pNextFrm, &aNxtInf ); nNextIndent = GetLineStart( aNxtLine ); } else { // ich bin mehrzeilig if( aLine.Next() ) { nNextIndent = GetLineStart( aLine ); aLine.Prev(); } } if( nNextIndent <= GetLineStart( aLine ) ) return 0; const Point aPoint( nNextIndent, aLine.Y() ); rFndPos = aLine.GetCrsrOfst( 0, aPoint, sal_False ); if( 1 >= rFndPos ) return 0; // steht vor einem "nicht Space" const XubString& rTxt = aInf.GetTxt(); xub_Unicode aChar = rTxt.GetChar( rFndPos ); if( CH_TAB == aChar || CH_BREAK == aChar || ' ' == aChar || (( CH_TXTATR_BREAKWORD == aChar || CH_TXTATR_INWORD == aChar ) && aInf.HasHint( rFndPos ) ) ) return 0; // und hinter einem "Space" aChar = rTxt.GetChar( rFndPos - 1 ); if( CH_TAB != aChar && CH_BREAK != aChar && ( ( CH_TXTATR_BREAKWORD != aChar && CH_TXTATR_INWORD != aChar ) || !aInf.HasHint( rFndPos - 1 ) ) && // mehr als 2 Blanks !! ( ' ' != aChar || ' ' != rTxt.GetChar( rFndPos - 2 ) ) ) return 0; SwRect aRect; return aLine.GetCharRect( &aRect, rFndPos ) ? KSHORT( aRect.Left() - pFrm->Frm().Left() - pFrm->Prt().Left()) : 0; } <|endoftext|>
<commit_before><commit_msg>stop unbalanced OutputDevice Push/Pop warnings on closing help<commit_after><|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: porftn.hxx,v $ * * $Revision: 1.8 $ * * last change: $Author: rt $ $Date: 2005-09-09 04:58:44 $ * * 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 _PORFTN_HXX #define _PORFTN_HXX #include "porfld.hxx" class SwTxtFrm; class SwTxtFtn; /************************************************************************* * class SwFtnPortion *************************************************************************/ class SwFtnPortion : public SwFldPortion { SwTxtFrm *pFrm; // um im Dtor RemoveFtn rufen zu koennen. SwTxtFtn *pFtn; KSHORT nOrigHeight; public: SwFtnPortion( const XubString &rExpand, SwTxtFrm *pFrm, SwTxtFtn *pFtn, KSHORT nOrig = KSHRT_MAX ); void ClearFtn(); inline KSHORT& Orig() { return nOrigHeight; } virtual void Paint( const SwTxtPaintInfo &rInf ) const; virtual sal_Bool GetExpTxt( const SwTxtSizeInfo &rInf, XubString &rTxt ) const; virtual SwPosSize GetTxtSize( const SwTxtSizeInfo &rInfo ) const; virtual sal_Bool Format( SwTxtFormatInfo &rInf ); const SwTxtFtn* GetTxtFtn() const { return pFtn; }; OUTPUT_OPERATOR }; /************************************************************************* * class SwFtnNumPortion *************************************************************************/ class SwFtnNumPortion : public SwNumberPortion { public: inline SwFtnNumPortion( const XubString &rExpand, SwFont *pFnt ) : SwNumberPortion( rExpand, pFnt, sal_True, sal_False, 0 ) { SetWhichPor( POR_FTNNUM ); } OUTPUT_OPERATOR }; /************************************************************************* * class SwQuoVadisPortion *************************************************************************/ class SwQuoVadisPortion : public SwFldPortion { XubString aErgo; public: SwQuoVadisPortion( const XubString &rExp, const XubString& rStr ); virtual sal_Bool Format( SwTxtFormatInfo &rInf ); virtual void Paint( const SwTxtPaintInfo &rInf ) const; virtual sal_Bool GetExpTxt( const SwTxtSizeInfo &rInf, XubString &rTxt ) const; inline void SetNumber( const XubString& rStr ) { aErgo = rStr; } inline const XubString &GetQuoTxt() const { return aExpand; } inline const XubString &GetContTxt() const { return aErgo; } // Felder-Cloner fuer SplitGlue virtual SwFldPortion *Clone( const XubString &rExpand ) const; // Accessibility: pass information about this portion to the PortionHandler virtual void HandlePortion( SwPortionHandler& rPH ) const; OUTPUT_OPERATOR }; /************************************************************************* * class SwErgoSumPortion *************************************************************************/ class SwErgoSumPortion : public SwFldPortion { public: SwErgoSumPortion( const XubString &rExp, const XubString& rStr ); virtual xub_StrLen GetCrsrOfst( const KSHORT nOfst ) const; virtual sal_Bool Format( SwTxtFormatInfo &rInf ); // Felder-Cloner fuer SplitGlue virtual SwFldPortion *Clone( const XubString &rExpand ) const; OUTPUT_OPERATOR }; CLASSIO( SwFtnPortion ) CLASSIO( SwFtnNumPortion ) CLASSIO( SwQuoVadisPortion ) CLASSIO( SwErgoSumPortion ) #endif <commit_msg>INTEGRATION: CWS os94 (1.8.734); FILE MERGED 2007/03/12 08:10:45 os 1.8.734.1: #i75235# unused methods removed<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: porftn.hxx,v $ * * $Revision: 1.9 $ * * last change: $Author: rt $ $Date: 2007-04-25 09:10:26 $ * * 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 _PORFTN_HXX #define _PORFTN_HXX #include "porfld.hxx" class SwTxtFrm; class SwTxtFtn; /************************************************************************* * class SwFtnPortion *************************************************************************/ class SwFtnPortion : public SwFldPortion { SwTxtFrm *pFrm; // um im Dtor RemoveFtn rufen zu koennen. SwTxtFtn *pFtn; KSHORT nOrigHeight; public: SwFtnPortion( const XubString &rExpand, SwTxtFrm *pFrm, SwTxtFtn *pFtn, KSHORT nOrig = KSHRT_MAX ); inline KSHORT& Orig() { return nOrigHeight; } virtual void Paint( const SwTxtPaintInfo &rInf ) const; virtual sal_Bool GetExpTxt( const SwTxtSizeInfo &rInf, XubString &rTxt ) const; virtual SwPosSize GetTxtSize( const SwTxtSizeInfo &rInfo ) const; virtual sal_Bool Format( SwTxtFormatInfo &rInf ); const SwTxtFtn* GetTxtFtn() const { return pFtn; }; OUTPUT_OPERATOR }; /************************************************************************* * class SwFtnNumPortion *************************************************************************/ class SwFtnNumPortion : public SwNumberPortion { public: inline SwFtnNumPortion( const XubString &rExpand, SwFont *pFnt ) : SwNumberPortion( rExpand, pFnt, sal_True, sal_False, 0 ) { SetWhichPor( POR_FTNNUM ); } OUTPUT_OPERATOR }; /************************************************************************* * class SwQuoVadisPortion *************************************************************************/ class SwQuoVadisPortion : public SwFldPortion { XubString aErgo; public: SwQuoVadisPortion( const XubString &rExp, const XubString& rStr ); virtual sal_Bool Format( SwTxtFormatInfo &rInf ); virtual void Paint( const SwTxtPaintInfo &rInf ) const; virtual sal_Bool GetExpTxt( const SwTxtSizeInfo &rInf, XubString &rTxt ) const; inline void SetNumber( const XubString& rStr ) { aErgo = rStr; } inline const XubString &GetQuoTxt() const { return aExpand; } inline const XubString &GetContTxt() const { return aErgo; } // Felder-Cloner fuer SplitGlue virtual SwFldPortion *Clone( const XubString &rExpand ) const; // Accessibility: pass information about this portion to the PortionHandler virtual void HandlePortion( SwPortionHandler& rPH ) const; OUTPUT_OPERATOR }; /************************************************************************* * class SwErgoSumPortion *************************************************************************/ class SwErgoSumPortion : public SwFldPortion { public: SwErgoSumPortion( const XubString &rExp, const XubString& rStr ); virtual xub_StrLen GetCrsrOfst( const KSHORT nOfst ) const; virtual sal_Bool Format( SwTxtFormatInfo &rInf ); // Felder-Cloner fuer SplitGlue virtual SwFldPortion *Clone( const XubString &rExpand ) const; OUTPUT_OPERATOR }; CLASSIO( SwFtnPortion ) CLASSIO( SwFtnNumPortion ) CLASSIO( SwQuoVadisPortion ) CLASSIO( SwErgoSumPortion ) #endif <|endoftext|>
<commit_before>/**************************************************************************** * * Copyright (c) 2015 Estimation and Control Library (ECL). 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. * 3. Neither the name ECL 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. * ****************************************************************************/ /** * @file ekf.cpp * Core functions for ekf attitude and position estimator. * * @author Roman Bast <[email protected]> * */ #include "ekf.h" #include <drivers/drv_hrt.h> Ekf::Ekf(): _filter_initialised(false), _earth_rate_initialised(false), _fuse_height(false), _fuse_pos(false), _fuse_vel(false), _mag_fuse_index(0) { _earth_rate_NED.setZero(); _R_prev = matrix::Dcm<float>(); _delta_angle_corr.setZero(); _delta_vel_corr.setZero(); _vel_corr.setZero(); } Ekf::~Ekf() { } bool Ekf::update() { bool ret = false; // indicates if there has been an update if (!_filter_initialised) { _filter_initialised = initialiseFilter(); if (!_filter_initialised) { return false; } } printStates(); //printStatesFast(); // prediction if (_imu_updated) { ret = true; predictState(); predictCovariance(); } // measurement updates if (_mag_buffer.pop_first_older_than(_imu_sample_delayed.time_us, &_mag_sample_delayed)) { //fuseHeading(); fuseMag(_mag_fuse_index); _mag_fuse_index = (_mag_fuse_index + 1) % 3; } if (_baro_buffer.pop_first_older_than(_imu_sample_delayed.time_us, &_baro_sample_delayed)) { _fuse_height = true; } if (_gps_buffer.pop_first_older_than(_imu_sample_delayed.time_us, &_gps_sample_delayed)) { _fuse_pos = true; _fuse_vel = true; } if (_fuse_height || _fuse_pos || _fuse_vel) { fuseVelPosHeight(); _fuse_vel = _fuse_pos = _fuse_height = false; } if (_range_buffer.pop_first_older_than(_imu_sample_delayed.time_us, &_range_sample_delayed)) { fuseRange(); } if (_airspeed_buffer.pop_first_older_than(_imu_sample_delayed.time_us, &_airspeed_sample_delayed)) { fuseAirspeed(); } calculateOutputStates(); return ret; } bool Ekf::initialiseFilter(void) { _state.ang_error.setZero(); _state.vel.setZero(); _state.pos.setZero(); _state.gyro_bias.setZero(); _state.gyro_scale(0) = _state.gyro_scale(1) = _state.gyro_scale(2) = 1.0f; _state.accel_z_bias = 0.0f; _state.mag_I.setZero(); _state.mag_B.setZero(); _state.wind_vel.setZero(); // get initial attitude estimate from accel vector, assuming vehicle is static Vector3f accel_init = _imu_down_sampled.delta_vel / _imu_down_sampled.delta_vel_dt; float pitch = 0.0f; float roll = 0.0f; if (accel_init.norm() > 0.001f) { accel_init.normalize(); pitch = asinf(accel_init(0)); roll = -asinf(accel_init(1) / cosf(pitch)); } matrix::Euler<float> euler_init(roll, pitch, 0.0f); _state.quat_nominal = Quaternion(euler_init); magSample mag_init = _mag_buffer.get_newest(); if (mag_init.time_us == 0) { return false; } matrix::Dcm<float> R_to_earth(euler_init); _state.mag_I = R_to_earth * mag_init.mag; resetVelocity(); resetPosition(); initialiseCovariance(); return true; } void Ekf::predictState() { if (!_earth_rate_initialised) { if (_gps_initialised) { calcEarthRateNED(_earth_rate_NED, _posRef.lat_rad ); _earth_rate_initialised = true; } } // attitude error state prediciton matrix::Dcm<float> R_to_earth(_state.quat_nominal); // transformation matrix from body to world frame Vector3f corrected_delta_ang = _imu_sample_delayed.delta_ang - _R_prev * _earth_rate_NED * _imu_sample_delayed.delta_ang_dt; Quaternion dq; // delta quaternion since last update dq.from_axis_angle(corrected_delta_ang); _state.quat_nominal = dq * _state.quat_nominal; _state.quat_nominal.normalize(); _R_prev = R_to_earth.transpose(); Vector3f vel_last = _state.vel; // predict velocity states _state.vel += R_to_earth * _imu_sample_delayed.delta_vel; _state.vel(2) += 9.81f * _imu_sample_delayed.delta_vel_dt; // predict position states via trapezoidal integration of velocity _state.pos += (vel_last + _state.vel) * _imu_sample_delayed.delta_vel_dt * 0.5f; constrainStates(); } void Ekf::calculateOutputStates() { imuSample imu_new = _imu_sample_new; Vector3f delta_angle; delta_angle(0) = imu_new.delta_ang(0) * _state.gyro_scale(0); delta_angle(1) = imu_new.delta_ang(1) * _state.gyro_scale(1); delta_angle(2) = imu_new.delta_ang(2) * _state.gyro_scale(2); delta_angle -= _state.gyro_bias; Vector3f delta_vel = imu_new.delta_vel; delta_vel(2) -= _state.accel_z_bias; delta_angle += _delta_angle_corr; Quaternion dq; dq.from_axis_angle(delta_angle); _output_new.time_us = imu_new.time_us; _output_new.quat_nominal = dq * _output_new.quat_nominal; _output_new.quat_nominal.normalize(); matrix::Dcm<float> R_to_earth(_output_new.quat_nominal); Vector3f delta_vel_NED = R_to_earth * delta_vel + _delta_vel_corr; delta_vel_NED(2) += 9.81f * imu_new.delta_vel_dt; Vector3f vel_last = _output_new.vel; _output_new.vel += delta_vel_NED; _output_new.pos += (_output_new.vel + vel_last) * (imu_new.delta_vel_dt * 0.5f) + _vel_corr * imu_new.delta_vel_dt; if (_imu_updated) { _output_buffer.push(_output_new); _imu_updated = false; } if (!_output_buffer.pop_first_older_than(_imu_sample_delayed.time_us, &_output_sample_delayed)) { return; } Quaternion quat_inv = _state.quat_nominal.inversed(); Quaternion q_error = _output_sample_delayed.quat_nominal * quat_inv; q_error.normalize(); Vector3f delta_ang_error; float scalar; if (q_error(0) >= 0.0f) { scalar = -2.0f; } else { scalar = 2.0f; } delta_ang_error(0) = scalar * q_error(1); delta_ang_error(1) = scalar * q_error(2); delta_ang_error(2) = scalar * q_error(3); _delta_angle_corr = delta_ang_error * imu_new.delta_ang_dt; _delta_vel_corr = (_state.vel - _output_sample_delayed.vel) * imu_new.delta_vel_dt; _vel_corr = (_state.pos - _output_sample_delayed.pos); } void Ekf::fuseAirspeed() { } void Ekf::fuseRange() { } void Ekf::printStates() { static int counter = 0; if (counter % 50 == 0) { printf("quaternion\n"); for(int i = 0; i < 4; i++) { printf("quat %i %.5f\n", i, (double)_state.quat_nominal(i)); } matrix::Euler<float> euler(_state.quat_nominal); printf("yaw pitch roll %.5f %.5f %.5f\n", (double)euler(2), (double)euler(1), (double)euler(0)); printf("vel\n"); for(int i = 0; i < 3; i++) { printf("v %i %.5f\n", i, (double)_state.vel(i)); } printf("pos\n"); for(int i = 0; i < 3; i++) { printf("p %i %.5f\n", i, (double)_state.pos(i)); } printf("gyro_scale\n"); for(int i = 0; i < 3; i++) { printf("gs %i %.5f\n", i, (double)_state.gyro_scale(i)); } printf("mag earth\n"); for(int i = 0; i < 3; i++) { printf("mI %i %.5f\n", i, (double)_state.mag_I(i)); } printf("mag bias\n"); for(int i = 0; i < 3; i++) { printf("mB %i %.5f\n", i, (double)_state.mag_B(i)); } counter = 0; } counter++; } void Ekf::printStatesFast() { static int counter_fast = 0; if (counter_fast % 50 == 0) { printf("quaternion\n"); for(int i = 0; i < 4; i++) { printf("quat %i %.5f\n", i, (double)_output_new.quat_nominal(i)); } printf("vel\n"); for(int i = 0; i < 3; i++) { printf("v %i %.5f\n", i, (double)_output_new.vel(i)); } printf("pos\n"); for(int i = 0; i < 3; i++) { printf("p %i %.5f\n", i, (double)_output_new.pos(i)); } counter_fast = 0; } counter_fast++; } <commit_msg>EKF: Remove excessive verbosity<commit_after>/**************************************************************************** * * Copyright (c) 2015 Estimation and Control Library (ECL). 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. * 3. Neither the name ECL 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. * ****************************************************************************/ /** * @file ekf.cpp * Core functions for ekf attitude and position estimator. * * @author Roman Bast <[email protected]> * */ #include "ekf.h" #include <drivers/drv_hrt.h> Ekf::Ekf(): _filter_initialised(false), _earth_rate_initialised(false), _fuse_height(false), _fuse_pos(false), _fuse_vel(false), _mag_fuse_index(0) { _earth_rate_NED.setZero(); _R_prev = matrix::Dcm<float>(); _delta_angle_corr.setZero(); _delta_vel_corr.setZero(); _vel_corr.setZero(); } Ekf::~Ekf() { } bool Ekf::update() { bool ret = false; // indicates if there has been an update if (!_filter_initialised) { _filter_initialised = initialiseFilter(); if (!_filter_initialised) { return false; } } //printStates(); //printStatesFast(); // prediction if (_imu_updated) { ret = true; predictState(); predictCovariance(); } // measurement updates if (_mag_buffer.pop_first_older_than(_imu_sample_delayed.time_us, &_mag_sample_delayed)) { //fuseHeading(); fuseMag(_mag_fuse_index); _mag_fuse_index = (_mag_fuse_index + 1) % 3; } if (_baro_buffer.pop_first_older_than(_imu_sample_delayed.time_us, &_baro_sample_delayed)) { _fuse_height = true; } if (_gps_buffer.pop_first_older_than(_imu_sample_delayed.time_us, &_gps_sample_delayed)) { _fuse_pos = true; _fuse_vel = true; } if (_fuse_height || _fuse_pos || _fuse_vel) { fuseVelPosHeight(); _fuse_vel = _fuse_pos = _fuse_height = false; } if (_range_buffer.pop_first_older_than(_imu_sample_delayed.time_us, &_range_sample_delayed)) { fuseRange(); } if (_airspeed_buffer.pop_first_older_than(_imu_sample_delayed.time_us, &_airspeed_sample_delayed)) { fuseAirspeed(); } calculateOutputStates(); return ret; } bool Ekf::initialiseFilter(void) { _state.ang_error.setZero(); _state.vel.setZero(); _state.pos.setZero(); _state.gyro_bias.setZero(); _state.gyro_scale(0) = _state.gyro_scale(1) = _state.gyro_scale(2) = 1.0f; _state.accel_z_bias = 0.0f; _state.mag_I.setZero(); _state.mag_B.setZero(); _state.wind_vel.setZero(); // get initial attitude estimate from accel vector, assuming vehicle is static Vector3f accel_init = _imu_down_sampled.delta_vel / _imu_down_sampled.delta_vel_dt; float pitch = 0.0f; float roll = 0.0f; if (accel_init.norm() > 0.001f) { accel_init.normalize(); pitch = asinf(accel_init(0)); roll = -asinf(accel_init(1) / cosf(pitch)); } matrix::Euler<float> euler_init(roll, pitch, 0.0f); _state.quat_nominal = Quaternion(euler_init); magSample mag_init = _mag_buffer.get_newest(); if (mag_init.time_us == 0) { return false; } matrix::Dcm<float> R_to_earth(euler_init); _state.mag_I = R_to_earth * mag_init.mag; resetVelocity(); resetPosition(); initialiseCovariance(); return true; } void Ekf::predictState() { if (!_earth_rate_initialised) { if (_gps_initialised) { calcEarthRateNED(_earth_rate_NED, _posRef.lat_rad ); _earth_rate_initialised = true; } } // attitude error state prediciton matrix::Dcm<float> R_to_earth(_state.quat_nominal); // transformation matrix from body to world frame Vector3f corrected_delta_ang = _imu_sample_delayed.delta_ang - _R_prev * _earth_rate_NED * _imu_sample_delayed.delta_ang_dt; Quaternion dq; // delta quaternion since last update dq.from_axis_angle(corrected_delta_ang); _state.quat_nominal = dq * _state.quat_nominal; _state.quat_nominal.normalize(); _R_prev = R_to_earth.transpose(); Vector3f vel_last = _state.vel; // predict velocity states _state.vel += R_to_earth * _imu_sample_delayed.delta_vel; _state.vel(2) += 9.81f * _imu_sample_delayed.delta_vel_dt; // predict position states via trapezoidal integration of velocity _state.pos += (vel_last + _state.vel) * _imu_sample_delayed.delta_vel_dt * 0.5f; constrainStates(); } void Ekf::calculateOutputStates() { imuSample imu_new = _imu_sample_new; Vector3f delta_angle; delta_angle(0) = imu_new.delta_ang(0) * _state.gyro_scale(0); delta_angle(1) = imu_new.delta_ang(1) * _state.gyro_scale(1); delta_angle(2) = imu_new.delta_ang(2) * _state.gyro_scale(2); delta_angle -= _state.gyro_bias; Vector3f delta_vel = imu_new.delta_vel; delta_vel(2) -= _state.accel_z_bias; delta_angle += _delta_angle_corr; Quaternion dq; dq.from_axis_angle(delta_angle); _output_new.time_us = imu_new.time_us; _output_new.quat_nominal = dq * _output_new.quat_nominal; _output_new.quat_nominal.normalize(); matrix::Dcm<float> R_to_earth(_output_new.quat_nominal); Vector3f delta_vel_NED = R_to_earth * delta_vel + _delta_vel_corr; delta_vel_NED(2) += 9.81f * imu_new.delta_vel_dt; Vector3f vel_last = _output_new.vel; _output_new.vel += delta_vel_NED; _output_new.pos += (_output_new.vel + vel_last) * (imu_new.delta_vel_dt * 0.5f) + _vel_corr * imu_new.delta_vel_dt; if (_imu_updated) { _output_buffer.push(_output_new); _imu_updated = false; } if (!_output_buffer.pop_first_older_than(_imu_sample_delayed.time_us, &_output_sample_delayed)) { return; } Quaternion quat_inv = _state.quat_nominal.inversed(); Quaternion q_error = _output_sample_delayed.quat_nominal * quat_inv; q_error.normalize(); Vector3f delta_ang_error; float scalar; if (q_error(0) >= 0.0f) { scalar = -2.0f; } else { scalar = 2.0f; } delta_ang_error(0) = scalar * q_error(1); delta_ang_error(1) = scalar * q_error(2); delta_ang_error(2) = scalar * q_error(3); _delta_angle_corr = delta_ang_error * imu_new.delta_ang_dt; _delta_vel_corr = (_state.vel - _output_sample_delayed.vel) * imu_new.delta_vel_dt; _vel_corr = (_state.pos - _output_sample_delayed.pos); } void Ekf::fuseAirspeed() { } void Ekf::fuseRange() { } void Ekf::printStates() { static int counter = 0; if (counter % 50 == 0) { printf("quaternion\n"); for(int i = 0; i < 4; i++) { printf("quat %i %.5f\n", i, (double)_state.quat_nominal(i)); } matrix::Euler<float> euler(_state.quat_nominal); printf("yaw pitch roll %.5f %.5f %.5f\n", (double)euler(2), (double)euler(1), (double)euler(0)); printf("vel\n"); for(int i = 0; i < 3; i++) { printf("v %i %.5f\n", i, (double)_state.vel(i)); } printf("pos\n"); for(int i = 0; i < 3; i++) { printf("p %i %.5f\n", i, (double)_state.pos(i)); } printf("gyro_scale\n"); for(int i = 0; i < 3; i++) { printf("gs %i %.5f\n", i, (double)_state.gyro_scale(i)); } printf("mag earth\n"); for(int i = 0; i < 3; i++) { printf("mI %i %.5f\n", i, (double)_state.mag_I(i)); } printf("mag bias\n"); for(int i = 0; i < 3; i++) { printf("mB %i %.5f\n", i, (double)_state.mag_B(i)); } counter = 0; } counter++; } void Ekf::printStatesFast() { static int counter_fast = 0; if (counter_fast % 50 == 0) { printf("quaternion\n"); for(int i = 0; i < 4; i++) { printf("quat %i %.5f\n", i, (double)_output_new.quat_nominal(i)); } printf("vel\n"); for(int i = 0; i < 3; i++) { printf("v %i %.5f\n", i, (double)_output_new.vel(i)); } printf("pos\n"); for(int i = 0; i < 3; i++) { printf("p %i %.5f\n", i, (double)_output_new.pos(i)); } counter_fast = 0; } counter_fast++; } <|endoftext|>
<commit_before>#include "BRDBoard.h" #include "FileFormats/BRDFile.h" #include <cerrno> #include <fstream> #include <functional> #include <iostream> #include <sstream> #include <string> #include <vector> using namespace std; using namespace std::placeholders; const string BRDBoard::kNetUnconnectedPrefix = "UNCONNECTED"; const string BRDBoard::kComponentDummyName = "..."; BRDBoard::BRDBoard(const BRDFile *const boardFile) : m_file(boardFile) { // TODO: strip / trim all strings, especially those used as keys // TODO: just loop through original arrays? vector<BRDPart> m_parts(m_file->num_parts); vector<BRDPin> m_pins(m_file->num_pins); vector<BRDNail> m_nails(m_file->num_nails); vector<BRDPoint> m_points(m_file->num_format); m_parts = m_file->parts; m_pins = m_file->pins; m_nails = m_file->nails; m_points = m_file->format; // Set outline { for (auto &brdPoint : m_points) { auto point = make_shared<Point>(brdPoint.x, brdPoint.y); outline_.push_back(point); } } // Populate map of unique nets SharedStringMap<Net> net_map; { // adding special net 'UNCONNECTED' auto net_nc = make_shared<Net>(); net_nc->name = kNetUnconnectedPrefix; net_nc->is_ground = false; net_map[net_nc->name] = net_nc; // handle all the others for (auto &brd_nail : m_nails) { auto net = make_shared<Net>(); // copy NET name and number (probe) net->name = string(brd_nail.net); // avoid having multiple UNCONNECTED<XXX> references if (is_prefix(kNetUnconnectedPrefix, net->name)) continue; // check whether the pin represents ground net->is_ground = (net->name == "GND"); net->number = brd_nail.probe; if (brd_nail.side == 1) { net->board_side = kBoardSideTop; } else { net->board_side = kBoardSideBottom; } // so we can find nets later by name (making unique by name) net_map[net->name] = net; } } // Populate parts { for (auto &brd_part : m_parts) { auto comp = make_shared<Component>(); comp->name = string(brd_part.name); comp->mfgcode = std::move(brd_part.mfgcode); comp->p1 = {brd_part.p1.x, brd_part.p1.y}; comp->p2 = {brd_part.p2.x, brd_part.p2.y}; // is it some dummy component to indicate test pads? if (is_prefix(kComponentDummyName, comp->name)) comp->component_type = Component::kComponentTypeDummy; // check what side the board is on (sorcery?) if (brd_part.mounting_side == BRDPartMountingSide::Top) { comp->board_side = kBoardSideTop; } else if (brd_part.mounting_side == BRDPartMountingSide::Bottom) { comp->board_side = kBoardSideBottom; } else { comp->board_side = kBoardSideBoth; } comp->mount_type = (brd_part.part_type == BRDPartType::SMD) ? Component::kMountTypeSMD : Component::kMountTypeDIP; components_.push_back(comp); } } // Populate pins { // generate dummy component as reference auto comp_dummy = make_shared<Component>(); comp_dummy->name = kComponentDummyName; comp_dummy->component_type = Component::kComponentTypeDummy; // NOTE: originally the pin diameter depended on part.name[0] == 'U' ? unsigned int pin_idx = 0; unsigned int part_idx = 1; auto pins = m_pins; auto parts = m_parts; for (size_t i = 0; i < pins.size(); i++) { // (originally from BoardView::DrawPins) const BRDPin &brd_pin = pins[i]; std::shared_ptr<Component> comp = components_[brd_pin.part - 1]; if (!comp) continue; auto pin = make_shared<Pin>(); if (comp->is_dummy()) { // component is virtual, i.e. "...", pin is test pad pin->type = Pin::kPinTypeTestPad; pin->component = comp_dummy; comp_dummy->pins.push_back(pin); } else { // component is regular / not virtual pin->type = Pin::kPinTypeComponent; pin->component = comp; pin->board_side = pin->component->board_side; comp->pins.push_back(pin); } // determine pin number on part ++pin_idx; if (brd_pin.part != part_idx) { part_idx = brd_pin.part; pin_idx = 1; } if (brd_pin.snum) { pin->number = brd_pin.snum; } else { pin->number = std::to_string(pin_idx); } // Lets us see BGA pad names finally // if (brd_pin.name) { pin->name = std::string(brd_pin.name); } else { pin->name = pin->number; } // copy position pin->position = Point(brd_pin.pos.x, brd_pin.pos.y); // set net reference (here's our NET key string again) string net_name = string(brd_pin.net); if (net_map.count(net_name)) { // there is a net with that name in our map pin->net = net_map[net_name].get(); if (pin->type == Pin::kPinTypeTestPad) { pin->board_side = pin->net->board_side; } } else { // no net with that name registered, so create one if (!net_name.empty()) { if (is_prefix(kNetUnconnectedPrefix, net_name)) { // pin is unconnected, so reference our special net pin->net = net_map[kNetUnconnectedPrefix].get(); pin->type = Pin::kPinTypeNotConnected; } else { // indeed a new net auto net = make_shared<Net>(); net->name = net_name; net->board_side = pin->board_side; // NOTE: net->number not set net_map[net_name] = net; pin->net = net.get(); } } else { // not sure this can happen -> no info // It does happen in .fz apparently and produces a SEGFAULT… Use // unconnected net. pin->net = net_map[kNetUnconnectedPrefix].get(); pin->type = Pin::kPinTypeNotConnected; } } // TODO: should either depend on file specs or type etc // // if(brd_pin.radius) pin->diameter = brd_pin.radius; // some format // (.fz) contains a radius field // else pin->diameter = 0.5f; pin->diameter = brd_pin.radius; // some format (.fz) contains a radius field pin->net->pins.push_back(pin); pins_.push_back(pin); } // remove all dummy components from vector, add our official dummy components_.erase( remove_if(begin(components_), end(components_), [](shared_ptr<Component> &comp) { return comp->is_dummy(); }), end(components_)); components_.push_back(comp_dummy); } // Populate Net vector by using the map. (sorted by keys) for (auto &net : net_map) { nets_.push_back(net.second); } // Sort components by name sort(begin(components_), end(components_), [](const shared_ptr<Component> &lhs, const shared_ptr<Component> &rhs) { return lhs->name < rhs->name; }); } BRDBoard::~BRDBoard() {} SharedVector<Component> &BRDBoard::Components() { return components_; } SharedVector<Pin> &BRDBoard::Pins() { return pins_; } SharedVector<Net> &BRDBoard::Nets() { return nets_; } SharedVector<Point> &BRDBoard::OutlinePoints() { return outline_; } Board::EBoardType BRDBoard::BoardType() { return kBoardTypeBRD; } <commit_msg>Detecting ground pins on files without net lists<commit_after>#include "BRDBoard.h" #include "FileFormats/BRDFile.h" #include <cerrno> #include <fstream> #include <functional> #include <iostream> #include <sstream> #include <string> #include <vector> using namespace std; using namespace std::placeholders; const string BRDBoard::kNetUnconnectedPrefix = "UNCONNECTED"; const string BRDBoard::kComponentDummyName = "..."; BRDBoard::BRDBoard(const BRDFile *const boardFile) : m_file(boardFile) { // TODO: strip / trim all strings, especially those used as keys // TODO: just loop through original arrays? vector<BRDPart> m_parts(m_file->num_parts); vector<BRDPin> m_pins(m_file->num_pins); vector<BRDNail> m_nails(m_file->num_nails); vector<BRDPoint> m_points(m_file->num_format); m_parts = m_file->parts; m_pins = m_file->pins; m_nails = m_file->nails; m_points = m_file->format; // Set outline { for (auto &brdPoint : m_points) { auto point = make_shared<Point>(brdPoint.x, brdPoint.y); outline_.push_back(point); } } // Populate map of unique nets SharedStringMap<Net> net_map; { // adding special net 'UNCONNECTED' auto net_nc = make_shared<Net>(); net_nc->name = kNetUnconnectedPrefix; net_nc->is_ground = false; net_map[net_nc->name] = net_nc; // handle all the others for (auto &brd_nail : m_nails) { auto net = make_shared<Net>(); // copy NET name and number (probe) net->name = string(brd_nail.net); // avoid having multiple UNCONNECTED<XXX> references if (is_prefix(kNetUnconnectedPrefix, net->name)) continue; net->number = brd_nail.probe; if (brd_nail.side == 1) { net->board_side = kBoardSideTop; } else { net->board_side = kBoardSideBottom; } // so we can find nets later by name (making unique by name) net_map[net->name] = net; } } // Populate parts { for (auto &brd_part : m_parts) { auto comp = make_shared<Component>(); comp->name = string(brd_part.name); comp->mfgcode = std::move(brd_part.mfgcode); comp->p1 = {brd_part.p1.x, brd_part.p1.y}; comp->p2 = {brd_part.p2.x, brd_part.p2.y}; // is it some dummy component to indicate test pads? if (is_prefix(kComponentDummyName, comp->name)) comp->component_type = Component::kComponentTypeDummy; // check what side the board is on (sorcery?) if (brd_part.mounting_side == BRDPartMountingSide::Top) { comp->board_side = kBoardSideTop; } else if (brd_part.mounting_side == BRDPartMountingSide::Bottom) { comp->board_side = kBoardSideBottom; } else { comp->board_side = kBoardSideBoth; } comp->mount_type = (brd_part.part_type == BRDPartType::SMD) ? Component::kMountTypeSMD : Component::kMountTypeDIP; components_.push_back(comp); } } // Populate pins { // generate dummy component as reference auto comp_dummy = make_shared<Component>(); comp_dummy->name = kComponentDummyName; comp_dummy->component_type = Component::kComponentTypeDummy; // NOTE: originally the pin diameter depended on part.name[0] == 'U' ? unsigned int pin_idx = 0; unsigned int part_idx = 1; auto pins = m_pins; auto parts = m_parts; for (size_t i = 0; i < pins.size(); i++) { // (originally from BoardView::DrawPins) const BRDPin &brd_pin = pins[i]; std::shared_ptr<Component> comp = components_[brd_pin.part - 1]; if (!comp) continue; auto pin = make_shared<Pin>(); if (comp->is_dummy()) { // component is virtual, i.e. "...", pin is test pad pin->type = Pin::kPinTypeTestPad; pin->component = comp_dummy; comp_dummy->pins.push_back(pin); } else { // component is regular / not virtual pin->type = Pin::kPinTypeComponent; pin->component = comp; pin->board_side = pin->component->board_side; comp->pins.push_back(pin); } // determine pin number on part ++pin_idx; if (brd_pin.part != part_idx) { part_idx = brd_pin.part; pin_idx = 1; } if (brd_pin.snum) { pin->number = brd_pin.snum; } else { pin->number = std::to_string(pin_idx); } // Lets us see BGA pad names finally // if (brd_pin.name) { pin->name = std::string(brd_pin.name); } else { pin->name = pin->number; } // copy position pin->position = Point(brd_pin.pos.x, brd_pin.pos.y); // set net reference (here's our NET key string again) string net_name = string(brd_pin.net); if (net_map.count(net_name)) { // there is a net with that name in our map pin->net = net_map[net_name].get(); if (pin->type == Pin::kPinTypeTestPad) { pin->board_side = pin->net->board_side; } } else { // no net with that name registered, so create one if (!net_name.empty()) { if (is_prefix(kNetUnconnectedPrefix, net_name)) { // pin is unconnected, so reference our special net pin->net = net_map[kNetUnconnectedPrefix].get(); pin->type = Pin::kPinTypeNotConnected; } else { // indeed a new net auto net = make_shared<Net>(); net->name = net_name; net->board_side = pin->board_side; // NOTE: net->number not set net_map[net_name] = net; pin->net = net.get(); } } else { // not sure this can happen -> no info // It does happen in .fz apparently and produces a SEGFAULT… Use // unconnected net. pin->net = net_map[kNetUnconnectedPrefix].get(); pin->type = Pin::kPinTypeNotConnected; } } // TODO: should either depend on file specs or type etc // // if(brd_pin.radius) pin->diameter = brd_pin.radius; // some format // (.fz) contains a radius field // else pin->diameter = 0.5f; pin->diameter = brd_pin.radius; // some format (.fz) contains a radius field pin->net->pins.push_back(pin); pins_.push_back(pin); } // remove all dummy components from vector, add our official dummy components_.erase( remove_if(begin(components_), end(components_), [](shared_ptr<Component> &comp) { return comp->is_dummy(); }), end(components_)); components_.push_back(comp_dummy); } // Populate Net vector by using the map. (sorted by keys) for (auto &net : net_map) { // check whether the pin represents ground net.second->is_ground = (net.second->name == "GND"); nets_.push_back(net.second); } // Sort components by name sort(begin(components_), end(components_), [](const shared_ptr<Component> &lhs, const shared_ptr<Component> &rhs) { return lhs->name < rhs->name; }); } BRDBoard::~BRDBoard() {} SharedVector<Component> &BRDBoard::Components() { return components_; } SharedVector<Pin> &BRDBoard::Pins() { return pins_; } SharedVector<Net> &BRDBoard::Nets() { return nets_; } SharedVector<Point> &BRDBoard::OutlinePoints() { return outline_; } Board::EBoardType BRDBoard::BoardType() { return kBoardTypeBRD; } <|endoftext|>
<commit_before>// Vasilii Bodnariuk #include <stdlib.h> #include <iostream> #include <string.h> #include <string> using namespace std; int good_str(char* data) { int i = 0; bool binary_operator = false; while(data[i] != '\0') { switch (data[i]) { case '+': case '/': case '*': if(binary_operator) { return 0; } binary_operator = true; break; case ' ': break; case '-': if(binary_operator) { data[i] = '~'; } else { binary_operator = true; } break; default: if(data[i] < '0' || data[i] > '9') { return 0; } binary_operator = false; } ++i; } return i; } int digit(char c) { return int(c) - '0'; } int skip_blanks(char* data, int start) { while(data[start] == ' ') { ++start; } return start; } int number(char* data, int start, int len) { int accumulator = 0; int i = skip_blanks(data, start); bool negative = data[i] == '~'; if (negative) { ++i; } i = skip_blanks(data, i); while(data[i] >= '0' && data[i] <= '9') { accumulator = 10 * accumulator + digit(data[i]); ++i; } return negative ? -accumulator : accumulator; } double term(char* data, int start, int len, bool last_mult) { start = skip_blanks(data, start); int i = start; while(i < len) { switch (data[i]) { case '*': case '/': if (true) { double tail = term(data, i + 1, len, data[i] == '*'); if((data[i] == '/') == last_mult) { return number(data, start, i) / tail; } else { return number(data, start, i) * tail; } } } ++i; i = skip_blanks(data, i); } return number(data, start, len); } double expression(char* data, int start, int len, bool last_plus) { start = skip_blanks(data, start); int i = start; while(i < len) { switch (data[i]) { case '-': case '+': { double tail = expression(data, i + 1, len, data[i] == '+'); if((data[i] == '-') == last_plus) { tail = - tail; } return term(data, start, i, true) + tail; } } ++i; i = skip_blanks(data, i); } return term(data, start, len, true); } int main(int argc, char* argv[]) { if(argc != 2) { cout << "usage:" << '\n'; cout << argv[0] << " expression" << '\n'; cout << "example:" << '\n'; cout << argv[0] << " \"-12 * 2 / 3 + 8 * 2 / 1\"" << '\n'; } else { auto data = argv[1]; double e; int len = good_str(data); if (len > 0) { e = expression(data, 0, len, true); cout << e << "\n"; } else { cout << "The program processes an arithmetic expression of integers!" << "\n"; return -1; } } return 0; } <commit_msg>zero div exception<commit_after>// Vasilii Bodnariuk // #include <stdlib.h> // #include <string.h> #include <math.h> #include <iostream> #include <string> using namespace std; enum errors { ERR_ZERO_DIV = 0, }; int good_str(char* data) { int i = 0; bool binary_operator = false; while(data[i] != '\0') { switch (data[i]) { case '+': case '/': case '*': if(binary_operator) { return 0; } binary_operator = true; break; case ' ': break; case '-': if(binary_operator) { data[i] = '~'; } else { binary_operator = true; } break; default: if(data[i] < '0' || data[i] > '9') { return 0; } binary_operator = false; } ++i; } return i; } int digit(char c) { return int(c) - '0'; } int skip_blanks(char* data, int start) { while(data[start] == ' ') { ++start; } return start; } int number(char* data, int start, int len) { int accumulator = 0; int i = skip_blanks(data, start); bool negative = data[i] == '~'; if (negative) { ++i; } i = skip_blanks(data, i); while(data[i] >= '0' && data[i] <= '9') { accumulator = 10 * accumulator + digit(data[i]); ++i; } return negative ? -accumulator : accumulator; } double term(char* data, int start, int len, bool last_mult) { start = skip_blanks(data, start); int i = start; while(i < len) { switch (data[i]) { case '*': case '/': if (true) { double tail = term(data, i + 1, len, data[i] == '*'); if((data[i] == '/') == last_mult) { double result = number(data, start, i) / tail; if(isinf(result)) { throw ERR_ZERO_DIV; } return result; } else { return number(data, start, i) * tail; } } } ++i; i = skip_blanks(data, i); } return number(data, start, len); } double expression(char* data, int start, int len, bool last_plus) { start = skip_blanks(data, start); int i = start; while(i < len) { switch (data[i]) { case '-': case '+': { double tail = expression(data, i + 1, len, data[i] == '+'); if((data[i] == '-') == last_plus) { tail = - tail; } return term(data, start, i, true) + tail; } } ++i; i = skip_blanks(data, i); } return term(data, start, len, true); } int main(int argc, char* argv[]) { if(argc != 2) { cout << "usage:" << '\n'; cout << argv[0] << " expression" << '\n'; cout << "example:" << '\n'; cout << argv[0] << " \"-12 * 2 / 3 + 8 * 2 / 1\"" << '\n'; } else { auto data = argv[1]; double result; int len = good_str(data); if(len > 0) { try { result = expression(data, 0, len, true); cout << result << "\n"; } catch(errors e) { switch (e) { case ERR_ZERO_DIV: cout << "Zero division error!" << "\n"; } } } else { cout << "The program processes an arithmetic expression of integers!" << "\n"; return -1; } } return 0; } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: labprt.hxx,v $ * * $Revision: 1.5 $ * * last change: $Author: vg $ $Date: 2007-10-22 15:15:36 $ * * 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 _LABPRT_HXX #define _LABPRT_HXX #ifndef _SV_GROUP_HXX //autogen #include <vcl/group.hxx> #endif #ifndef _SV_FIELD_HXX //autogen #include <vcl/field.hxx> #endif #ifndef _STDCTRL_HXX //autogen #include <svtools/stdctrl.hxx> #endif #ifndef _SV_BUTTON_HXX //autogen #include <vcl/button.hxx> #endif #ifndef _SFXTABDLG_HXX //autogen #include <sfx2/tabdlg.hxx> #endif class SwLabDlg; class SwLabItem; // class SwLabPrtPage ------------------------------------------------------- class SwLabPrtPage : public SfxTabPage { Printer* pPrinter; //Fuer die Schachteinstellug - leider. RadioButton aPageButton; RadioButton aSingleButton; FixedText aColText; NumericField aColField; FixedText aRowText; NumericField aRowField; CheckBox aSynchronCB; FixedLine aFLDontKnow; FixedInfo aPrinterInfo; PushButton aPrtSetup; FixedLine aFLPrinter; SwLabPrtPage(Window* pParent, const SfxItemSet& rSet); ~SwLabPrtPage(); DECL_LINK( CountHdl, Button * ); using Window::GetParent; SwLabDlg* GetParent() {return (SwLabDlg*) SfxTabPage::GetParent()->GetParent();} using TabPage::ActivatePage; using TabPage::DeactivatePage; public: static SfxTabPage* Create(Window* pParent, const SfxItemSet& rSet); virtual void ActivatePage(const SfxItemSet& rSet); virtual int DeactivatePage(SfxItemSet* pSet = 0); void FillItem(SwLabItem& rItem); virtual BOOL FillItemSet(SfxItemSet& rSet); virtual void Reset(const SfxItemSet& rSet); inline Printer* GetPrt() { return (pPrinter); } }; #endif <commit_msg>INTEGRATION: CWS changefileheader (1.5.216); FILE MERGED 2008/04/01 15:58:59 thb 1.5.216.2: #i85898# Stripping all external header guards 2008/03/31 16:57:52 rt 1.5.216.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: labprt.hxx,v $ * $Revision: 1.6 $ * * 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 _LABPRT_HXX #define _LABPRT_HXX #include <vcl/group.hxx> #include <vcl/field.hxx> #include <svtools/stdctrl.hxx> #ifndef _SV_BUTTON_HXX //autogen #include <vcl/button.hxx> #endif #include <sfx2/tabdlg.hxx> class SwLabDlg; class SwLabItem; // class SwLabPrtPage ------------------------------------------------------- class SwLabPrtPage : public SfxTabPage { Printer* pPrinter; //Fuer die Schachteinstellug - leider. RadioButton aPageButton; RadioButton aSingleButton; FixedText aColText; NumericField aColField; FixedText aRowText; NumericField aRowField; CheckBox aSynchronCB; FixedLine aFLDontKnow; FixedInfo aPrinterInfo; PushButton aPrtSetup; FixedLine aFLPrinter; SwLabPrtPage(Window* pParent, const SfxItemSet& rSet); ~SwLabPrtPage(); DECL_LINK( CountHdl, Button * ); using Window::GetParent; SwLabDlg* GetParent() {return (SwLabDlg*) SfxTabPage::GetParent()->GetParent();} using TabPage::ActivatePage; using TabPage::DeactivatePage; public: static SfxTabPage* Create(Window* pParent, const SfxItemSet& rSet); virtual void ActivatePage(const SfxItemSet& rSet); virtual int DeactivatePage(SfxItemSet* pSet = 0); void FillItem(SwLabItem& rItem); virtual BOOL FillItemSet(SfxItemSet& rSet); virtual void Reset(const SfxItemSet& rSet); inline Printer* GetPrt() { return (pPrinter); } }; #endif <|endoftext|>
<commit_before>// @(#)root/graf:$Name: $:$Id: TArc.cxx,v 1.9 2005/11/11 17:31:48 couet Exp $ // Author: Rene Brun 16/10/95 /************************************************************************* * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ #include "Riostream.h" #include "TROOT.h" #include "TArc.h" #include "TVirtualPad.h" ClassImp(TArc) //______________________________________________________________________________ // // An arc is specified with the position of its centre, its radius // a minimum and maximum angle. // The attributes of the outline line are given via TAttLine // The attributes of the fill area are given via TAttFill // //______________________________________________________________________________ TArc::TArc(): TEllipse() { // Arc default constructor. } //______________________________________________________________________________ TArc::TArc(Double_t x1, Double_t y1,Double_t r1,Double_t phimin,Double_t phimax) :TEllipse(x1,y1,r1,r1,phimin,phimax,0) { // Arc normal constructor. // // x1,y1 : coordinates of centre of arc // r1 : arc radius // phimin : min and max angle in degrees (default is 0-->360) // phimax : // // When a circle sector only is drawn, the lines connecting the center // of the arc to the edges are drawn by default. One can specify // the drawing option "only" to not draw these lines. } //______________________________________________________________________________ TArc::TArc(const TArc &arc) : TEllipse(arc) { // Copy constructor. ((TArc&)arc).Copy(*this); } //______________________________________________________________________________ TArc::~TArc() { // Arc default destructor. } //______________________________________________________________________________ void TArc::Copy(TObject &arc) const { // Copy this arc to arc. TEllipse::Copy(arc); } //______________________________________________________________________________ void TArc::DrawArc(Double_t x1, Double_t y1,Double_t r1,Double_t phimin,Double_t phimax,Option_t *option) { // Draw this arc with new coordinates. TArc *newarc = new TArc(x1, y1, r1, phimin, phimax); TAttLine::Copy(*newarc); TAttFill::Copy(*newarc); newarc->AppendPad(option); } //______________________________________________________________________________ void TArc::SavePrimitive(ostream &out, Option_t * /*= ""*/) { // Save primitive as a C++ statement(s) on output stream out out<<" "<<endl; if (gROOT->ClassSaved(TArc::Class())) { out<<" "; } else { out<<" TArc *"; } out<<"arc = new TArc("<<fX1<<","<<fY1<<","<<fR1 <<","<<fPhimin<<","<<fPhimax<<");"<<endl; SaveFillAttributes(out,"arc",0,1001); SaveLineAttributes(out,"arc",1,1,1); if (GetNoEdges()) out<<" arc->SetNoEdges();"<<endl; out<<" arc->Draw();"<<endl; } <commit_msg>In TArc::DrawArc, one must set the kCanDelete bit for the cloned object (thanks jan Musinski)<commit_after>// @(#)root/graf:$Name: $:$Id: TArc.cxx,v 1.10 2006/07/03 16:10:44 brun Exp $ // Author: Rene Brun 16/10/95 /************************************************************************* * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ #include "Riostream.h" #include "TROOT.h" #include "TArc.h" #include "TVirtualPad.h" ClassImp(TArc) //______________________________________________________________________________ // // An arc is specified with the position of its centre, its radius // a minimum and maximum angle. // The attributes of the outline line are given via TAttLine // The attributes of the fill area are given via TAttFill // //______________________________________________________________________________ TArc::TArc(): TEllipse() { // Arc default constructor. } //______________________________________________________________________________ TArc::TArc(Double_t x1, Double_t y1,Double_t r1,Double_t phimin,Double_t phimax) :TEllipse(x1,y1,r1,r1,phimin,phimax,0) { // Arc normal constructor. // // x1,y1 : coordinates of centre of arc // r1 : arc radius // phimin : min and max angle in degrees (default is 0-->360) // phimax : // // When a circle sector only is drawn, the lines connecting the center // of the arc to the edges are drawn by default. One can specify // the drawing option "only" to not draw these lines. } //______________________________________________________________________________ TArc::TArc(const TArc &arc) : TEllipse(arc) { // Copy constructor. ((TArc&)arc).Copy(*this); } //______________________________________________________________________________ TArc::~TArc() { // Arc default destructor. } //______________________________________________________________________________ void TArc::Copy(TObject &arc) const { // Copy this arc to arc. TEllipse::Copy(arc); } //______________________________________________________________________________ void TArc::DrawArc(Double_t x1, Double_t y1,Double_t r1,Double_t phimin,Double_t phimax,Option_t *option) { // Draw this arc with new coordinates. TArc *newarc = new TArc(x1, y1, r1, phimin, phimax); TAttLine::Copy(*newarc); TAttFill::Copy(*newarc); newarc->SetBit(kCanDelete); newarc->AppendPad(option); } //______________________________________________________________________________ void TArc::SavePrimitive(ostream &out, Option_t * /*= ""*/) { // Save primitive as a C++ statement(s) on output stream out out<<" "<<endl; if (gROOT->ClassSaved(TArc::Class())) { out<<" "; } else { out<<" TArc *"; } out<<"arc = new TArc("<<fX1<<","<<fY1<<","<<fR1 <<","<<fPhimin<<","<<fPhimax<<");"<<endl; SaveFillAttributes(out,"arc",0,1001); SaveLineAttributes(out,"arc",1,1,1); if (GetNoEdges()) out<<" arc->SetNoEdges();"<<endl; out<<" arc->Draw();"<<endl; } <|endoftext|>
<commit_before>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield * * This library is open source and may be redistributed and/or modified under * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or * (at your option) any later version. The full license is in LICENSE file * included with this distribution, and on the openscenegraph.org website. * * 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 * OpenSceneGraph Public License for more details. */ #include <osgUtil/RayIntersector> #include <osgUtil/LineSegmentIntersector> #include <osg/KdTree> #include <osg/Notify> #include <osg/TexMat> #include <limits> #include <cmath> using namespace osg; using namespace osgUtil; /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // RayIntersector // RayIntersector::RayIntersector(CoordinateFrame cf, RayIntersector* parent, Intersector::IntersectionLimit intersectionLimit) : Intersector(cf, intersectionLimit), _parent(parent) { if (parent) setPrecisionHint(parent->getPrecisionHint()); } RayIntersector::RayIntersector(const Vec3d& start, const Vec3d& direction) : Intersector(), _start(start), _direction(direction) { } RayIntersector::RayIntersector(CoordinateFrame cf, const Vec3d& start, const Vec3d& direction, RayIntersector* parent, Intersector::IntersectionLimit intersectionLimit) : Intersector(cf, intersectionLimit), _parent(parent), _start(start), _direction(direction) { if (parent) setPrecisionHint(parent->getPrecisionHint()); } RayIntersector::RayIntersector(CoordinateFrame cf, double x, double y) : Intersector(cf), _parent(0) { switch(cf) { case WINDOW: setStart(Vec3d(x,y,0.)); setDirection(Vec3d(0.,0.,1.)); break; case PROJECTION: setStart(Vec3d(x,y,-1.)); setDirection(Vec3d(0.,0.,1.)); break; case VIEW: setStart(Vec3d(x,y,0.)); setDirection(Vec3d(0.,0.,1.)); break; case MODEL: setStart(Vec3d(x,y,0.)); setDirection(Vec3d(0.,0.,1.)); break; } } Intersector* RayIntersector::clone(IntersectionVisitor& iv) { if (_coordinateFrame==MODEL && iv.getModelMatrix()==0) { return new RayIntersector(MODEL, _start, _direction, this, _intersectionLimit); } Matrix matrix(LineSegmentIntersector::getTransformation(iv, _coordinateFrame)); Vec3d newStart = _start * matrix; Vec4d tmp = Vec4d(_start + _direction, 1.) * matrix; Vec3d newEnd = Vec3d(tmp.x(), tmp.y(), tmp.z()) - (newStart * tmp.w()); return new RayIntersector(MODEL, newStart, newEnd, this, _intersectionLimit); } bool RayIntersector::enter(const Node& node) { if (reachedLimit()) return false; return !node.isCullingActive() || intersects( node.getBound() ); } void RayIntersector::leave() { // do nothing } void RayIntersector::reset() { Intersector::reset(); _intersections.clear(); } void RayIntersector::intersect(IntersectionVisitor& iv, Drawable* drawable) { // did we reached what we wanted as specified by setIntersectionLimit()? if (reachedLimit()) return; // clip ray to finite line segment Vec3d s(_start), e; if (!intersectAndClip(s, _direction, e, drawable->getBound())) return; // dummy traversal if (iv.getDoDummyTraversal()) return; // get intersections using LineSegmentIntersector LineSegmentIntersector lsi(MODEL, s, e, NULL, _intersectionLimit); lsi.setPrecisionHint(getPrecisionHint()); lsi.intersect(iv, drawable, s, e); // copy intersections from LineSegmentIntersector LineSegmentIntersector::Intersections intersections = lsi.getIntersections(); if (!intersections.empty()) { double preLength = (s - _start).length(); double esLength = (e - s).length(); for(LineSegmentIntersector::Intersections::iterator it = intersections.begin(); it != intersections.end(); it++) { Intersection hit; hit.distance = preLength + it->ratio * esLength; hit.matrix = it->matrix; hit.nodePath = it->nodePath; hit.drawable = it->drawable; hit.primitiveIndex = it->primitiveIndex; hit.localIntersectionPoint = it->localIntersectionPoint; hit.localIntersectionNormal = it->localIntersectionNormal; hit.indexList = it->indexList; hit.ratioList = it->ratioList; insertIntersection(hit); } } } bool RayIntersector::intersects(const BoundingSphere& bs) { // if bs not valid then return true based on the assumption that an invalid sphere is yet to be defined. if (!bs.valid()) return true; // test for _start inside the bounding sphere Vec3d sm = _start - bs._center; double c = sm.length2() - bs._radius * bs._radius; if (c<0.0) return true; // solve quadratic equation double a = _direction.length2(); double b = (sm * _direction) * 2.0; double d = b * b - 4.0 * a * c; // no intersections if d<0 if (d<0.0) return false; // compute two solutions of quadratic equation d = sqrt(d); double div = 1.0/(2.0*a); double r1 = (-b-d)*div; double r2 = (-b+d)*div; // return false if both intersections are before the ray start if (r1<=0.0 && r2<=0.0) return false; // if LIMIT_NEAREST and closest point of bounding sphere is further than already found intersection, return false if (_intersectionLimit == LIMIT_NEAREST && !getIntersections().empty()) { double minDistance = sm.length() - bs._radius; if (minDistance >= getIntersections().begin()->distance) return false; } // passed all the rejection tests so line must intersect bounding sphere, return true. return true; } bool RayIntersector::intersectAndClip(Vec3d& s, const Vec3d& d, Vec3d& e, const BoundingBox& bbInput) { // bounding box min and max Vec3d bb_min(bbInput._min); Vec3d bb_max(bbInput._max); // Expand the extents of the bounding box by the epsilon to prevent numerical errors resulting in misses. const double epsilon = 1e-6; // clip s against all three components of the Min to Max range of bb for (int i=0; i<3; i++) { // test direction if (d[i] >= 0.) { // trivial reject of segment wholly outside if (s[i] > bb_max[i]) return false; if (s[i] < bb_min[i]) { // clip s to xMin double t = (bb_min[i]-s[i])/d[i] - epsilon; if (t>0.0) s = s + d*t; } } else { // trivial reject of segment wholly outside if (s[i] < bb_min[i]) return false; if (s[i] > bb_max[i]) { // clip s to xMax double t = (bb_max[i]-s[i])/d[i] - epsilon; if (t>0.0) s = s + d*t; } } } // t for ending point of clipped ray double end_t = std::numeric_limits<double>::infinity(); // get end point by clipping the ray by bb // note: this can not be done in previous loop as start point s is moving for (int i=0; i<3; i++) { // test direction if (d[i] >= 0.) { // compute end_t based on xMax double t = (bb_max[i]-s[i])/d[i] + epsilon; if (t < end_t) end_t = t; } else { // compute end_t based on xMin double t = (bb_min[i]-s[i])/d[i] + epsilon; if (t < end_t) end_t = t; } } // compute e e = s + d*end_t; return true; } Texture* RayIntersector::Intersection::getTextureLookUp(Vec3& tc) const { Geometry* geometry = drawable.valid() ? drawable->asGeometry() : 0; Vec3Array* vertices = geometry ? dynamic_cast<Vec3Array*>(geometry->getVertexArray()) : 0; if (vertices) { if (indexList.size()==3 && ratioList.size()==3) { unsigned int i1 = indexList[0]; unsigned int i2 = indexList[1]; unsigned int i3 = indexList[2]; float r1 = ratioList[0]; float r2 = ratioList[1]; float r3 = ratioList[2]; Array* texcoords = (geometry->getNumTexCoordArrays()>0) ? geometry->getTexCoordArray(0) : 0; FloatArray* texcoords_FloatArray = dynamic_cast<FloatArray*>(texcoords); Vec2Array* texcoords_Vec2Array = dynamic_cast<Vec2Array*>(texcoords); Vec3Array* texcoords_Vec3Array = dynamic_cast<Vec3Array*>(texcoords); if (texcoords_FloatArray) { // we have tex coord array so now we can compute the final tex coord at the point of intersection. float tc1 = (*texcoords_FloatArray)[i1]; float tc2 = (*texcoords_FloatArray)[i2]; float tc3 = (*texcoords_FloatArray)[i3]; tc.x() = tc1*r1 + tc2*r2 + tc3*r3; } else if (texcoords_Vec2Array) { // we have tex coord array so now we can compute the final tex coord at the point of intersection. const Vec2& tc1 = (*texcoords_Vec2Array)[i1]; const Vec2& tc2 = (*texcoords_Vec2Array)[i2]; const Vec2& tc3 = (*texcoords_Vec2Array)[i3]; tc.x() = tc1.x()*r1 + tc2.x()*r2 + tc3.x()*r3; tc.y() = tc1.y()*r1 + tc2.y()*r2 + tc3.y()*r3; } else if (texcoords_Vec3Array) { // we have tex coord array so now we can compute the final tex coord at the point of intersection. const Vec3& tc1 = (*texcoords_Vec3Array)[i1]; const Vec3& tc2 = (*texcoords_Vec3Array)[i2]; const Vec3& tc3 = (*texcoords_Vec3Array)[i3]; tc.x() = tc1.x()*r1 + tc2.x()*r2 + tc3.x()*r3; tc.y() = tc1.y()*r1 + tc2.y()*r2 + tc3.y()*r3; tc.z() = tc1.z()*r1 + tc2.z()*r2 + tc3.z()*r3; } else { return 0; } } const TexMat* activeTexMat = 0; const Texture* activeTexture = 0; if (drawable->getStateSet()) { const TexMat* texMat = dynamic_cast<TexMat*>(drawable->getStateSet()->getTextureAttribute(0,StateAttribute::TEXMAT)); if (texMat) activeTexMat = texMat; const Texture* texture = dynamic_cast<Texture*>(drawable->getStateSet()->getTextureAttribute(0,StateAttribute::TEXTURE)); if (texture) activeTexture = texture; } for(NodePath::const_reverse_iterator itr = nodePath.rbegin(); itr != nodePath.rend() && (!activeTexMat || !activeTexture); ++itr) { const Node* node = *itr; if (node->getStateSet()) { if (!activeTexMat) { const TexMat* texMat = dynamic_cast<const TexMat*>(node->getStateSet()->getTextureAttribute(0,StateAttribute::TEXMAT)); if (texMat) activeTexMat = texMat; } if (!activeTexture) { const Texture* texture = dynamic_cast<const Texture*>(node->getStateSet()->getTextureAttribute(0,StateAttribute::TEXTURE)); if (texture) activeTexture = texture; } } } if (activeTexMat) { Vec4 tc_transformed = Vec4(tc.x(), tc.y(), tc.z() ,0.0f) * activeTexMat->getMatrix(); tc.x() = tc_transformed.x(); tc.y() = tc_transformed.y(); tc.z() = tc_transformed.z(); if (activeTexture && activeTexMat->getScaleByTextureRectangleSize()) { tc.x() *= static_cast<float>(activeTexture->getTextureWidth()); tc.y() *= static_cast<float>(activeTexture->getTextureHeight()); tc.z() *= static_cast<float>(activeTexture->getTextureDepth()); } } return const_cast<Texture*>(activeTexture); } return 0; } <commit_msg>From Bjorn Hein, "please find attached a small fix for RayIntersector.cpp.<commit_after>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield * * This library is open source and may be redistributed and/or modified under * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or * (at your option) any later version. The full license is in LICENSE file * included with this distribution, and on the openscenegraph.org website. * * 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 * OpenSceneGraph Public License for more details. */ #include <osgUtil/RayIntersector> #include <osgUtil/LineSegmentIntersector> #include <osg/KdTree> #include <osg/Notify> #include <osg/TexMat> #include <limits> #include <cmath> using namespace osg; using namespace osgUtil; /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // RayIntersector // RayIntersector::RayIntersector(CoordinateFrame cf, RayIntersector* parent, Intersector::IntersectionLimit intersectionLimit) : Intersector(cf, intersectionLimit), _parent(parent) { if (parent) setPrecisionHint(parent->getPrecisionHint()); } RayIntersector::RayIntersector(const Vec3d& start, const Vec3d& direction) : Intersector(), _parent(0), _start(start), _direction(direction) { } RayIntersector::RayIntersector(CoordinateFrame cf, const Vec3d& start, const Vec3d& direction, RayIntersector* parent, Intersector::IntersectionLimit intersectionLimit) : Intersector(cf, intersectionLimit), _parent(parent), _start(start), _direction(direction) { if (parent) setPrecisionHint(parent->getPrecisionHint()); } RayIntersector::RayIntersector(CoordinateFrame cf, double x, double y) : Intersector(cf), _parent(0) { switch(cf) { case WINDOW: setStart(Vec3d(x,y,0.)); setDirection(Vec3d(0.,0.,1.)); break; case PROJECTION: setStart(Vec3d(x,y,-1.)); setDirection(Vec3d(0.,0.,1.)); break; case VIEW: setStart(Vec3d(x,y,0.)); setDirection(Vec3d(0.,0.,1.)); break; case MODEL: setStart(Vec3d(x,y,0.)); setDirection(Vec3d(0.,0.,1.)); break; } } Intersector* RayIntersector::clone(IntersectionVisitor& iv) { if (_coordinateFrame==MODEL && iv.getModelMatrix()==0) { return new RayIntersector(MODEL, _start, _direction, this, _intersectionLimit); } Matrix matrix(LineSegmentIntersector::getTransformation(iv, _coordinateFrame)); Vec3d newStart = _start * matrix; Vec4d tmp = Vec4d(_start + _direction, 1.) * matrix; Vec3d newEnd = Vec3d(tmp.x(), tmp.y(), tmp.z()) - (newStart * tmp.w()); return new RayIntersector(MODEL, newStart, newEnd, this, _intersectionLimit); } bool RayIntersector::enter(const Node& node) { if (reachedLimit()) return false; return !node.isCullingActive() || intersects( node.getBound() ); } void RayIntersector::leave() { // do nothing } void RayIntersector::reset() { Intersector::reset(); _intersections.clear(); } void RayIntersector::intersect(IntersectionVisitor& iv, Drawable* drawable) { // did we reached what we wanted as specified by setIntersectionLimit()? if (reachedLimit()) return; // clip ray to finite line segment Vec3d s(_start), e; if (!intersectAndClip(s, _direction, e, drawable->getBound())) return; // dummy traversal if (iv.getDoDummyTraversal()) return; // get intersections using LineSegmentIntersector LineSegmentIntersector lsi(MODEL, s, e, NULL, _intersectionLimit); lsi.setPrecisionHint(getPrecisionHint()); lsi.intersect(iv, drawable, s, e); // copy intersections from LineSegmentIntersector LineSegmentIntersector::Intersections intersections = lsi.getIntersections(); if (!intersections.empty()) { double preLength = (s - _start).length(); double esLength = (e - s).length(); for(LineSegmentIntersector::Intersections::iterator it = intersections.begin(); it != intersections.end(); it++) { Intersection hit; hit.distance = preLength + it->ratio * esLength; hit.matrix = it->matrix; hit.nodePath = it->nodePath; hit.drawable = it->drawable; hit.primitiveIndex = it->primitiveIndex; hit.localIntersectionPoint = it->localIntersectionPoint; hit.localIntersectionNormal = it->localIntersectionNormal; hit.indexList = it->indexList; hit.ratioList = it->ratioList; insertIntersection(hit); } } } bool RayIntersector::intersects(const BoundingSphere& bs) { // if bs not valid then return true based on the assumption that an invalid sphere is yet to be defined. if (!bs.valid()) return true; // test for _start inside the bounding sphere Vec3d sm = _start - bs._center; double c = sm.length2() - bs._radius * bs._radius; if (c<0.0) return true; // solve quadratic equation double a = _direction.length2(); double b = (sm * _direction) * 2.0; double d = b * b - 4.0 * a * c; // no intersections if d<0 if (d<0.0) return false; // compute two solutions of quadratic equation d = sqrt(d); double div = 1.0/(2.0*a); double r1 = (-b-d)*div; double r2 = (-b+d)*div; // return false if both intersections are before the ray start if (r1<=0.0 && r2<=0.0) return false; // if LIMIT_NEAREST and closest point of bounding sphere is further than already found intersection, return false if (_intersectionLimit == LIMIT_NEAREST && !getIntersections().empty()) { double minDistance = sm.length() - bs._radius; if (minDistance >= getIntersections().begin()->distance) return false; } // passed all the rejection tests so line must intersect bounding sphere, return true. return true; } bool RayIntersector::intersectAndClip(Vec3d& s, const Vec3d& d, Vec3d& e, const BoundingBox& bbInput) { // bounding box min and max Vec3d bb_min(bbInput._min); Vec3d bb_max(bbInput._max); // Expand the extents of the bounding box by the epsilon to prevent numerical errors resulting in misses. const double epsilon = 1e-6; // clip s against all three components of the Min to Max range of bb for (int i=0; i<3; i++) { // test direction if (d[i] >= 0.) { // trivial reject of segment wholly outside if (s[i] > bb_max[i]) return false; if (s[i] < bb_min[i]) { // clip s to xMin double t = (bb_min[i]-s[i])/d[i] - epsilon; if (t>0.0) s = s + d*t; } } else { // trivial reject of segment wholly outside if (s[i] < bb_min[i]) return false; if (s[i] > bb_max[i]) { // clip s to xMax double t = (bb_max[i]-s[i])/d[i] - epsilon; if (t>0.0) s = s + d*t; } } } // t for ending point of clipped ray double end_t = std::numeric_limits<double>::infinity(); // get end point by clipping the ray by bb // note: this can not be done in previous loop as start point s is moving for (int i=0; i<3; i++) { // test direction if (d[i] >= 0.) { // compute end_t based on xMax double t = (bb_max[i]-s[i])/d[i] + epsilon; if (t < end_t) end_t = t; } else { // compute end_t based on xMin double t = (bb_min[i]-s[i])/d[i] + epsilon; if (t < end_t) end_t = t; } } // compute e e = s + d*end_t; return true; } Texture* RayIntersector::Intersection::getTextureLookUp(Vec3& tc) const { Geometry* geometry = drawable.valid() ? drawable->asGeometry() : 0; Vec3Array* vertices = geometry ? dynamic_cast<Vec3Array*>(geometry->getVertexArray()) : 0; if (vertices) { if (indexList.size()==3 && ratioList.size()==3) { unsigned int i1 = indexList[0]; unsigned int i2 = indexList[1]; unsigned int i3 = indexList[2]; float r1 = ratioList[0]; float r2 = ratioList[1]; float r3 = ratioList[2]; Array* texcoords = (geometry->getNumTexCoordArrays()>0) ? geometry->getTexCoordArray(0) : 0; FloatArray* texcoords_FloatArray = dynamic_cast<FloatArray*>(texcoords); Vec2Array* texcoords_Vec2Array = dynamic_cast<Vec2Array*>(texcoords); Vec3Array* texcoords_Vec3Array = dynamic_cast<Vec3Array*>(texcoords); if (texcoords_FloatArray) { // we have tex coord array so now we can compute the final tex coord at the point of intersection. float tc1 = (*texcoords_FloatArray)[i1]; float tc2 = (*texcoords_FloatArray)[i2]; float tc3 = (*texcoords_FloatArray)[i3]; tc.x() = tc1*r1 + tc2*r2 + tc3*r3; } else if (texcoords_Vec2Array) { // we have tex coord array so now we can compute the final tex coord at the point of intersection. const Vec2& tc1 = (*texcoords_Vec2Array)[i1]; const Vec2& tc2 = (*texcoords_Vec2Array)[i2]; const Vec2& tc3 = (*texcoords_Vec2Array)[i3]; tc.x() = tc1.x()*r1 + tc2.x()*r2 + tc3.x()*r3; tc.y() = tc1.y()*r1 + tc2.y()*r2 + tc3.y()*r3; } else if (texcoords_Vec3Array) { // we have tex coord array so now we can compute the final tex coord at the point of intersection. const Vec3& tc1 = (*texcoords_Vec3Array)[i1]; const Vec3& tc2 = (*texcoords_Vec3Array)[i2]; const Vec3& tc3 = (*texcoords_Vec3Array)[i3]; tc.x() = tc1.x()*r1 + tc2.x()*r2 + tc3.x()*r3; tc.y() = tc1.y()*r1 + tc2.y()*r2 + tc3.y()*r3; tc.z() = tc1.z()*r1 + tc2.z()*r2 + tc3.z()*r3; } else { return 0; } } const TexMat* activeTexMat = 0; const Texture* activeTexture = 0; if (drawable->getStateSet()) { const TexMat* texMat = dynamic_cast<TexMat*>(drawable->getStateSet()->getTextureAttribute(0,StateAttribute::TEXMAT)); if (texMat) activeTexMat = texMat; const Texture* texture = dynamic_cast<Texture*>(drawable->getStateSet()->getTextureAttribute(0,StateAttribute::TEXTURE)); if (texture) activeTexture = texture; } for(NodePath::const_reverse_iterator itr = nodePath.rbegin(); itr != nodePath.rend() && (!activeTexMat || !activeTexture); ++itr) { const Node* node = *itr; if (node->getStateSet()) { if (!activeTexMat) { const TexMat* texMat = dynamic_cast<const TexMat*>(node->getStateSet()->getTextureAttribute(0,StateAttribute::TEXMAT)); if (texMat) activeTexMat = texMat; } if (!activeTexture) { const Texture* texture = dynamic_cast<const Texture*>(node->getStateSet()->getTextureAttribute(0,StateAttribute::TEXTURE)); if (texture) activeTexture = texture; } } } if (activeTexMat) { Vec4 tc_transformed = Vec4(tc.x(), tc.y(), tc.z() ,0.0f) * activeTexMat->getMatrix(); tc.x() = tc_transformed.x(); tc.y() = tc_transformed.y(); tc.z() = tc_transformed.z(); if (activeTexture && activeTexMat->getScaleByTextureRectangleSize()) { tc.x() *= static_cast<float>(activeTexture->getTextureWidth()); tc.y() *= static_cast<float>(activeTexture->getTextureHeight()); tc.z() *= static_cast<float>(activeTexture->getTextureDepth()); } } return const_cast<Texture*>(activeTexture); } return 0; } <|endoftext|>
<commit_before>/** * @file * @copyright defined in eos/LICENSE.txt */ #include <eosio/chain/block_log.hpp> #include <fstream> #include <fc/io/raw.hpp> #define LOG_READ (std::ios::in | std::ios::binary) #define LOG_WRITE (std::ios::out | std::ios::binary | std::ios::app) namespace eosio { namespace chain { namespace detail { class block_log_impl { public: signed_block_ptr head; block_id_type head_id; std::fstream block_stream; std::fstream index_stream; fc::path block_file; fc::path index_file; bool block_write; bool index_write; inline void check_block_read() { if (block_write) { block_stream.close(); block_stream.open(block_file.generic_string().c_str(), LOG_READ); block_write = false; } } inline void check_block_write() { if (!block_write) { block_stream.close(); block_stream.open(block_file.generic_string().c_str(), LOG_WRITE); block_write = true; } } inline void check_index_read() { try { if (index_write) { index_stream.close(); index_stream.open(index_file.generic_string().c_str(), LOG_READ); index_write = false; } } FC_LOG_AND_RETHROW() } inline void check_index_write() { if (!index_write) { index_stream.close(); index_stream.open(index_file.generic_string().c_str(), LOG_WRITE); index_write = true; } } }; } block_log::block_log(const fc::path& data_dir) :my(new detail::block_log_impl()) { my->block_stream.exceptions(std::fstream::failbit | std::fstream::badbit); my->index_stream.exceptions(std::fstream::failbit | std::fstream::badbit); open(data_dir); } block_log::block_log(block_log&& other) { my = std::move(other.my); } block_log::~block_log() { if (my) { flush(); my.reset(); } } void block_log::open(const fc::path& data_dir) { if (my->block_stream.is_open()) my->block_stream.close(); if (my->index_stream.is_open()) my->index_stream.close(); if (!fc::is_directory(data_dir)) fc::create_directories(data_dir); my->block_file = data_dir / "blocks.log"; my->index_file = data_dir / "blocks.index"; //ilog("Opening block log at ${path}", ("path", my->block_file.generic_string())); my->block_stream.open(my->block_file.generic_string().c_str(), LOG_WRITE); my->index_stream.open(my->index_file.generic_string().c_str(), LOG_WRITE); my->block_write = true; my->index_write = true; /* On startup of the block log, there are several states the log file and the index file can be * in relation to each other. * * Block Log * Exists Is New * +------------+------------+ * Exists | Check | Delete | * Index | Head | Index | * File +------------+------------+ * Is New | Replay | Do | * | Log | Nothing | * +------------+------------+ * * Checking the heads of the files has several conditions as well. * - If they are the same, do nothing. * - If the index file head is not in the log file, delete the index and replay. * - If the index file head is in the log, but not up to date, replay from index head. */ auto log_size = fc::file_size(my->block_file); auto index_size = fc::file_size(my->index_file); if (log_size) { ilog("Log is nonempty"); my->head = read_head(); my->head_id = my->head->id(); edump((my->head->block_num())); if (index_size) { my->check_block_read(); my->check_index_read(); ilog("Index is nonempty"); uint64_t block_pos; my->block_stream.seekg(-sizeof(uint64_t), std::ios::end); my->block_stream.read((char*)&block_pos, sizeof(block_pos)); uint64_t index_pos; my->index_stream.seekg(-sizeof(uint64_t), std::ios::end); my->index_stream.read((char*)&index_pos, sizeof(index_pos)); if (block_pos < index_pos) { ilog("block_pos < index_pos, close and reopen index_stream"); construct_index(); } else if (block_pos > index_pos) { ilog("Index is incomplete"); construct_index(); } } else { ilog("Index is empty"); construct_index(); } } else if (index_size) { ilog("Index is nonempty, remove and recreate it"); my->index_stream.close(); fc::remove_all(my->index_file); my->index_stream.open(my->index_file.generic_string().c_str(), LOG_WRITE); my->index_write = true; } } uint64_t block_log::append(const signed_block_ptr& b) { try { my->check_block_write(); my->check_index_write(); uint64_t pos = my->block_stream.tellp(); FC_ASSERT(my->index_stream.tellp() == sizeof(uint64_t) * (b->block_num() - 1), "Append to index file occuring at wrong position.", ("position", (uint64_t) my->index_stream.tellp()) ("expected", (b->block_num() - 1) * sizeof(uint64_t))); auto data = fc::raw::pack(*b); my->block_stream.write(data.data(), data.size()); my->block_stream.write((char*)&pos, sizeof(pos)); my->index_stream.write((char*)&pos, sizeof(pos)); my->head = b; my->head_id = b->id(); flush(); return pos; } FC_LOG_AND_RETHROW() } void block_log::flush() { my->block_stream.flush(); my->index_stream.flush(); } std::pair<signed_block_ptr, uint64_t> block_log::read_block(uint64_t pos)const { my->check_block_read(); my->block_stream.seekg(pos); std::pair<signed_block_ptr,uint64_t> result; result.first = std::make_shared<signed_block>(); fc::raw::unpack(my->block_stream, *result.first); result.second = uint64_t(my->block_stream.tellg()) + 8; return result; } signed_block_ptr block_log::read_block_by_num(uint32_t block_num)const { try { signed_block_ptr b; uint64_t pos = get_block_pos(block_num); if (pos != npos) { b = read_block(pos).first; FC_ASSERT(b->block_num() == block_num, "Wrong block was read from block log.", ("returned", b->block_num())("expected", block_num)); } return b; } FC_LOG_AND_RETHROW() } uint64_t block_log::get_block_pos(uint32_t block_num) const { my->check_index_read(); if (!(my->head && block_num <= block_header::num_from_id(my->head_id) && block_num > 0)) return npos; my->index_stream.seekg(sizeof(uint64_t) * (block_num - 1)); uint64_t pos; my->index_stream.read((char*)&pos, sizeof(pos)); return pos; } signed_block_ptr block_log::read_head()const { my->check_block_read(); uint64_t pos; // Check that the file is not empty my->block_stream.seekg(0, std::ios::end); if (my->block_stream.tellg() <= sizeof(pos)) return {}; my->block_stream.seekg(-sizeof(pos), std::ios::end); my->block_stream.read((char*)&pos, sizeof(pos)); return read_block(pos).first; } const signed_block_ptr& block_log::head()const { return my->head; } void block_log::construct_index() { ilog("Reconstructing Block Log Index..."); my->index_stream.close(); fc::remove_all(my->index_file); my->index_stream.open(my->index_file.generic_string().c_str(), LOG_WRITE); my->index_write = true; uint64_t pos = 0; uint64_t end_pos; my->check_block_read(); my->block_stream.seekg(-sizeof( uint64_t), std::ios::end); my->block_stream.read((char*)&end_pos, sizeof(end_pos)); signed_block tmp; my->block_stream.seekg(pos); while( pos < end_pos ) { fc::raw::unpack(my->block_stream, tmp); my->block_stream.read((char*)&pos, sizeof(pos)); my->index_stream.write((char*)&pos, sizeof(pos)); } } // construct_index fc::path block_log::repair_log( const fc::path& data_dir ) { ilog("Recovering Block Log..."); FC_ASSERT( fc::is_directory(data_dir) && fc::is_regular_file(data_dir / "blocks.log"), "Block log not found in '${blocks_dir}'", ("blocks_dir", data_dir) ); auto now = fc::time_point::now(); auto blocks_dir = fc::canonical( data_dir ); if( blocks_dir.filename().generic_string() == "." ) { blocks_dir = blocks_dir.parent_path(); } auto backup_dir = blocks_dir.parent_path(); auto blocks_dir_name = blocks_dir.filename(); FC_ASSERT( blocks_dir_name.generic_string() != ".", "Invalid path to blocks directory" ); backup_dir = backup_dir / blocks_dir_name.generic_string().append("-").append( now ); FC_ASSERT( !fc::exists(backup_dir), "Cannot move existing blocks directory to already existing directory '${new_blocks_dir}'", ("new_blocks_dir", backup_dir) ); fc::rename( blocks_dir, backup_dir ); ilog( "Moved existing blocks directory to backup location: '${new_blocks_dir}'", ("new_blocks_dir", backup_dir) ); fc::create_directories(blocks_dir); auto block_log_path = blocks_dir / "blocks.log"; ilog( "Reconstructing '${new_block_log}' from backed up block log", ("new_block_log", block_log_path) ); std::fstream old_block_stream; std::fstream new_block_stream; old_block_stream.open( (backup_dir / "blocks.log").generic_string().c_str(), LOG_READ ); new_block_stream.open( block_log_path.generic_string().c_str(), LOG_WRITE ); uint64_t pos = 0; uint64_t end_pos = old_block_stream.tellg(); old_block_stream.seekg( 0, std::ios::end ); end_pos = static_cast<uint64_t>(old_block_stream.tellg()) - end_pos; old_block_stream.seekg( 0 ); std::exception_ptr except_ptr; vector<char> incomplete_block_data; optional<signed_block> bad_block; uint32_t block_num = 0; while( pos < end_pos ) { signed_block tmp; try { fc::raw::unpack(old_block_stream, tmp); } catch( ... ) { except_ptr = std::current_exception(); incomplete_block_data.resize( end_pos - pos ); old_block_stream.read( incomplete_block_data.data(), incomplete_block_data.size() ); break; } uint64_t tmp_pos = std::numeric_limits<uint64_t>::max(); if( (static_cast<uint64_t>(old_block_stream.tellg()) + sizeof(pos)) <= end_pos ) { old_block_stream.read( reinterpret_cast<char*>(&tmp_pos), sizeof(tmp_pos) ); } if( pos != tmp_pos ) { bad_block = tmp; break; } auto data = fc::raw::pack(tmp); new_block_stream.write( data.data(), data.size() ); new_block_stream.write( reinterpret_cast<char*>(&pos), sizeof(pos) ); block_num = tmp.block_num(); pos = new_block_stream.tellp(); } if( bad_block.valid() ) { ilog( "Recovered only up to block number ${num}. Last block in block log was not properly committed:\n${last_block}", ("num", block_num)("last_block", *bad_block) ); } else if( except_ptr ) { std::string error_msg; try { std::rethrow_exception(except_ptr); } catch( const fc::exception& e ) { error_msg = e.what(); } catch( const std::exception& e ) { error_msg = e.what(); } catch( ... ) { error_msg = "unrecognized exception"; } ilog( "Recovered only up to block number ${num}. " "The block ${next_num} could not be deserialized from the block log due to error:\n${error_msg}", ("num", block_num)("next_num", block_num+1)("error_msg", error_msg) ); auto tail_path = blocks_dir / std::string("blocks-bad-tail-").append( now ).append(".log"); if( !fc::exists(tail_path) && incomplete_block_data.size() > 0 ) { std::fstream tail_stream; tail_stream.open( tail_path.generic_string().c_str(), LOG_WRITE ); tail_stream.write( incomplete_block_data.data(), incomplete_block_data.size() ); ilog( "Data at tail end of block log which should contain the (incomplete) serialization of block ${num} " "has been written out to '${tail_path}'.", ("num", block_num+1)("tail_path", tail_path) ); } } else { ilog( "Existing block log was undamaged. Recovered all irreversible blocks up to block number ${num}.", ("num", block_num) ); } return backup_dir; } } } /// eosio::chain <commit_msg>add warnings in case block log is corrupted<commit_after>/** * @file * @copyright defined in eos/LICENSE.txt */ #include <eosio/chain/block_log.hpp> #include <fstream> #include <fc/io/raw.hpp> #define LOG_READ (std::ios::in | std::ios::binary) #define LOG_WRITE (std::ios::out | std::ios::binary | std::ios::app) namespace eosio { namespace chain { namespace detail { class block_log_impl { public: signed_block_ptr head; block_id_type head_id; std::fstream block_stream; std::fstream index_stream; fc::path block_file; fc::path index_file; bool block_write; bool index_write; inline void check_block_read() { if (block_write) { block_stream.close(); block_stream.open(block_file.generic_string().c_str(), LOG_READ); block_write = false; } } inline void check_block_write() { if (!block_write) { block_stream.close(); block_stream.open(block_file.generic_string().c_str(), LOG_WRITE); block_write = true; } } inline void check_index_read() { try { if (index_write) { index_stream.close(); index_stream.open(index_file.generic_string().c_str(), LOG_READ); index_write = false; } } FC_LOG_AND_RETHROW() } inline void check_index_write() { if (!index_write) { index_stream.close(); index_stream.open(index_file.generic_string().c_str(), LOG_WRITE); index_write = true; } } }; } block_log::block_log(const fc::path& data_dir) :my(new detail::block_log_impl()) { my->block_stream.exceptions(std::fstream::failbit | std::fstream::badbit); my->index_stream.exceptions(std::fstream::failbit | std::fstream::badbit); open(data_dir); } block_log::block_log(block_log&& other) { my = std::move(other.my); } block_log::~block_log() { if (my) { flush(); my.reset(); } } void block_log::open(const fc::path& data_dir) { if (my->block_stream.is_open()) my->block_stream.close(); if (my->index_stream.is_open()) my->index_stream.close(); if (!fc::is_directory(data_dir)) fc::create_directories(data_dir); my->block_file = data_dir / "blocks.log"; my->index_file = data_dir / "blocks.index"; //ilog("Opening block log at ${path}", ("path", my->block_file.generic_string())); my->block_stream.open(my->block_file.generic_string().c_str(), LOG_WRITE); my->index_stream.open(my->index_file.generic_string().c_str(), LOG_WRITE); my->block_write = true; my->index_write = true; /* On startup of the block log, there are several states the log file and the index file can be * in relation to each other. * * Block Log * Exists Is New * +------------+------------+ * Exists | Check | Delete | * Index | Head | Index | * File +------------+------------+ * Is New | Replay | Do | * | Log | Nothing | * +------------+------------+ * * Checking the heads of the files has several conditions as well. * - If they are the same, do nothing. * - If the index file head is not in the log file, delete the index and replay. * - If the index file head is in the log, but not up to date, replay from index head. */ auto log_size = fc::file_size(my->block_file); auto index_size = fc::file_size(my->index_file); if (log_size) { ilog("Log is nonempty"); my->head = read_head(); my->head_id = my->head->id(); edump((my->head->block_num())); if (index_size) { my->check_block_read(); my->check_index_read(); ilog("Index is nonempty"); uint64_t block_pos; my->block_stream.seekg(-sizeof(uint64_t), std::ios::end); my->block_stream.read((char*)&block_pos, sizeof(block_pos)); uint64_t index_pos; my->index_stream.seekg(-sizeof(uint64_t), std::ios::end); my->index_stream.read((char*)&index_pos, sizeof(index_pos)); if (block_pos < index_pos) { ilog("block_pos < index_pos, close and reopen index_stream"); construct_index(); } else if (block_pos > index_pos) { ilog("Index is incomplete"); construct_index(); } } else { ilog("Index is empty"); construct_index(); } } else if (index_size) { ilog("Index is nonempty, remove and recreate it"); my->index_stream.close(); fc::remove_all(my->index_file); my->index_stream.open(my->index_file.generic_string().c_str(), LOG_WRITE); my->index_write = true; } } uint64_t block_log::append(const signed_block_ptr& b) { try { my->check_block_write(); my->check_index_write(); uint64_t pos = my->block_stream.tellp(); FC_ASSERT(my->index_stream.tellp() == sizeof(uint64_t) * (b->block_num() - 1), "Append to index file occuring at wrong position.", ("position", (uint64_t) my->index_stream.tellp()) ("expected", (b->block_num() - 1) * sizeof(uint64_t))); auto data = fc::raw::pack(*b); my->block_stream.write(data.data(), data.size()); my->block_stream.write((char*)&pos, sizeof(pos)); my->index_stream.write((char*)&pos, sizeof(pos)); my->head = b; my->head_id = b->id(); flush(); return pos; } FC_LOG_AND_RETHROW() } void block_log::flush() { my->block_stream.flush(); my->index_stream.flush(); } std::pair<signed_block_ptr, uint64_t> block_log::read_block(uint64_t pos)const { my->check_block_read(); my->block_stream.seekg(pos); std::pair<signed_block_ptr,uint64_t> result; result.first = std::make_shared<signed_block>(); fc::raw::unpack(my->block_stream, *result.first); result.second = uint64_t(my->block_stream.tellg()) + 8; return result; } signed_block_ptr block_log::read_block_by_num(uint32_t block_num)const { try { signed_block_ptr b; uint64_t pos = get_block_pos(block_num); if (pos != npos) { b = read_block(pos).first; FC_ASSERT(b->block_num() == block_num, "Wrong block was read from block log.", ("returned", b->block_num())("expected", block_num)); } return b; } FC_LOG_AND_RETHROW() } uint64_t block_log::get_block_pos(uint32_t block_num) const { my->check_index_read(); if (!(my->head && block_num <= block_header::num_from_id(my->head_id) && block_num > 0)) return npos; my->index_stream.seekg(sizeof(uint64_t) * (block_num - 1)); uint64_t pos; my->index_stream.read((char*)&pos, sizeof(pos)); return pos; } signed_block_ptr block_log::read_head()const { my->check_block_read(); uint64_t pos; // Check that the file is not empty my->block_stream.seekg(0, std::ios::end); if (my->block_stream.tellg() <= sizeof(pos)) return {}; my->block_stream.seekg(-sizeof(pos), std::ios::end); my->block_stream.read((char*)&pos, sizeof(pos)); return read_block(pos).first; } const signed_block_ptr& block_log::head()const { return my->head; } void block_log::construct_index() { ilog("Reconstructing Block Log Index..."); my->index_stream.close(); fc::remove_all(my->index_file); my->index_stream.open(my->index_file.generic_string().c_str(), LOG_WRITE); my->index_write = true; uint64_t pos = 0; uint64_t end_pos; my->check_block_read(); my->block_stream.seekg(-sizeof( uint64_t), std::ios::end); my->block_stream.read((char*)&end_pos, sizeof(end_pos)); signed_block tmp; my->block_stream.seekg(pos); while( pos < end_pos ) { fc::raw::unpack(my->block_stream, tmp); my->block_stream.read((char*)&pos, sizeof(pos)); my->index_stream.write((char*)&pos, sizeof(pos)); } } // construct_index fc::path block_log::repair_log( const fc::path& data_dir ) { ilog("Recovering Block Log..."); FC_ASSERT( fc::is_directory(data_dir) && fc::is_regular_file(data_dir / "blocks.log"), "Block log not found in '${blocks_dir}'", ("blocks_dir", data_dir) ); auto now = fc::time_point::now(); auto blocks_dir = fc::canonical( data_dir ); if( blocks_dir.filename().generic_string() == "." ) { blocks_dir = blocks_dir.parent_path(); } auto backup_dir = blocks_dir.parent_path(); auto blocks_dir_name = blocks_dir.filename(); FC_ASSERT( blocks_dir_name.generic_string() != ".", "Invalid path to blocks directory" ); backup_dir = backup_dir / blocks_dir_name.generic_string().append("-").append( now ); FC_ASSERT( !fc::exists(backup_dir), "Cannot move existing blocks directory to already existing directory '${new_blocks_dir}'", ("new_blocks_dir", backup_dir) ); fc::rename( blocks_dir, backup_dir ); ilog( "Moved existing blocks directory to backup location: '${new_blocks_dir}'", ("new_blocks_dir", backup_dir) ); fc::create_directories(blocks_dir); auto block_log_path = blocks_dir / "blocks.log"; ilog( "Reconstructing '${new_block_log}' from backed up block log", ("new_block_log", block_log_path) ); std::fstream old_block_stream; std::fstream new_block_stream; old_block_stream.open( (backup_dir / "blocks.log").generic_string().c_str(), LOG_READ ); new_block_stream.open( block_log_path.generic_string().c_str(), LOG_WRITE ); uint64_t pos = 0; uint64_t end_pos = old_block_stream.tellg(); old_block_stream.seekg( 0, std::ios::end ); end_pos = static_cast<uint64_t>(old_block_stream.tellg()) - end_pos; old_block_stream.seekg( 0 ); std::exception_ptr except_ptr; vector<char> incomplete_block_data; optional<signed_block> bad_block; uint32_t block_num = 0; block_id_type previous; while( pos < end_pos ) { signed_block tmp; try { fc::raw::unpack(old_block_stream, tmp); } catch( ... ) { except_ptr = std::current_exception(); incomplete_block_data.resize( end_pos - pos ); old_block_stream.read( incomplete_block_data.data(), incomplete_block_data.size() ); break; } auto id = tmp.id(); if( block_header::num_from_id(previous) + 1 != block_header::num_from_id(id) ) { elog( "Block ${num} (${id}) skips blocks. Previous block in block log is block ${prev_num} (${previous})", ("num", block_header::num_from_id(id))("id", id) ("prev_num", block_header::num_from_id(previous))("previous", previous) ); } if( previous != tmp.previous ) { elog( "Block ${num} (${id}) does not link back to previous block. " "Expected previous: ${expected}. Actual previous: ${actual}.", ("num", block_header::num_from_id(id))("id", id)("expected", previous)("actual", tmp.previous) ); } previous = id; uint64_t tmp_pos = std::numeric_limits<uint64_t>::max(); if( (static_cast<uint64_t>(old_block_stream.tellg()) + sizeof(pos)) <= end_pos ) { old_block_stream.read( reinterpret_cast<char*>(&tmp_pos), sizeof(tmp_pos) ); } if( pos != tmp_pos ) { bad_block = tmp; break; } auto data = fc::raw::pack(tmp); new_block_stream.write( data.data(), data.size() ); new_block_stream.write( reinterpret_cast<char*>(&pos), sizeof(pos) ); block_num = tmp.block_num(); pos = new_block_stream.tellp(); } if( bad_block.valid() ) { ilog( "Recovered only up to block number ${num}. Last block in block log was not properly committed:\n${last_block}", ("num", block_num)("last_block", *bad_block) ); } else if( except_ptr ) { std::string error_msg; try { std::rethrow_exception(except_ptr); } catch( const fc::exception& e ) { error_msg = e.what(); } catch( const std::exception& e ) { error_msg = e.what(); } catch( ... ) { error_msg = "unrecognized exception"; } ilog( "Recovered only up to block number ${num}. " "The block ${next_num} could not be deserialized from the block log due to error:\n${error_msg}", ("num", block_num)("next_num", block_num+1)("error_msg", error_msg) ); auto tail_path = blocks_dir / std::string("blocks-bad-tail-").append( now ).append(".log"); if( !fc::exists(tail_path) && incomplete_block_data.size() > 0 ) { std::fstream tail_stream; tail_stream.open( tail_path.generic_string().c_str(), LOG_WRITE ); tail_stream.write( incomplete_block_data.data(), incomplete_block_data.size() ); ilog( "Data at tail end of block log which should contain the (incomplete) serialization of block ${num} " "has been written out to '${tail_path}'.", ("num", block_num+1)("tail_path", tail_path) ); } } else { ilog( "Existing block log was undamaged. Recovered all irreversible blocks up to block number ${num}.", ("num", block_num) ); } return backup_dir; } } } /// eosio::chain <|endoftext|>
<commit_before>/* This file is part of KOrganizer. Copyright (c) 2001 Cornelius Schumacher <[email protected]> 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., 675 Mass Ave, Cambridge, MA 02139, 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 <qwidget.h> #include <klibloader.h> #include <kdebug.h> #include <kconfig.h> #include <calendar/plugin.h> #include <korganizer/part.h> #include "koprefs.h" #include "kocore.h" KOCore *KOCore::mSelf = 0; KOCore *KOCore::self() { if (!mSelf) { mSelf = new KOCore; } return mSelf; } KOCore::KOCore() : mCalendarDecorationsLoaded(false), mHolidaysLoaded(false) { KGlobal::config()->setGroup("General"); QString calSystem = KGlobal::config()->readEntry( "CalendarSystem", "gregorian" ); mCalendarSystem = KCalendarSystemFactory::create( calSystem ); } KTrader::OfferList KOCore::availablePlugins(const QString &type) { return KTrader::self()->query(type); } KOrg::Plugin *KOCore::loadPlugin(KService::Ptr service) { kdDebug() << "loadPlugin: library: " << service->library() << endl; KLibFactory *factory = KLibLoader::self()->factory(service->library()); if (!factory) { kdDebug() << "KOCore::loadPlugin(): Factory creation failed" << endl; return 0; } KOrg::PluginFactory *pluginFactory = dynamic_cast<KOrg::PluginFactory *>(factory); if (!pluginFactory) { kdDebug() << "KOCore::loadPlugin(): Cast to KOrg::PluginFactory failed" << endl; return 0; } return pluginFactory->create(); } KOrg::Plugin *KOCore::loadPlugin(const QString &name) { KTrader::OfferList list = availablePlugins("Calendar/Plugin"); KTrader::OfferList::ConstIterator it; for(it = list.begin(); it != list.end(); ++it) { if ((*it)->desktopEntryName() == name) { return loadPlugin(*it); } } return 0; } KOrg::CalendarDecoration *KOCore::loadCalendarDecoration(KService::Ptr service) { kdDebug() << "loadCalendarDecoration: library: " << service->library() << endl; KLibFactory *factory = KLibLoader::self()->factory(service->library()); if (!factory) { kdDebug() << "KOCore::loadCalendarDecoration(): Factory creation failed" << endl; return 0; } KOrg::CalendarDecorationFactory *pluginFactory = dynamic_cast<KOrg::CalendarDecorationFactory *>(factory); if (!pluginFactory) { kdDebug() << "KOCore::loadCalendarDecoration(): Cast failed" << endl; return 0; } return pluginFactory->create(); } KOrg::CalendarDecoration *KOCore::loadCalendarDecoration(const QString &name) { KTrader::OfferList list = availablePlugins("Calendar/Decoration"); KTrader::OfferList::ConstIterator it; for(it = list.begin(); it != list.end(); ++it) { if ((*it)->desktopEntryName() == name) { return loadCalendarDecoration(*it); } } return 0; } KOrg::Part *KOCore::loadPart(KService::Ptr service, KOrg::MainWindow *parent) { kdDebug() << "loadPart: library: " << service->library() << endl; KLibFactory *factory = KLibLoader::self()->factory(service->library()); if (!factory) { kdDebug() << "KOCore::loadPart(): Factory creation failed" << endl; return 0; } KOrg::PartFactory *pluginFactory = dynamic_cast<KOrg::PartFactory *>(factory); if (!pluginFactory) { kdDebug() << "KOCore::loadPart(): Cast failed" << endl; return 0; } return pluginFactory->create(parent); } KOrg::Part *KOCore::loadPart(const QString &name,KOrg::MainWindow *parent) { KTrader::OfferList list = availablePlugins("KOrg::MainWindow/Part"); KTrader::OfferList::ConstIterator it; for(it = list.begin(); it != list.end(); ++it) { if ((*it)->desktopEntryName() == name) { return loadPart(*it,parent); } } return 0; } KOrg::CalendarDecoration::List KOCore::calendarDecorations() { if (!mCalendarDecorationsLoaded) { QStringList selectedPlugins = KOPrefs::instance()->mSelectedPlugins; mCalendarDecorations.clear(); KTrader::OfferList plugins = availablePlugins("Calendar/Decoration"); KTrader::OfferList::ConstIterator it; for(it = plugins.begin(); it != plugins.end(); ++it) { if ((*it)->hasServiceType("Calendar/Decoration")) { if (selectedPlugins.find((*it)->desktopEntryName()) != selectedPlugins.end()) { mCalendarDecorations.append(loadCalendarDecoration(*it)); } } } mCalendarDecorationsLoaded = true; } return mCalendarDecorations; } KOrg::Part::List KOCore::loadParts( KOrg::MainWindow *parent ) { KOrg::Part::List parts; QStringList selectedPlugins = KOPrefs::instance()->mSelectedPlugins; KTrader::OfferList plugins = availablePlugins("KOrganizer/Part"); KTrader::OfferList::ConstIterator it; for(it = plugins.begin(); it != plugins.end(); ++it) { if (selectedPlugins.find((*it)->desktopEntryName()) != selectedPlugins.end()) { KOrg::Part *part = loadPart(*it,parent); parent->guiFactory()->addClient( part ); parts.append( part ); } } return parts; } void KOCore::unloadPlugins() { KOrg::CalendarDecoration *plugin; for( plugin=mCalendarDecorations.first(); plugin; plugin=mCalendarDecorations.next() ) { delete plugin; } mCalendarDecorations.clear(); mCalendarDecorationsLoaded = false; } void KOCore::unloadParts( KOrg::MainWindow *parent, KOrg::Part::List& parts ) { KOrg::Part *part; for( part=parts.first(); part; part=parts.next() ) { parent->guiFactory()->removeClient( part ); delete part; } parts.clear(); } KOrg::Part::List KOCore::reloadParts( KOrg::MainWindow *parent, KOrg::Part::List& parts ) { unloadParts( parent, parts ); return loadParts( parent ); } void KOCore::reloadPlugins() { mCalendarDecorationsLoaded = false; // Plugins should be unloaded, but e.g. komonthview keeps using the old ones unloadPlugins(); calendarDecorations(); } QString KOCore::holiday(const QDate &date) { if (!mHolidaysLoaded) { mHolidays = dynamic_cast<KOrg::CalendarDecoration *>(loadPlugin("holidays")); mHolidaysLoaded = true; } if (mHolidays) return mHolidays->shortText(date); else return QString::null; } KCalendarSystem* KOCore::calendarSystem() { return mCalendarSystem; } <commit_msg>dynamic_cast doesn't seem to work reliably. Replaced by static_cast and some additional checks.<commit_after>/* This file is part of KOrganizer. Copyright (c) 2001 Cornelius Schumacher <[email protected]> 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., 675 Mass Ave, Cambridge, MA 02139, 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 <qwidget.h> #include <klibloader.h> #include <kdebug.h> #include <kconfig.h> #include <calendar/plugin.h> #include <korganizer/part.h> #include "koprefs.h" #include "kocore.h" KOCore *KOCore::mSelf = 0; KOCore *KOCore::self() { if (!mSelf) { mSelf = new KOCore; } return mSelf; } KOCore::KOCore() : mCalendarDecorationsLoaded(false), mHolidaysLoaded(false) { KGlobal::config()->setGroup("General"); QString calSystem = KGlobal::config()->readEntry( "CalendarSystem", "gregorian" ); mCalendarSystem = KCalendarSystemFactory::create( calSystem ); } KTrader::OfferList KOCore::availablePlugins(const QString &type) { return KTrader::self()->query(type); } KOrg::Plugin *KOCore::loadPlugin(KService::Ptr service) { kdDebug() << "loadPlugin: library: " << service->library() << endl; if ( !service->hasServiceType( "Calendar/Plugin" ) ) { return 0; } KLibFactory *factory = KLibLoader::self()->factory(service->library()); if (!factory) { kdDebug() << "KOCore::loadPlugin(): Factory creation failed" << endl; return 0; } KOrg::PluginFactory *pluginFactory = static_cast<KOrg::PluginFactory *>(factory); if (!pluginFactory) { kdDebug() << "KOCore::loadPlugin(): Cast to KOrg::PluginFactory failed" << endl; return 0; } return pluginFactory->create(); } KOrg::Plugin *KOCore::loadPlugin(const QString &name) { KTrader::OfferList list = availablePlugins("Calendar/Plugin"); KTrader::OfferList::ConstIterator it; for(it = list.begin(); it != list.end(); ++it) { if ((*it)->desktopEntryName() == name) { return loadPlugin(*it); } } return 0; } KOrg::CalendarDecoration *KOCore::loadCalendarDecoration(KService::Ptr service) { kdDebug() << "loadCalendarDecoration: library: " << service->library() << endl; KLibFactory *factory = KLibLoader::self()->factory(service->library()); if (!factory) { kdDebug() << "KOCore::loadCalendarDecoration(): Factory creation failed" << endl; return 0; } KOrg::CalendarDecorationFactory *pluginFactory = static_cast<KOrg::CalendarDecorationFactory *>(factory); if (!pluginFactory) { kdDebug() << "KOCore::loadCalendarDecoration(): Cast failed" << endl; return 0; } return pluginFactory->create(); } KOrg::CalendarDecoration *KOCore::loadCalendarDecoration(const QString &name) { KTrader::OfferList list = availablePlugins("Calendar/Decoration"); KTrader::OfferList::ConstIterator it; for(it = list.begin(); it != list.end(); ++it) { if ((*it)->desktopEntryName() == name) { return loadCalendarDecoration(*it); } } return 0; } KOrg::Part *KOCore::loadPart(KService::Ptr service, KOrg::MainWindow *parent) { kdDebug() << "loadPart: library: " << service->library() << endl; if ( !service->hasServiceType( "KOrganizer/Part" ) ) { return 0; } KLibFactory *factory = KLibLoader::self()->factory(service->library()); if (!factory) { kdDebug() << "KOCore::loadPart(): Factory creation failed" << endl; return 0; } KOrg::PartFactory *pluginFactory = static_cast<KOrg::PartFactory *>(factory); if (!pluginFactory) { kdDebug() << "KOCore::loadPart(): Cast failed" << endl; return 0; } return pluginFactory->create(parent); } KOrg::Part *KOCore::loadPart(const QString &name,KOrg::MainWindow *parent) { KTrader::OfferList list = availablePlugins("KOrg::MainWindow/Part"); KTrader::OfferList::ConstIterator it; for(it = list.begin(); it != list.end(); ++it) { if ((*it)->desktopEntryName() == name) { return loadPart(*it,parent); } } return 0; } KOrg::CalendarDecoration::List KOCore::calendarDecorations() { if (!mCalendarDecorationsLoaded) { QStringList selectedPlugins = KOPrefs::instance()->mSelectedPlugins; mCalendarDecorations.clear(); KTrader::OfferList plugins = availablePlugins("Calendar/Decoration"); KTrader::OfferList::ConstIterator it; for(it = plugins.begin(); it != plugins.end(); ++it) { if ((*it)->hasServiceType("Calendar/Decoration")) { if (selectedPlugins.find((*it)->desktopEntryName()) != selectedPlugins.end()) { mCalendarDecorations.append(loadCalendarDecoration(*it)); } } } mCalendarDecorationsLoaded = true; } return mCalendarDecorations; } KOrg::Part::List KOCore::loadParts( KOrg::MainWindow *parent ) { KOrg::Part::List parts; QStringList selectedPlugins = KOPrefs::instance()->mSelectedPlugins; KTrader::OfferList plugins = availablePlugins("KOrganizer/Part"); KTrader::OfferList::ConstIterator it; for(it = plugins.begin(); it != plugins.end(); ++it) { if (selectedPlugins.find((*it)->desktopEntryName()) != selectedPlugins.end()) { KOrg::Part *part = loadPart(*it,parent); if ( part ) { parent->guiFactory()->addClient( part ); parts.append( part ); } } } return parts; } void KOCore::unloadPlugins() { KOrg::CalendarDecoration *plugin; for( plugin=mCalendarDecorations.first(); plugin; plugin=mCalendarDecorations.next() ) { delete plugin; } mCalendarDecorations.clear(); mCalendarDecorationsLoaded = false; } void KOCore::unloadParts( KOrg::MainWindow *parent, KOrg::Part::List& parts ) { KOrg::Part *part; for( part=parts.first(); part; part=parts.next() ) { parent->guiFactory()->removeClient( part ); delete part; } parts.clear(); } KOrg::Part::List KOCore::reloadParts( KOrg::MainWindow *parent, KOrg::Part::List& parts ) { unloadParts( parent, parts ); return loadParts( parent ); } void KOCore::reloadPlugins() { mCalendarDecorationsLoaded = false; // Plugins should be unloaded, but e.g. komonthview keeps using the old ones unloadPlugins(); calendarDecorations(); } QString KOCore::holiday(const QDate &date) { if (!mHolidaysLoaded) { mHolidays = static_cast<KOrg::CalendarDecoration *>(loadPlugin("holidays")); mHolidaysLoaded = true; } if (mHolidays) return mHolidays->shortText(date); else return QString::null; } KCalendarSystem* KOCore::calendarSystem() { return mCalendarSystem; } <|endoftext|>
<commit_before>/* Copyright (c) 2010 - 2021 Advanced Micro Devices, Inc. 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. */ #ifndef VERSIONS_HPP_ #define VERSIONS_HPP_ #include "utils/macros.hpp" #ifndef AMD_PLATFORM_NAME #define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing" #endif // AMD_PLATFORM_NAME #ifndef AMD_PLATFORM_BUILD_NUMBER #define AMD_PLATFORM_BUILD_NUMBER 3351 #endif // AMD_PLATFORM_BUILD_NUMBER #ifndef AMD_PLATFORM_REVISION_NUMBER #define AMD_PLATFORM_REVISION_NUMBER 0 #endif // AMD_PLATFORM_REVISION_NUMBER #ifndef AMD_PLATFORM_RELEASE_INFO #define AMD_PLATFORM_RELEASE_INFO #endif // AMD_PLATFORM_RELEASE_INFO #define AMD_BUILD_STRING \ XSTR(AMD_PLATFORM_BUILD_NUMBER) \ "." XSTR(AMD_PLATFORM_REVISION_NUMBER) #ifndef AMD_PLATFORM_INFO #define AMD_PLATFORM_INFO \ "AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \ "." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")" #endif // ATI_PLATFORM_INFO #endif // VERSIONS_HPP_ <commit_msg>SWDEV-2 - Change OpenCL version number from 3351 to 3352<commit_after>/* Copyright (c) 2010 - 2021 Advanced Micro Devices, Inc. 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. */ #ifndef VERSIONS_HPP_ #define VERSIONS_HPP_ #include "utils/macros.hpp" #ifndef AMD_PLATFORM_NAME #define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing" #endif // AMD_PLATFORM_NAME #ifndef AMD_PLATFORM_BUILD_NUMBER #define AMD_PLATFORM_BUILD_NUMBER 3352 #endif // AMD_PLATFORM_BUILD_NUMBER #ifndef AMD_PLATFORM_REVISION_NUMBER #define AMD_PLATFORM_REVISION_NUMBER 0 #endif // AMD_PLATFORM_REVISION_NUMBER #ifndef AMD_PLATFORM_RELEASE_INFO #define AMD_PLATFORM_RELEASE_INFO #endif // AMD_PLATFORM_RELEASE_INFO #define AMD_BUILD_STRING \ XSTR(AMD_PLATFORM_BUILD_NUMBER) \ "." XSTR(AMD_PLATFORM_REVISION_NUMBER) #ifndef AMD_PLATFORM_INFO #define AMD_PLATFORM_INFO \ "AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \ "." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")" #endif // ATI_PLATFORM_INFO #endif // VERSIONS_HPP_ <|endoftext|>
<commit_before>/* -*- C++ -*- */ /************************************************************************* * Copyright(c) 1995~2005 Masaharu Goto ([email protected]) * * For the licensing terms see the file COPYING * ************************************************************************/ #include <stdio.h> typedef long Long_t; typedef unsigned long ULong_t; typedef long long Long64_t; typedef unsigned long long ULong64_t; typedef long double Double92_t; typedef double Double_t; void test0() { #if 0 ULong_t a = dynamic_cast<ULong_t>(123); ULong64_t b = dynamic_cast<ULong64_t>(456); Double92_t c = dynamic_cast<Double92_t>(1.234); #else ULong_t a = (ULong_t)(123); ULong64_t b = (ULong64_t)(456); Double92_t c = (Double92_t)(1.234); Double_t d = (Double_t)(5.678); #endif printf("%lu %llu %LG %g\n",a,b,c,d); printf("%lu %g\n",a,d); printf("%LG\n",c); } void test1() { ULong64_t aa; aa = (ULong64_t)(-(1<<30 - 1)); printf("%llu ",aa); aa = aa<<1; printf("%llu ",aa); aa = aa*2; printf("%llu ",aa); aa = aa/((Long64_t)(-(1u<<30 - 1))); printf("%llu\n",aa); } void test2() { ULong64_t aa; aa = 1ULL<<31; printf("%llu ",aa); aa = aa<<1; printf("%llu ",aa); aa = aa*2; printf("%llu ",aa); aa = aa/((Long64_t)(1u<<31)); printf("%llu\n",aa); } void test3() { Long64_t aa; aa = (int)(1u<<31); printf("%lld ",aa); aa = aa<<1; printf("%lld ",aa); aa = aa*2; printf("%lld ",aa); aa = aa/(1LL<<31); printf("%lld\n",aa); } void test4() { Long64_t aa; aa = 1LL<<31; printf("%lld ",aa); aa = aa<<1; printf("%lld ",aa); aa = aa*2; printf("%lld ",aa); aa = aa/(1LL<<31); printf("%lld\n",aa); } int main() { test0(); test1(); test2(); test3(); test4(); return 0; } <commit_msg>Extra output<commit_after>/* -*- C++ -*- */ /************************************************************************* * Copyright(c) 1995~2005 Masaharu Goto ([email protected]) * * For the licensing terms see the file COPYING * ************************************************************************/ #include <stdio.h> typedef long Long_t; typedef unsigned long ULong_t; typedef long long Long64_t; typedef unsigned long long ULong64_t; typedef long double Double92_t; typedef double Double_t; void test0() { #if 0 ULong_t a = dynamic_cast<ULong_t>(123); ULong64_t b = dynamic_cast<ULong64_t>(456); Double92_t c = dynamic_cast<Double92_t>(1.234); #else ULong_t a = (ULong_t)(123); ULong64_t b = (ULong64_t)(456); Double92_t c = (Double92_t)(1.234); Double_t d = (Double_t)(5.678); #endif printf("%lu %llu %LG %g\n",a,b,c,d); printf("%lu %g\n",a,d); printf("%LG\n",c); } void test1() { printf("test1\n"); ULong64_t aa; aa = (ULong64_t)(-(1<<30 - 1)); printf("1: %llu ",aa); aa = aa<<1; printf("2: %llu ",aa); aa = aa*2; printf("3: %llu ",aa); ULong64_t bb = aa; // printf("4-0: %x %x ",1u<<30 - 1,-(1u<<30 - 1)); // Long_t ii = -(1u<<28-1); // -(536870913u-1); // 1u<<30 - 1); // printf("4-1: %lld %llu %llu ",ii,(ULong64_t)ii, aa); // aa = bb / ii; aa = bb/((Long64_t)(-(1u<<30 - 1))); printf("4: %llu\n",aa); } void test2() { printf("test2\n"); ULong64_t aa; aa = 1ULL<<31; printf("1: %llu ",aa); aa = aa<<1; printf("2: %llu ",aa); aa = aa*2; printf("3: %llu ",aa); aa = aa/((Long64_t)(1u<<31)); printf("4: %llu\n",aa); } void test3() { printf("test3\n"); Long64_t aa; aa = (int)(1u<<31); printf("1: %lld ",aa); aa = aa<<1; printf("2: %lld ",aa); aa = aa*2; printf("3: %lld ",aa); aa = aa/(1LL<<31); printf("4: %lld\n",aa); } void test4() { printf("test4\n"); Long64_t aa; aa = 1LL<<31; printf("1: %lld ",aa); aa = aa<<1; printf("2: %lld ",aa); aa = aa*2; printf("3: %lld ",aa); aa = aa/(1LL<<31); printf("4: %lld\n",aa); } int main() { test0(); test1(); test2(); test3(); test4(); return 0; } <|endoftext|>
<commit_before>/* Copyright (c) 2010-present Advanced Micro Devices, Inc. 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. */ #ifndef VERSIONS_HPP_ #define VERSIONS_HPP_ #include "utils/macros.hpp" #ifndef AMD_PLATFORM_NAME #define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing" #endif // AMD_PLATFORM_NAME #ifndef AMD_PLATFORM_BUILD_NUMBER #define AMD_PLATFORM_BUILD_NUMBER 3306 #endif // AMD_PLATFORM_BUILD_NUMBER #ifndef AMD_PLATFORM_REVISION_NUMBER #define AMD_PLATFORM_REVISION_NUMBER 0 #endif // AMD_PLATFORM_REVISION_NUMBER #ifndef AMD_PLATFORM_RELEASE_INFO #define AMD_PLATFORM_RELEASE_INFO #endif // AMD_PLATFORM_RELEASE_INFO #define AMD_BUILD_STRING \ XSTR(AMD_PLATFORM_BUILD_NUMBER) \ "." XSTR(AMD_PLATFORM_REVISION_NUMBER) #ifndef AMD_PLATFORM_INFO #define AMD_PLATFORM_INFO \ "AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \ "." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")" #endif // ATI_PLATFORM_INFO #endif // VERSIONS_HPP_ <commit_msg>SWDEV-2 - Change OpenCL version number from 3306 to 3307<commit_after>/* Copyright (c) 2010-present Advanced Micro Devices, Inc. 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. */ #ifndef VERSIONS_HPP_ #define VERSIONS_HPP_ #include "utils/macros.hpp" #ifndef AMD_PLATFORM_NAME #define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing" #endif // AMD_PLATFORM_NAME #ifndef AMD_PLATFORM_BUILD_NUMBER #define AMD_PLATFORM_BUILD_NUMBER 3307 #endif // AMD_PLATFORM_BUILD_NUMBER #ifndef AMD_PLATFORM_REVISION_NUMBER #define AMD_PLATFORM_REVISION_NUMBER 0 #endif // AMD_PLATFORM_REVISION_NUMBER #ifndef AMD_PLATFORM_RELEASE_INFO #define AMD_PLATFORM_RELEASE_INFO #endif // AMD_PLATFORM_RELEASE_INFO #define AMD_BUILD_STRING \ XSTR(AMD_PLATFORM_BUILD_NUMBER) \ "." XSTR(AMD_PLATFORM_REVISION_NUMBER) #ifndef AMD_PLATFORM_INFO #define AMD_PLATFORM_INFO \ "AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \ "." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")" #endif // ATI_PLATFORM_INFO #endif // VERSIONS_HPP_ <|endoftext|>
<commit_before>#include "JSONExpr.h" #include "llvm/Support/Format.h" namespace clang { namespace clangd { namespace json { using namespace llvm; void Expr::copyFrom(const Expr &M) { Type = M.Type; switch (Type) { case T_Null: case T_Boolean: case T_Number: memcpy(Union.buffer, M.Union.buffer, sizeof(Union.buffer)); break; case T_StringRef: create<StringRef>(M.as<StringRef>()); break; case T_String: create<std::string>(M.as<std::string>()); break; case T_Object: create<Object>(M.as<Object>()); break; case T_Array: create<Array>(M.as<Array>()); break; } } void Expr::moveFrom(const Expr &&M) { Type = M.Type; switch (Type) { case T_Null: case T_Boolean: case T_Number: memcpy(Union.buffer, M.Union.buffer, sizeof(Union.buffer)); break; case T_StringRef: create<StringRef>(M.as<StringRef>()); break; case T_String: create<std::string>(std::move(M.as<std::string>())); M.Type = T_Null; break; case T_Object: create<Object>(std::move(M.as<Object>())); M.Type = T_Null; break; case T_Array: create<Array>(std::move(M.as<Array>())); M.Type = T_Null; break; } } void Expr::destroy() { switch (Type) { case T_Null: case T_Boolean: case T_Number: break; case T_StringRef: as<StringRef>().~StringRef(); break; case T_String: as<std::string>().~basic_string(); break; case T_Object: as<Object>().~Object(); break; case T_Array: as<Array>().~Array(); break; } } } // namespace json } // namespace clangd } // namespace clang namespace { void quote(llvm::raw_ostream &OS, llvm::StringRef S) { OS << '\"'; for (unsigned char C : S) { if (C == 0x22 || C == 0x5C) OS << '\\'; if (C >= 0x20) { OS << C; continue; } OS << '\\'; switch (C) { // A few characters are common enough to make short escapes worthwhile. case '\t': OS << 't'; break; case '\n': OS << 'n'; break; case '\r': OS << 'r'; break; default: OS << 'u'; llvm::write_hex(OS, C, llvm::HexPrintStyle::Lower, 4); break; } } OS << '\"'; } enum IndenterAction { Indent, Outdent, Newline, Space, }; } // namespace // Prints JSON. The indenter can be used to control formatting. template <typename Indenter> void clang::clangd::json::Expr::print(raw_ostream &OS, const Indenter &I) const { switch (Type) { case T_Null: OS << "null"; break; case T_Boolean: OS << (as<bool>() ? "true" : "false"); break; case T_Number: OS << format("%g", as<double>()); break; case T_StringRef: quote(OS, as<StringRef>()); break; case T_String: quote(OS, as<std::string>()); break; case T_Object: { bool Comma = false; OS << '{'; I(Indent); for (const auto &P : as<Expr::Object>()) { if (Comma) OS << ','; Comma = true; I(Newline); quote(OS, P.first); OS << ':'; I(Space); P.second.print(OS, I); } I(Outdent); if (Comma) I(Newline); OS << '}'; break; } case T_Array: { bool Comma = false; OS << '['; I(Indent); for (const auto &E : as<Expr::Array>()) { if (Comma) OS << ','; Comma = true; I(Newline); E.print(OS, I); } I(Outdent); if (Comma) I(Newline); OS << ']'; break; } } } llvm::raw_ostream &clang::clangd::json::operator<<(raw_ostream &OS, const Expr &E) { E.print(OS, [](IndenterAction A) { /*ignore*/ }); return OS; } void llvm::format_provider<clang::clangd::json::Expr>::format( const clang::clangd::json::Expr &E, raw_ostream &OS, StringRef Options) { if (Options.empty()) { OS << E; return; } unsigned IndentAmount = 0; if (Options.getAsInteger(/*Radix=*/10, IndentAmount)) assert(false && "json::Expr format options should be an integer"); unsigned IndentLevel = 0; E.print(OS, [&](IndenterAction A) { switch (A) { case Newline: OS << '\n'; OS.indent(IndentLevel); break; case Space: OS << ' '; break; case Indent: IndentLevel += IndentAmount; break; case Outdent: IndentLevel -= IndentAmount; break; }; }); } <commit_msg>[clangd] Squash namespace warning<commit_after>#include "JSONExpr.h" #include "llvm/Support/Format.h" namespace clang { namespace clangd { namespace json { using namespace llvm; void Expr::copyFrom(const Expr &M) { Type = M.Type; switch (Type) { case T_Null: case T_Boolean: case T_Number: memcpy(Union.buffer, M.Union.buffer, sizeof(Union.buffer)); break; case T_StringRef: create<StringRef>(M.as<StringRef>()); break; case T_String: create<std::string>(M.as<std::string>()); break; case T_Object: create<Object>(M.as<Object>()); break; case T_Array: create<Array>(M.as<Array>()); break; } } void Expr::moveFrom(const Expr &&M) { Type = M.Type; switch (Type) { case T_Null: case T_Boolean: case T_Number: memcpy(Union.buffer, M.Union.buffer, sizeof(Union.buffer)); break; case T_StringRef: create<StringRef>(M.as<StringRef>()); break; case T_String: create<std::string>(std::move(M.as<std::string>())); M.Type = T_Null; break; case T_Object: create<Object>(std::move(M.as<Object>())); M.Type = T_Null; break; case T_Array: create<Array>(std::move(M.as<Array>())); M.Type = T_Null; break; } } void Expr::destroy() { switch (Type) { case T_Null: case T_Boolean: case T_Number: break; case T_StringRef: as<StringRef>().~StringRef(); break; case T_String: as<std::string>().~basic_string(); break; case T_Object: as<Object>().~Object(); break; case T_Array: as<Array>().~Array(); break; } } } // namespace json } // namespace clangd } // namespace clang namespace { void quote(llvm::raw_ostream &OS, llvm::StringRef S) { OS << '\"'; for (unsigned char C : S) { if (C == 0x22 || C == 0x5C) OS << '\\'; if (C >= 0x20) { OS << C; continue; } OS << '\\'; switch (C) { // A few characters are common enough to make short escapes worthwhile. case '\t': OS << 't'; break; case '\n': OS << 'n'; break; case '\r': OS << 'r'; break; default: OS << 'u'; llvm::write_hex(OS, C, llvm::HexPrintStyle::Lower, 4); break; } } OS << '\"'; } enum IndenterAction { Indent, Outdent, Newline, Space, }; } // namespace // Prints JSON. The indenter can be used to control formatting. template <typename Indenter> void clang::clangd::json::Expr::print(raw_ostream &OS, const Indenter &I) const { switch (Type) { case T_Null: OS << "null"; break; case T_Boolean: OS << (as<bool>() ? "true" : "false"); break; case T_Number: OS << format("%g", as<double>()); break; case T_StringRef: quote(OS, as<StringRef>()); break; case T_String: quote(OS, as<std::string>()); break; case T_Object: { bool Comma = false; OS << '{'; I(Indent); for (const auto &P : as<Expr::Object>()) { if (Comma) OS << ','; Comma = true; I(Newline); quote(OS, P.first); OS << ':'; I(Space); P.second.print(OS, I); } I(Outdent); if (Comma) I(Newline); OS << '}'; break; } case T_Array: { bool Comma = false; OS << '['; I(Indent); for (const auto &E : as<Expr::Array>()) { if (Comma) OS << ','; Comma = true; I(Newline); E.print(OS, I); } I(Outdent); if (Comma) I(Newline); OS << ']'; break; } } } namespace clang { namespace clangd { namespace json { llvm::raw_ostream &operator<<(raw_ostream &OS, const Expr &E) { E.print(OS, [](IndenterAction A) { /*ignore*/ }); return OS; } } // namespace json } // namespace clangd } // namespace clang void llvm::format_provider<clang::clangd::json::Expr>::format( const clang::clangd::json::Expr &E, raw_ostream &OS, StringRef Options) { if (Options.empty()) { OS << E; return; } unsigned IndentAmount = 0; if (Options.getAsInteger(/*Radix=*/10, IndentAmount)) assert(false && "json::Expr format options should be an integer"); unsigned IndentLevel = 0; E.print(OS, [&](IndenterAction A) { switch (A) { case Newline: OS << '\n'; OS.indent(IndentLevel); break; case Space: OS << ' '; break; case Indent: IndentLevel += IndentAmount; break; case Outdent: IndentLevel -= IndentAmount; break; }; }); } <|endoftext|>
<commit_before><commit_msg>coverity#1292225 variable guards dead code<commit_after><|endoftext|>
<commit_before><commit_msg>fix old indent<commit_after><|endoftext|>
<commit_before>/*-------------geometrical_optics.cpp-----------------------------------------// * * geometrical optics * * Purpose: to simulate light going through a lens with a variable refractive * index. Not wave-like. * *-----------------------------------------------------------------------------*/ #include <iostream> #include <cmath> #include <fstream> #include <cassert> /*----------------------------------------------------------------------------// * STRUCTS / FUNCTIONS *-----------------------------------------------------------------------------*/ // constants const int lightnum = 10, time_res = 200; // Struct for space struct dimensions{ double x, y; }; // Struct for light rays struct light_rays{ dimensions ray[lightnum]; dimensions ray_vel[lightnum]; double index[lightnum]; }; // checks refractive index profile double check_n(double x, double y); // Generate light and refractive index profile light_rays light_gen(dimensions dim, double max_vel, double angle); // Propagate light through media light_rays propagate(light_rays ray_diagram, double step_size, double max_vel, std::ofstream &output); /*----------------------------------------------------------------------------// * MAIN *-----------------------------------------------------------------------------*/ int main(){ // defines output std::ofstream output("out.dat", std::ofstream::out); dimensions dim; dim.x = 4; dim.y = 10; double max_vel = 1; light_rays pvec = light_gen(dim, max_vel, 0.523598776); pvec = propagate(pvec, 0.1, max_vel, output); output << "\n \n5 0 0 0 \n5 5 0 0 \n"; } /*----------------------------------------------------------------------------// * SUBROUTINE *-----------------------------------------------------------------------------*/ // checks refractive index profile double check_n(double x, double y){ // check refractive index against a set profile double index; if (x < 5 || x > 7){ index = 1.0; } else{ //index = (x - 4.0); index = 1.4; } return index; } // Generate light and refractive index profile light_rays light_gen(dimensions dim, double max_vel, double angle){ light_rays ray_diagram; // create rays for (size_t i = 0; i < lightnum; i++){ ray_diagram.ray[i].x = (double)i * dim.x / lightnum; ray_diagram.ray[i].y = 0; //ray_diagram.ray[i].y = cos(angle); //ray_diagram.ray[i].x = sin(angle); ray_diagram.ray_vel[i].x = max_vel * cos(angle); ray_diagram.ray_vel[i].y = max_vel * sin(angle); ray_diagram.index[i] = check_n(ray_diagram.ray[i].x, ray_diagram.ray[i].y); } return ray_diagram; } // Propagate light through media light_rays propagate(light_rays ray_diagram, double step_size, double max_vel, std::ofstream &output){ double index_p, theta, theta_p; double iratio, dotprod; // move simulation every timestep for (size_t i = 0; i < time_res; i++){ for (size_t j = 0; j < lightnum; j++){ ray_diagram.ray[j].x += ray_diagram.ray_vel[j].x * step_size; ray_diagram.ray[j].y += ray_diagram.ray_vel[j].y * step_size; if (ray_diagram.index[j] != check_n(ray_diagram.ray[j].x, ray_diagram.ray[j].y)){ index_p = check_n(ray_diagram.ray[j].x, ray_diagram.ray[j].y); std::cout << index_p << '\t' << i << '\t' << j << '\n'; /* // Non vector form theta = atan2(ray_diagram.ray_vel[j].y, ray_diagram.ray_vel[j].x); theta_p = asin((ray_diagram.index[j] / index_p) * sin(theta)); ray_diagram.ray_vel[j].y = max_vel * sin(theta_p); ray_diagram.ray_vel[j].x = max_vel * cos(theta_p); */ // Vector form -- So;ution by Gustorn! double r = ray_diagram.index[j] / index_p; double mag = std::sqrt(ray_diagram.ray_vel[j].x * ray_diagram.ray_vel[j].x + ray_diagram.ray_vel[j].y * ray_diagram.ray_vel[j].y); double ix = ray_diagram.ray_vel[j].x / mag; double iy = ray_diagram.ray_vel[j].y / mag; // Normal: [-1, 0] double c = ix; double k = 1.0 - r * r * (1.0 - c * c); if (k < 0.0) { // Do whatever } else { double k1 = std::sqrt(k); ray_diagram.ray_vel[j].x = r * ix - (r * c - k1); ray_diagram.ray_vel[j].y = r * iy; } ray_diagram.index[j] = index_p; } } for (size_t q = 0; q < lightnum; q++){ output << ray_diagram.ray[q].x <<'\t'<< ray_diagram.ray[q].y << '\t' << ray_diagram.ray_vel[q].x <<'\t'<< ray_diagram.ray_vel[q].y << '\n'; } output << '\n' << '\n'; } return ray_diagram; } <commit_msg>Added a sphere instead of wall; however, not convinced normal vector is defined appropriately.<commit_after>/*-------------geometrical_optics.cpp-----------------------------------------// * * geometrical optics * * Purpose: to simulate light going through a lens with a variable refractive * index. Not wave-like. * * Notes: Compiles with g++ geometrical_optics.cpp -std=c++11 * *-----------------------------------------------------------------------------*/ #include <iostream> #include <cmath> #include <fstream> #include <cassert> /*----------------------------------------------------------------------------// * STRUCTS / FUNCTIONS *-----------------------------------------------------------------------------*/ // constants const int lightnum = 10, time_res = 200; // Struct for space struct dimensions{ double x, y; }; // Struct for light rays struct light_rays{ dimensions ray[lightnum]; dimensions ray_vel[lightnum]; double index[lightnum]; }; // checks refractive index profile double check_n(double x, double y, dimensions origin, double radius); // Generate light and refractive index profile light_rays light_gen(dimensions dim, double max_vel, double angle, dimensions origin, double radius); // Propagate light through media light_rays propagate(light_rays ray_diagram, double step_size, double max_vel, dimensions origin, double radius, std::ofstream &output); // Finds the c for later double find_c(double ix, double iy, dimensions origin, double radius); /*----------------------------------------------------------------------------// * MAIN *-----------------------------------------------------------------------------*/ int main(){ // defines output std::ofstream output("out.dat", std::ofstream::out); dimensions dim; dim.x = 4; dim.y = 10; // origin of the sphere dimensions origin; origin.x = 5; origin.y = 5; double radius = 5; double max_vel = 1; light_rays pvec = light_gen(dim, max_vel, 0.523598776, origin, radius); pvec = propagate(pvec, 0.1, max_vel, origin, radius, output); output << "\n \n5 0 0 0 \n5 5 0 0 \n"; } /*----------------------------------------------------------------------------// * SUBROUTINE *-----------------------------------------------------------------------------*/ // checks refractive index profile double check_n(double x, double y, dimensions origin, double radius){ // check refractive index against a set profile double index, diff; diff = sqrt((x - origin.x) * (x - origin.x) + (y - origin.y) * (y - origin.y)); if (diff < radius){ index = 1.4; } else{ index = 1; } /* if (x < 5 || x > 7){ index = 1.0; } else{ //index = (x - 4.0); index = 1.4; } */ return index; } // Generate light and refractive index profile light_rays light_gen(dimensions dim, double max_vel, double angle, dimensions origin, double radius){ light_rays ray_diagram; // create rays for (size_t i = 0; i < lightnum; i++){ ray_diagram.ray[i].x = (double)i * dim.x / lightnum; ray_diagram.ray[i].y = 0; //ray_diagram.ray[i].y = cos(angle); //ray_diagram.ray[i].x = sin(angle); ray_diagram.ray_vel[i].x = max_vel * cos(angle); ray_diagram.ray_vel[i].y = max_vel * sin(angle); ray_diagram.index[i] = check_n(ray_diagram.ray[i].x, ray_diagram.ray[i].y, origin, radius); } return ray_diagram; } // Propagate light through media light_rays propagate(light_rays ray_diagram, double step_size, double max_vel, dimensions origin, double radius, std::ofstream &output){ double index_p, theta, theta_p; double iratio, dotprod; // move simulation every timestep for (size_t i = 0; i < time_res; i++){ for (size_t j = 0; j < lightnum; j++){ ray_diagram.ray[j].x += ray_diagram.ray_vel[j].x * step_size; ray_diagram.ray[j].y += ray_diagram.ray_vel[j].y * step_size; if (ray_diagram.index[j] != check_n(ray_diagram.ray[j].x, ray_diagram.ray[j].y, origin, radius)){ index_p = check_n(ray_diagram.ray[j].x, ray_diagram.ray[j].y, origin, radius); std::cout << index_p << '\t' << i << '\t' << j << '\n'; /* // Non vector form theta = atan2(ray_diagram.ray_vel[j].y, ray_diagram.ray_vel[j].x); theta_p = asin((ray_diagram.index[j] / index_p) * sin(theta)); ray_diagram.ray_vel[j].y = max_vel * sin(theta_p); ray_diagram.ray_vel[j].x = max_vel * cos(theta_p); */ // Vector form -- Solution by Gustorn! double r = ray_diagram.index[j] / index_p; double mag = std::sqrt(ray_diagram.ray_vel[j].x * ray_diagram.ray_vel[j].x + ray_diagram.ray_vel[j].y * ray_diagram.ray_vel[j].y); double ix = ray_diagram.ray_vel[j].x / mag; double iy = ray_diagram.ray_vel[j].y / mag; // c for later; Normal was: [-1, 0] double c = find_c(ix, iy, origin, radius); double k = 1.0 - r * r * (1.0 - c * c); if (k < 0.0) { // Do whatever } else { double k1 = std::sqrt(k); ray_diagram.ray_vel[j].x = r * ix - (r * c - k1); ray_diagram.ray_vel[j].y = r * iy; } ray_diagram.index[j] = index_p; } } /* output << ray_diagram.ray[5].x <<'\t'<< ray_diagram.ray[5].y << '\t' << ray_diagram.ray_vel[5].x <<'\t'<< ray_diagram.ray_vel[5].y << '\n'; */ for (size_t q = 0; q < lightnum; q++){ output << ray_diagram.ray[q].x <<'\t'<< ray_diagram.ray[q].y << '\t' << ray_diagram.ray_vel[q].x <<'\t'<< ray_diagram.ray_vel[q].y << '\n'; } output << '\n' << '\n'; } return ray_diagram; } // Finds the c for later double find_c(double ix, double iy, dimensions origin, double radius){ // Step 1: define normal vector // In this case, the normal vector is just the direction from the radius // of the sphere double mag = sqrt((ix - origin.x) * (ix - origin.x) + (iy - origin.y) * (iy - origin.y)); double x, y; x = (ix - origin.x) / mag; y = (iy - origin.y) / mag; // Step 2: simple dot product double dot = -(ix * x + iy * y); return dot; } <|endoftext|>
<commit_before><commit_msg>silence unknown packing spew<commit_after><|endoftext|>
<commit_before><commit_msg>coverity#1187640 this code has no effect<commit_after><|endoftext|>
<commit_before>/* Copyright 2022 Jordi SUBIRANA 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. */ #ifndef ATEMA_MATH_VECTOR_HPP #define ATEMA_MATH_VECTOR_HPP #include <Atema/Core/Hash.hpp> #include <array> namespace at { namespace detail { template <size_t N, typename T> struct VectorBase { std::array<T, N> data; }; template <typename T> struct VectorBase<2, T> { union { std::array<T, 2> data; struct { T x, y; }; }; }; template <typename T> struct VectorBase<3, T> { union { std::array<T, 3> data; struct { T x, y, z; }; }; }; template <typename T> struct VectorBase<4, T> { union { std::array<T, 4> data; struct { T x, y, z, w; }; }; }; } template <size_t N, typename T> struct Vector : detail::VectorBase<N, T> { Vector(); Vector(const Vector& other); Vector(Vector&& other) noexcept; template <typename...Args> Vector(Args...args); ~Vector() noexcept; Vector<N, T>& normalize() noexcept; T getNorm() const noexcept; Vector<N, T> getNormalized() const noexcept; Vector<N, T> operator +(const Vector<N, T>& arg) const; Vector<N, T> operator -(const Vector<N, T>& arg) const; Vector<N, T> operator *(const Vector<N, T>& arg) const; Vector<N, T> operator /(const Vector<N, T>& arg) const; Vector<N, T> operator +(T arg) const; Vector<N, T> operator -(T arg) const; Vector<N, T> operator *(T arg) const; Vector<N, T> operator /(T arg) const; Vector<N, T>& operator +=(const Vector<N, T>& arg); Vector<N, T>& operator -=(const Vector<N, T>& arg); Vector<N, T>& operator *=(const Vector<N, T>& arg); Vector<N, T>& operator /=(const Vector<N, T>& arg); Vector<N, T>& operator +=(T arg); Vector<N, T>& operator -=(T arg); Vector<N, T>& operator *=(T arg); Vector<N, T>& operator /=(T arg); Vector<N, T>& operator ++(); Vector<N, T> operator ++(int); Vector<N, T>& operator --(); Vector<N, T> operator --(int); Vector<N, T> operator+() const; Vector<N, T> operator-() const; Vector& operator=(const Vector& other); Vector& operator=(Vector&& other) noexcept; bool operator==(const Vector<N, T>& other) const; bool operator!=(const Vector<N, T>& other) const; T& operator[](size_t index); const T& operator[](size_t index) const; T dot(const Vector<N, T>& other) const; T angle(const Vector<N, T>& other) const; }; template <typename T> using Vector2 = Vector<2, T>; template <typename T> using Vector3 = Vector<3, T>; template <typename T> using Vector4 = Vector<4, T>; using Vector2i = Vector2<int>; using Vector2u = Vector2<unsigned>; using Vector2f = Vector2<float>; using Vector2d = Vector2<double>; using Vector3i = Vector3<int>; using Vector3u = Vector3<unsigned>; using Vector3f = Vector3<float>; using Vector3d = Vector3<double>; using Vector4i = Vector4<int>; using Vector4u = Vector4<unsigned>; using Vector4f = Vector4<float>; using Vector4d = Vector4<double>; template <typename T> Vector3<T> cross(const Vector2<T>& v1, const Vector2<T>& v2) { T z = v1.x * v2.y - v1.y * v2.x; return (Vector3<T>(0, 0, z)); } template <typename T> Vector3<T> cross(const Vector3<T>& v1, const Vector3<T>& v2) { Vector3<T> tmp; tmp.x = v1.y * v2.z - v1.z * v2.y; tmp.y = v1.z * v2.x - v1.x * v2.z; tmp.z = v1.x * v2.y - v1.y * v2.x; return (tmp); } } ATEMA_DECLARE_STD_HASH(at::Vector2i) ATEMA_DECLARE_STD_HASH(at::Vector2u) ATEMA_DECLARE_STD_HASH(at::Vector2f) ATEMA_DECLARE_STD_HASH(at::Vector2d) ATEMA_DECLARE_STD_HASH(at::Vector3i) ATEMA_DECLARE_STD_HASH(at::Vector3u) ATEMA_DECLARE_STD_HASH(at::Vector3f) ATEMA_DECLARE_STD_HASH(at::Vector3d) ATEMA_DECLARE_STD_HASH(at::Vector4i) ATEMA_DECLARE_STD_HASH(at::Vector4u) ATEMA_DECLARE_STD_HASH(at::Vector4f) ATEMA_DECLARE_STD_HASH(at::Vector4d) #include <Atema/Math/Vector.inl> #endif<commit_msg>Math - Vector - Generic overload of std::hash instead of specialized functions<commit_after>/* Copyright 2022 Jordi SUBIRANA 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. */ #ifndef ATEMA_MATH_VECTOR_HPP #define ATEMA_MATH_VECTOR_HPP #include <Atema/Core/Hash.hpp> #include <array> namespace at { namespace detail { template <size_t N, typename T> struct VectorBase { std::array<T, N> data; }; template <typename T> struct VectorBase<2, T> { union { std::array<T, 2> data; struct { T x, y; }; }; }; template <typename T> struct VectorBase<3, T> { union { std::array<T, 3> data; struct { T x, y, z; }; }; }; template <typename T> struct VectorBase<4, T> { union { std::array<T, 4> data; struct { T x, y, z, w; }; }; }; } template <size_t N, typename T> struct Vector : detail::VectorBase<N, T> { Vector(); Vector(const Vector& other); Vector(Vector&& other) noexcept; template <typename...Args> Vector(Args...args); ~Vector() noexcept; Vector<N, T>& normalize() noexcept; T getNorm() const noexcept; Vector<N, T> getNormalized() const noexcept; Vector<N, T> operator +(const Vector<N, T>& arg) const; Vector<N, T> operator -(const Vector<N, T>& arg) const; Vector<N, T> operator *(const Vector<N, T>& arg) const; Vector<N, T> operator /(const Vector<N, T>& arg) const; Vector<N, T> operator +(T arg) const; Vector<N, T> operator -(T arg) const; Vector<N, T> operator *(T arg) const; Vector<N, T> operator /(T arg) const; Vector<N, T>& operator +=(const Vector<N, T>& arg); Vector<N, T>& operator -=(const Vector<N, T>& arg); Vector<N, T>& operator *=(const Vector<N, T>& arg); Vector<N, T>& operator /=(const Vector<N, T>& arg); Vector<N, T>& operator +=(T arg); Vector<N, T>& operator -=(T arg); Vector<N, T>& operator *=(T arg); Vector<N, T>& operator /=(T arg); Vector<N, T>& operator ++(); Vector<N, T> operator ++(int); Vector<N, T>& operator --(); Vector<N, T> operator --(int); Vector<N, T> operator+() const; Vector<N, T> operator-() const; Vector& operator=(const Vector& other); Vector& operator=(Vector&& other) noexcept; bool operator==(const Vector<N, T>& other) const; bool operator!=(const Vector<N, T>& other) const; T& operator[](size_t index); const T& operator[](size_t index) const; T dot(const Vector<N, T>& other) const; T angle(const Vector<N, T>& other) const; }; template <typename T> using Vector2 = Vector<2, T>; template <typename T> using Vector3 = Vector<3, T>; template <typename T> using Vector4 = Vector<4, T>; using Vector2i = Vector2<int>; using Vector2u = Vector2<unsigned>; using Vector2f = Vector2<float>; using Vector2d = Vector2<double>; using Vector3i = Vector3<int>; using Vector3u = Vector3<unsigned>; using Vector3f = Vector3<float>; using Vector3d = Vector3<double>; using Vector4i = Vector4<int>; using Vector4u = Vector4<unsigned>; using Vector4f = Vector4<float>; using Vector4d = Vector4<double>; template <typename T> Vector3<T> cross(const Vector2<T>& v1, const Vector2<T>& v2) { T z = v1.x * v2.y - v1.y * v2.x; return (Vector3<T>(0, 0, z)); } template <typename T> Vector3<T> cross(const Vector3<T>& v1, const Vector3<T>& v2) { Vector3<T> tmp; tmp.x = v1.y * v2.z - v1.z * v2.y; tmp.y = v1.z * v2.x - v1.x * v2.z; tmp.z = v1.x * v2.y - v1.y * v2.x; return (tmp); } } namespace std { template <size_t N, typename T> struct hash<at::Vector<N, T>> { std::size_t operator()(const at::Vector<N, T>& object) const { return at::Hasher<at::DefaultHashFunction<std::size_t>>::hash(object); } }; } #include <Atema/Math/Vector.inl> #endif<|endoftext|>
<commit_before>// Copyright Joshua Boyce 2010-2012. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // This file is part of HadesMem. // <http://www.raptorfactor.com/> <[email protected]> #include "hadesmem/injector.hpp" #define BOOST_TEST_MODULE alloc #include "hadesmem/detail/warning_disable_prefix.hpp" #include <boost/test/unit_test.hpp> #include "hadesmem/detail/warning_disable_suffix.hpp" #include "hadesmem/error.hpp" #include "hadesmem/process.hpp" #include "hadesmem/detail/self_path.hpp" // Boost.Test causes the following warning under GCC: // error: base class 'struct boost::unit_test::ut_detail::nil_t' has a // non-virtual destructor [-Werror=effc++] #if defined(HADESMEM_GCC) #pragma GCC diagnostic ignored "-Weffc++" #endif // #if defined(HADESMEM_GCC) BOOST_AUTO_TEST_CASE(injector) { hadesmem::Process const process(::GetCurrentProcessId()); HMODULE const kernel32_mod = GetModuleHandle(L"kernel32.dll"); BOOST_REQUIRE(kernel32_mod != nullptr); // 'Inject' Kernel32 with path resolution disabled and ensure that the // module handle matches the one retrieved via GetModuleHandle earlier. HMODULE const kernel32_mod_new = hadesmem::InjectDll(process, L"kernel32.dll", hadesmem::InjectFlags::kNone); BOOST_CHECK_EQUAL(kernel32_mod, kernel32_mod_new); // Call Kernel32.dll!FreeLibrary and ensure the return value and // last error code are their expected values. std::pair<DWORD_PTR, DWORD> const export_ret = CallExport(process, kernel32_mod_new, "FreeLibrary", kernel32_mod_new); BOOST_CHECK_NE(export_ret.first, static_cast<DWORD_PTR>(0)); BOOST_CHECK_EQUAL(export_ret.second, 0UL); // Perform injection test again so we can test the FreeDll API. HMODULE const kernel32_mod_new_2 = hadesmem::InjectDll(process, L"kernel32.dll", hadesmem::InjectFlags::kNone); BOOST_CHECK_EQUAL(kernel32_mod, kernel32_mod_new_2); // Free kernel32.dll in remote process. hadesmem::FreeDll(process, kernel32_mod_new_2); // Todo: Test path resolution. // TODO: Test export calling in CreateAndInject. // TODO: Test work dir, args, etc in CreateAndInject. hadesmem::CreateAndInjectData const inject_data = hadesmem::CreateAndInject( hadesmem::detail::GetSelfPath(), L"", std::vector<std::wstring>(), L"d3d9.dll", "", nullptr, hadesmem::InjectFlags::kNone); BOOL const terminated = ::TerminateProcess( inject_data.GetProcess().GetHandle(), 0); DWORD const last_error = ::GetLastError(); BOOST_CHECK_NE(terminated, 0); if (!terminated) { BOOST_CHECK_NE(last_error, 0UL); } } <commit_msg>* Fix test name.<commit_after>// Copyright Joshua Boyce 2010-2012. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // This file is part of HadesMem. // <http://www.raptorfactor.com/> <[email protected]> #include "hadesmem/injector.hpp" #define BOOST_TEST_MODULE injector #include "hadesmem/detail/warning_disable_prefix.hpp" #include <boost/test/unit_test.hpp> #include "hadesmem/detail/warning_disable_suffix.hpp" #include "hadesmem/error.hpp" #include "hadesmem/process.hpp" #include "hadesmem/detail/self_path.hpp" // Boost.Test causes the following warning under GCC: // error: base class 'struct boost::unit_test::ut_detail::nil_t' has a // non-virtual destructor [-Werror=effc++] #if defined(HADESMEM_GCC) #pragma GCC diagnostic ignored "-Weffc++" #endif // #if defined(HADESMEM_GCC) BOOST_AUTO_TEST_CASE(injector) { hadesmem::Process const process(::GetCurrentProcessId()); HMODULE const kernel32_mod = GetModuleHandle(L"kernel32.dll"); BOOST_REQUIRE(kernel32_mod != nullptr); // 'Inject' Kernel32 with path resolution disabled and ensure that the // module handle matches the one retrieved via GetModuleHandle earlier. HMODULE const kernel32_mod_new = hadesmem::InjectDll(process, L"kernel32.dll", hadesmem::InjectFlags::kNone); BOOST_CHECK_EQUAL(kernel32_mod, kernel32_mod_new); // Call Kernel32.dll!FreeLibrary and ensure the return value and // last error code are their expected values. std::pair<DWORD_PTR, DWORD> const export_ret = CallExport(process, kernel32_mod_new, "FreeLibrary", kernel32_mod_new); BOOST_CHECK_NE(export_ret.first, static_cast<DWORD_PTR>(0)); BOOST_CHECK_EQUAL(export_ret.second, 0UL); // Perform injection test again so we can test the FreeDll API. HMODULE const kernel32_mod_new_2 = hadesmem::InjectDll(process, L"kernel32.dll", hadesmem::InjectFlags::kNone); BOOST_CHECK_EQUAL(kernel32_mod, kernel32_mod_new_2); // Free kernel32.dll in remote process. hadesmem::FreeDll(process, kernel32_mod_new_2); // Todo: Test path resolution. // TODO: Test export calling in CreateAndInject. // TODO: Test work dir, args, etc in CreateAndInject. hadesmem::CreateAndInjectData const inject_data = hadesmem::CreateAndInject( hadesmem::detail::GetSelfPath(), L"", std::vector<std::wstring>(), L"d3d9.dll", "", nullptr, hadesmem::InjectFlags::kNone); BOOL const terminated = ::TerminateProcess( inject_data.GetProcess().GetHandle(), 0); DWORD const last_error = ::GetLastError(); BOOST_CHECK_NE(terminated, 0); if (!terminated) { BOOST_CHECK_NE(last_error, 0UL); } } <|endoftext|>
<commit_before>// // Copyright (c) 2013-2017 Ian Godin and Kimball Thurston // All rights reserved. // Copyrights licensed under the MIT License. // See the accompanying LICENSE.txt file for terms // #include "system.h" #include "screen.h" #include "window.h" #include "dispatcher.h" #include <platform/platform.h> #include <base/contract.h> #include <base/env.h> #include <stdexcept> //////////////////////////////////////// namespace { int xErrorCB( Display *d, XErrorEvent *e ) { char errorBuf[4096]; XGetErrorText( d, e->error_code, errorBuf, 4096 ); std::cerr << "ERROR: Xlib Error" << "\n Major/Minor: " << int(e->request_code) << " / " << int(e->minor_code) << "\n Error code: " << int(e->error_code) << "\n Message: " << errorBuf << std::endl; return 0; } int xIOErrorCB( Display * ) { std::cerr << "ERROR: I/O error w/ X server (connection lost?)" << std::endl; exit( -1 ); } } namespace platform { namespace xlib { //////////////////////////////////////// system::system( const std::string &d ) : ::platform::system( "x11", "X11/XLib" ) { const char *dname = nullptr; if ( ! d.empty() ) dname = d.c_str(); std::string disenv = base::env::global().get( "DISPLAY" ); if ( ! dname && ! disenv.empty() ) dname = disenv.c_str(); XSetErrorHandler( &xErrorCB ); XSetIOErrorHandler( &xIOErrorCB ); _display.reset( XOpenDisplay( dname ), &XCloseDisplay ); if ( ! _display ) { if ( dname ) throw std::runtime_error( "Unable to connect to display '" + std::string( dname ) + "'" ); throw std::runtime_error( "no X display" ); } if ( ! XSupportsLocale() ) throw std::runtime_error( "Current locale not supported by X" ); if ( XSetLocaleModifiers( "@im=none" ) == nullptr ) throw std::runtime_error( "Unable to set locale modifiers for Xlib" ); _screens.resize( static_cast<size_t>( ScreenCount( _display.get() ) ) ); for ( int i = 0; i < ScreenCount( _display.get() ); ++i ) _screens[0] = std::make_shared<screen>( _display, i ); // don't have a good way to identify individual keyboards // in raw xlib? _keyboard = std::make_shared<keyboard>(); // don't have a good way to identify individual keyboards // in raw xlib? _mouse = std::make_shared<mouse>(); _dispatcher = std::make_shared<dispatcher>( _display, _keyboard, _mouse ); // _dispatcher->add_waitable( _keyboard ); // _dispatcher->add_waitable( _mouse ); } //////////////////////////////////////// system::~system( void ) { } //////////////////////////////////////// std::shared_ptr<::platform::window> system::new_window( void ) { auto ret = std::make_shared<window>( _display ); _dispatcher->add_window( ret ); return ret; } //////////////////////////////////////// std::shared_ptr<::platform::dispatcher> system::get_dispatcher( void ) { return _dispatcher; } //////////////////////////////////////// std::shared_ptr<::platform::keyboard> system::get_keyboard( void ) { return _keyboard; } //////////////////////////////////////// std::shared_ptr<::platform::mouse> system::get_mouse( void ) { return _mouse; } //////////////////////////////////////// } } <commit_msg>Fixed crash when X11 can't connect.<commit_after>// // Copyright (c) 2013-2017 Ian Godin and Kimball Thurston // All rights reserved. // Copyrights licensed under the MIT License. // See the accompanying LICENSE.txt file for terms // #include "system.h" #include "screen.h" #include "window.h" #include "dispatcher.h" #include <platform/platform.h> #include <base/contract.h> #include <base/env.h> #include <stdexcept> //////////////////////////////////////// namespace { int xErrorCB( Display *d, XErrorEvent *e ) { char errorBuf[4096]; XGetErrorText( d, e->error_code, errorBuf, 4096 ); std::cerr << "ERROR: Xlib Error" << "\n Major/Minor: " << int(e->request_code) << " / " << int(e->minor_code) << "\n Error code: " << int(e->error_code) << "\n Message: " << errorBuf << std::endl; return 0; } int xIOErrorCB( Display * ) { std::cerr << "ERROR: I/O error w/ X server (connection lost?)" << std::endl; exit( -1 ); } void CloseDisplay( Display *disp ) { if ( disp != nullptr ) XCloseDisplay( disp ); } } namespace platform { namespace xlib { //////////////////////////////////////// system::system( const std::string &d ) : ::platform::system( "x11", "X11/XLib" ) { const char *dname = nullptr; if ( ! d.empty() ) dname = d.c_str(); std::string disenv = base::env::global().get( "DISPLAY" ); if ( ! dname && ! disenv.empty() ) dname = disenv.c_str(); XSetErrorHandler( &xErrorCB ); XSetIOErrorHandler( &xIOErrorCB ); _display.reset( XOpenDisplay( dname ), &CloseDisplay ); if ( ! _display ) { if ( dname ) throw std::runtime_error( "Unable to connect to display '" + std::string( dname ) + "'" ); throw std::runtime_error( "no X display" ); } if ( ! XSupportsLocale() ) throw std::runtime_error( "Current locale not supported by X" ); if ( XSetLocaleModifiers( "@im=none" ) == nullptr ) throw std::runtime_error( "Unable to set locale modifiers for Xlib" ); _screens.resize( static_cast<size_t>( ScreenCount( _display.get() ) ) ); for ( int i = 0; i < ScreenCount( _display.get() ); ++i ) _screens[0] = std::make_shared<screen>( _display, i ); // don't have a good way to identify individual keyboards // in raw xlib? _keyboard = std::make_shared<keyboard>(); // don't have a good way to identify individual keyboards // in raw xlib? _mouse = std::make_shared<mouse>(); _dispatcher = std::make_shared<dispatcher>( _display, _keyboard, _mouse ); // _dispatcher->add_waitable( _keyboard ); // _dispatcher->add_waitable( _mouse ); } //////////////////////////////////////// system::~system( void ) { } //////////////////////////////////////// std::shared_ptr<::platform::window> system::new_window( void ) { auto ret = std::make_shared<window>( _display ); _dispatcher->add_window( ret ); return ret; } //////////////////////////////////////// std::shared_ptr<::platform::dispatcher> system::get_dispatcher( void ) { return _dispatcher; } //////////////////////////////////////// std::shared_ptr<::platform::keyboard> system::get_keyboard( void ) { return _keyboard; } //////////////////////////////////////// std::shared_ptr<::platform::mouse> system::get_mouse( void ) { return _mouse; } //////////////////////////////////////// } } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: CustomAnimationCloner.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: rt $ $Date: 2005-09-09 02:50:26 $ * * 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 _SD_CUSTOMANIMATIONCLONER_HXX #define _SD_CUSTOMANIMATIONCLONER_HXX #ifndef _COM_SUN_STAR_ANIMATIONS_XANIMATIONNODE_HPP_ #include <com/sun/star/animations/XAnimationNode.hpp> #endif class SdPage; namespace sd { ::com::sun::star::uno::Reference< ::com::sun::star::animations::XAnimationNode > Clone( const ::com::sun::star::uno::Reference< ::com::sun::star::animations::XAnimationNode >& xSourceNode, const SdPage* pSource = 0, const SdPage* pTarget = 0 ); } #endif // _SD_CUSTOMANIMATIONCLONER_HXX <commit_msg>INTEGRATION: CWS changefileheader (1.3.624); FILE MERGED 2008/04/01 12:38:21 thb 1.3.624.2: #i85898# Stripping all external header guards 2008/03/31 13:56:39 rt 1.3.624.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: CustomAnimationCloner.hxx,v $ * $Revision: 1.4 $ * * 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 _SD_CUSTOMANIMATIONCLONER_HXX #define _SD_CUSTOMANIMATIONCLONER_HXX #include <com/sun/star/animations/XAnimationNode.hpp> class SdPage; namespace sd { ::com::sun::star::uno::Reference< ::com::sun::star::animations::XAnimationNode > Clone( const ::com::sun::star::uno::Reference< ::com::sun::star::animations::XAnimationNode >& xSourceNode, const SdPage* pSource = 0, const SdPage* pTarget = 0 ); } #endif // _SD_CUSTOMANIMATIONCLONER_HXX <|endoftext|>
<commit_before>#include "mex.h" #include <iostream> #include "drakeUtil.h" #include "RigidBodyManipulator.h" #include "math.h" #include <sstream> using namespace Eigen; using namespace std; #define BIG 1e20 inline void getInclusionIndices(vector<bool> const & inclusion, vector<size_t> & indices, bool get_true_indices) { const size_t n = inclusion.size(); indices.clear(); for (size_t x = 0; x < n; x++) { if (inclusion[x] == get_true_indices) { indices.push_back(x); } } } template <typename Derived> inline void getThresholdInclusion(MatrixBase<Derived> const &values, const double threshold, vector<bool> & below_threshold) { const size_t n = values.size(); below_threshold.clear(); for (size_t x = 0; x < n; x++) { below_threshold.push_back(values[x] < threshold); } } //counts number of inclusions inline size_t getNumTrue(vector<bool> const & bools) { size_t count = 0; const size_t n = bools.size(); for (size_t x = 0; x < n; x++) { if (bools[x]) { count++; } } return count; } //splits a vector into two based on inclusion mapping inline void partitionVector(vector<bool> const &indices, VectorXd const & v, VectorXd & included, VectorXd & excluded) { const size_t n = indices.size(); const size_t count = getNumTrue(indices); included = VectorXd::Zero(count); excluded = VectorXd::Zero(n-count); size_t inclusionIndex = 0; size_t exclusionIndex = 0; for (size_t x = 0; x < n; x++) { if (indices[x]) { included[inclusionIndex++] = v[x]; } else { excluded[exclusionIndex++] = v[x]; } } } //splits a matrix into two based on a row inclusion mapping inline void partitionMatrix(vector<bool> const &indices, MatrixXd const & M, MatrixXd & included, MatrixXd & excluded) { const size_t n = indices.size(); const size_t count = getNumTrue(indices); const size_t cols = M.cols(); included = MatrixXd::Zero(count, cols); excluded = MatrixXd::Zero(n-count, cols); size_t inclusionIndex = 0; size_t exclusionIndex = 0; for (size_t x = 0; x < n; x++) { if (indices[x]) { included.row(inclusionIndex++) = M.row(x); } else { excluded.row(exclusionIndex++) = M.row(x); } } } //builds a filtered matrix containing only the rows specified by indices inline void filterByIndices(vector<size_t> const &indices, MatrixXd const & M, MatrixXd & filtered) { const size_t n = indices.size(); filtered = MatrixXd::Zero(n, M.cols()); for (size_t x = 0; x < n; x++) { filtered.row(x) = M.row(indices[x]); } } //[z, Mqdn, wqdn] = setupLCPmex(mex_model_ptr, q, qd, u, phiC, n, D, h, z_inactive_guess_tol) void mexFunction(int nlhs, mxArray *plhs[],int nrhs, const mxArray *prhs[] ) { if (nlhs != 3 || nrhs != 9) { mexErrMsgIdAndTxt("Drake:setupLCPmex:InvalidUsage","Usage: [z, Mqdn, wqdn] = setupLCPmex(mex_model_ptr, q, qd, u, phiC, n, D, h, z_inactive_guess_tol)"); } RigidBodyManipulator *model= (RigidBodyManipulator*) getDrakeMexPointer(prhs[0]); const int nq = model->num_positions; const int nv = model->num_velocities; //input mappings const mxArray* q_array = prhs[1]; const mxArray* v_array = prhs[2]; const mxArray* u_array = prhs[3]; const mxArray* phiC_array = prhs[4]; const mxArray* n_array = prhs[5]; const mxArray* D_array = prhs[6]; const mxArray* h_array = prhs[7]; const mxArray* inactive_guess_array = prhs[8]; const size_t numContactPairs = mxGetNumberOfElements(phiC_array); const size_t mC = mxGetNumberOfElements(D_array); const double z_inactive_guess_tol = static_cast<double>(mxGetScalar(inactive_guess_array)); const double h = static_cast<double>(mxGetScalar(h_array)); const Map<VectorXd> q(mxGetPr(q_array),nq); const Map<VectorXd> v(mxGetPr(v_array),nv); const Map<VectorXd> u(mxGetPr(u_array),model->B.cols()); const Map<VectorXd> phiC(mxGetPr(phiC_array),numContactPairs); const Map<MatrixXd> n(mxGetPr(n_array), numContactPairs, nq); VectorXd C, phiL, phiP, phiL_possible, phiC_possible, phiL_check, phiC_check; MatrixXd H, B, JP, JL, JL_possible, n_possible, JL_check, n_check; H.resize(nv, nv); C = VectorXd::Zero(nv); B = model->B; model->HandC(q, v, (MatrixXd*)nullptr, H, C, (MatrixXd*)nullptr, (MatrixXd*)nullptr, (MatrixXd*)nullptr); model->positionConstraints(phiP, JP); model->jointLimitConstraints(q, phiL, JL); MatrixXd Hinv = H.inverse(); const size_t nP = phiP.size(); plhs[2] = mxCreateDoubleMatrix(nq, 1, mxREAL); Map<VectorXd> wqdn(mxGetPr(plhs[2]), nq); wqdn = v + h * Hinv * (B * u - C); //use forward euler step in joint space as //initial guess for active constraints vector<bool> possible_contact; vector<bool> possible_jointlimit; getThresholdInclusion(phiC + h * n * v, z_inactive_guess_tol, possible_contact); getThresholdInclusion(phiL + h * JL * v, z_inactive_guess_tol, possible_jointlimit); while (true) { //continue from here if our inactive guess fails const size_t nC = getNumTrue(possible_contact); const size_t nL = getNumTrue(possible_jointlimit); const size_t lcp_size = nL + nP + (mC + 2) * nC; vector<size_t> possible_contact_indices; getInclusionIndices(possible_contact, possible_contact_indices, true); partitionVector(possible_contact, phiC, phiC_possible, phiC_check); partitionVector(possible_jointlimit, phiL, phiL_possible, phiL_check); partitionMatrix(possible_contact, n, n_possible, n_check); partitionMatrix(possible_jointlimit, JL, JL_possible, JL_check); MatrixXd D_possible(mC * nC, nq); for (size_t i = 0; i < mC ; i++) { Map<MatrixXd> D_i(mxGetPr(mxGetCell(D_array, i)), numContactPairs , nq); MatrixXd D_i_possible, D_i_exclude; filterByIndices(possible_contact_indices, D_i, D_i_possible); D_possible.block(nC * i, 0, nC, nq) = D_i_possible; } MatrixXd J(lcp_size, nq); J << JL_possible, JP, n_possible, D_possible, MatrixXd::Zero(nC, nq); plhs[0] = mxCreateDoubleMatrix(lcp_size, 1, mxREAL); plhs[1] = mxCreateDoubleMatrix(nq, lcp_size, mxREAL); Map<VectorXd> z(mxGetPr(plhs[0]), lcp_size); Map<MatrixXd> Mqdn(mxGetPr(plhs[1]), nq, lcp_size); Mqdn = Hinv*J.transpose(); //solve LCP problem //TODO: call fastQP first //TODO: call path from C++ (currently only 32-bit C libraries available) mxArray* mxM = mxCreateDoubleMatrix(lcp_size, lcp_size, mxREAL); mxArray* mxw = mxCreateDoubleMatrix(lcp_size, 1, mxREAL); mxArray* mxlb = mxCreateDoubleMatrix(lcp_size, 1, mxREAL); mxArray* mxub = mxCreateDoubleMatrix(lcp_size, 1, mxREAL); Map<VectorXd> lb(mxGetPr(mxlb), lcp_size); Map<VectorXd> ub(mxGetPr(mxub), lcp_size); lb << VectorXd::Zero(nL), -BIG * VectorXd::Ones(nP), VectorXd::Zero(nC + mC * nC + nC); ub = BIG * VectorXd::Ones(lcp_size); Map<MatrixXd> M(mxGetPr(mxM),lcp_size, lcp_size); Map<VectorXd> w(mxGetPr(mxw), lcp_size); //build LCP matrix M << h * JL_possible*Mqdn, h * JP * Mqdn, h * n_possible * Mqdn, D_possible * Mqdn, MatrixXd::Zero(nC, lcp_size); if (nC > 0) { for (size_t i = 0; i < mC ; i++) { M.block(nL + nP + nC + nC * i, nL + nP + nC + mC * nC, nC, nC) = MatrixXd::Identity(nC, nC); M.block(nL + nP + nC + mC*nC, nL + nP + nC + nC * i, nC, nC) = -MatrixXd::Identity(nC, nC); } double mu = 1.0; //TODO: pull this from contactConstraints M.block(nL + nP + nC + mC * nC, nL + nP, nC, nC) = mu * MatrixXd::Identity(nC, nC); } //build LCP vector w << phiL_possible + h * JL_possible * wqdn, phiP + h * JP * wqdn, phiC_possible + h * n_possible * wqdn, D_possible * wqdn, VectorXd::Zero(nC); mxArray *lhs[1]; mxArray *rhs[] = {mxM, mxw, mxlb, mxub}; //call solver mexCallMATLAB(1, lhs, 4, rhs, "pathlcp"); Map<VectorXd> z_path(mxGetPr(lhs[0]), lcp_size); z = z_path; //clean up mxDestroyArray(lhs[0]); mxDestroyArray(mxlb); mxDestroyArray(mxub); mxDestroyArray(mxM); mxDestroyArray(mxw); VectorXd qdn = Mqdn * z + wqdn; vector<size_t> impossible_contact_indices, impossible_limit_indices; getInclusionIndices(possible_contact, impossible_contact_indices, false); getInclusionIndices(possible_jointlimit, impossible_limit_indices, false); vector<bool> penetrating_joints, penetrating_contacts; getThresholdInclusion(phiL_check + h * JL_check * qdn, 0.0, penetrating_joints); getThresholdInclusion(phiC_check + h * n_check * qdn, 0.0, penetrating_contacts); const size_t num_penetrating_joints = getNumTrue(penetrating_joints); const size_t num_penetrating_contacts = getNumTrue(penetrating_contacts); const size_t penetrations = num_penetrating_joints + num_penetrating_contacts; //check nonpenetration assumptions if (penetrations > 0) { //revise joint limit active set for (size_t i = 0; i < impossible_limit_indices.size(); i++) { if (penetrating_joints[i]) { possible_jointlimit[impossible_limit_indices[i]] = true; } } //revise contact constraint active set for (size_t i = 0; i < impossible_contact_indices.size(); i++) { if (penetrating_contacts[i]) { possible_contact[impossible_contact_indices[i]] = true; } } //throw away our old solution and try again mxDestroyArray(plhs[0]); mxDestroyArray(plhs[1]); continue; } //our initial guess was correct. we're done break; } } <commit_msg>re-added a fix I lost during cleanup<commit_after>#include "mex.h" #include <iostream> #include "drakeUtil.h" #include "RigidBodyManipulator.h" #include "math.h" #include <sstream> using namespace Eigen; using namespace std; #define BIG 1e20 inline void getInclusionIndices(vector<bool> const & inclusion, vector<size_t> & indices, bool get_true_indices) { const size_t n = inclusion.size(); indices.clear(); for (size_t x = 0; x < n; x++) { if (inclusion[x] == get_true_indices) { indices.push_back(x); } } } template <typename Derived> inline void getThresholdInclusion(MatrixBase<Derived> const & values, const double threshold, vector<bool> & below_threshold) { const size_t n = values.size(); below_threshold.clear(); for (size_t x = 0; x < n; x++) { below_threshold.push_back(values[x] < threshold); } } //counts number of inclusions inline size_t getNumTrue(vector<bool> const & bools) { size_t count = 0; const size_t n = bools.size(); for (size_t x = 0; x < n; x++) { if (bools[x]) { count++; } } return count; } //splits a vector into two based on inclusion mapping inline void partitionVector(vector<bool> const & indices, VectorXd const & v, VectorXd & included, VectorXd & excluded) { const size_t n = indices.size(); const size_t count = getNumTrue(indices); included = VectorXd::Zero(count); excluded = VectorXd::Zero(n - count); size_t inclusionIndex = 0; size_t exclusionIndex = 0; for (size_t x = 0; x < n; x++) { if (indices[x]) { included[inclusionIndex++] = v[x]; } else { excluded[exclusionIndex++] = v[x]; } } } //splits a matrix into two based on a row inclusion mapping inline void partitionMatrix(vector<bool> const & indices, MatrixXd const & M, MatrixXd & included, MatrixXd & excluded) { const size_t n = indices.size(); const size_t count = getNumTrue(indices); const size_t cols = M.cols(); included = MatrixXd::Zero(count, cols); excluded = MatrixXd::Zero(n-count, cols); size_t inclusionIndex = 0; size_t exclusionIndex = 0; for (size_t x = 0; x < n; x++) { if (indices[x]) { included.row(inclusionIndex++) = M.row(x); } else { excluded.row(exclusionIndex++) = M.row(x); } } } //builds a filtered matrix containing only the rows specified by indices inline void filterByIndices(vector<size_t> const &indices, MatrixXd const & M, MatrixXd & filtered) { const size_t n = indices.size(); filtered = MatrixXd::Zero(n, M.cols()); for (size_t x = 0; x < n; x++) { filtered.row(x) = M.row(indices[x]); } } //[z, Mqdn, wqdn] = setupLCPmex(mex_model_ptr, q, qd, u, phiC, n, D, h, z_inactive_guess_tol) void mexFunction(int nlhs, mxArray *plhs[],int nrhs, const mxArray *prhs[] ) { if (nlhs != 3 || nrhs != 9) { mexErrMsgIdAndTxt("Drake:setupLCPmex:InvalidUsage","Usage: [z, Mqdn, wqdn] = setupLCPmex(mex_model_ptr, q, qd, u, phiC, n, D, h, z_inactive_guess_tol)"); } RigidBodyManipulator *model= (RigidBodyManipulator*) getDrakeMexPointer(prhs[0]); const int nq = model->num_positions; const int nv = model->num_velocities; //input mappings const mxArray* q_array = prhs[1]; const mxArray* v_array = prhs[2]; const mxArray* u_array = prhs[3]; const mxArray* phiC_array = prhs[4]; const mxArray* n_array = prhs[5]; const mxArray* D_array = prhs[6]; const mxArray* h_array = prhs[7]; const mxArray* inactive_guess_array = prhs[8]; const size_t numContactPairs = mxGetNumberOfElements(phiC_array); const size_t mC = mxGetNumberOfElements(D_array); const double z_inactive_guess_tol = static_cast<double>(mxGetScalar(inactive_guess_array)); const double h = static_cast<double>(mxGetScalar(h_array)); const Map<VectorXd> q(mxGetPr(q_array),nq); const Map<VectorXd> v(mxGetPr(v_array),nv); const Map<VectorXd> u(mxGetPr(u_array),model->B.cols()); const Map<VectorXd> phiC(mxGetPr(phiC_array),numContactPairs); const Map<MatrixXd> n(mxGetPr(n_array), numContactPairs, nq); VectorXd C, phiL, phiP, phiL_possible, phiC_possible, phiL_check, phiC_check; MatrixXd H, B, JP, JL, JL_possible, n_possible, JL_check, n_check; H.resize(nv, nv); C = VectorXd::Zero(nv); B = model->B; model->HandC(q, v, (MatrixXd*)nullptr, H, C, (MatrixXd*)nullptr, (MatrixXd*)nullptr, (MatrixXd*)nullptr); model->positionConstraints(phiP, JP); model->jointLimitConstraints(q, phiL, JL); MatrixXd Hinv = H.inverse(); const size_t nP = phiP.size(); plhs[2] = mxCreateDoubleMatrix(nq, 1, mxREAL); Map<VectorXd> wqdn(mxGetPr(plhs[2]), nq); wqdn = v + h * Hinv * (B * u - C); //use forward euler step in joint space as //initial guess for active constraints vector<bool> possible_contact; vector<bool> possible_jointlimit; getThresholdInclusion(phiC + h * n * v, z_inactive_guess_tol, possible_contact); getThresholdInclusion(phiL + h * JL * v, z_inactive_guess_tol, possible_jointlimit); while (true) { //continue from here if our inactive guess fails const size_t nC = getNumTrue(possible_contact); const size_t nL = getNumTrue(possible_jointlimit); const size_t lcp_size = nL + nP + (mC + 2) * nC; plhs[0] = mxCreateDoubleMatrix(lcp_size, 1, mxREAL); plhs[1] = mxCreateDoubleMatrix(nq, lcp_size, mxREAL); Map<VectorXd> z(mxGetPr(plhs[0]), lcp_size); Map<MatrixXd> Mqdn(mxGetPr(plhs[1]), nq, lcp_size); if (lcp_size == 0) { return; } vector<size_t> possible_contact_indices; getInclusionIndices(possible_contact, possible_contact_indices, true); partitionVector(possible_contact, phiC, phiC_possible, phiC_check); partitionVector(possible_jointlimit, phiL, phiL_possible, phiL_check); partitionMatrix(possible_contact, n, n_possible, n_check); partitionMatrix(possible_jointlimit, JL, JL_possible, JL_check); MatrixXd D_possible(mC * nC, nq); for (size_t i = 0; i < mC ; i++) { Map<MatrixXd> D_i(mxGetPr(mxGetCell(D_array, i)), numContactPairs , nq); MatrixXd D_i_possible, D_i_exclude; filterByIndices(possible_contact_indices, D_i, D_i_possible); D_possible.block(nC * i, 0, nC, nq) = D_i_possible; } MatrixXd J(lcp_size, nq); J << JL_possible, JP, n_possible, D_possible, MatrixXd::Zero(nC, nq); Mqdn = Hinv*J.transpose(); //solve LCP problem //TODO: call fastQP first //TODO: call path from C++ (currently only 32-bit C libraries available) mxArray* mxM = mxCreateDoubleMatrix(lcp_size, lcp_size, mxREAL); mxArray* mxw = mxCreateDoubleMatrix(lcp_size, 1, mxREAL); mxArray* mxlb = mxCreateDoubleMatrix(lcp_size, 1, mxREAL); mxArray* mxub = mxCreateDoubleMatrix(lcp_size, 1, mxREAL); Map<VectorXd> lb(mxGetPr(mxlb), lcp_size); Map<VectorXd> ub(mxGetPr(mxub), lcp_size); lb << VectorXd::Zero(nL), -BIG * VectorXd::Ones(nP), VectorXd::Zero(nC + mC * nC + nC); ub = BIG * VectorXd::Ones(lcp_size); Map<MatrixXd> M(mxGetPr(mxM),lcp_size, lcp_size); Map<VectorXd> w(mxGetPr(mxw), lcp_size); //build LCP matrix M << h * JL_possible*Mqdn, h * JP * Mqdn, h * n_possible * Mqdn, D_possible * Mqdn, MatrixXd::Zero(nC, lcp_size); if (nC > 0) { for (size_t i = 0; i < mC ; i++) { M.block(nL + nP + nC + nC * i, nL + nP + nC + mC * nC, nC, nC) = MatrixXd::Identity(nC, nC); M.block(nL + nP + nC + mC*nC, nL + nP + nC + nC * i, nC, nC) = -MatrixXd::Identity(nC, nC); } double mu = 1.0; //TODO: pull this from contactConstraints M.block(nL + nP + nC + mC * nC, nL + nP, nC, nC) = mu * MatrixXd::Identity(nC, nC); } //build LCP vector w << phiL_possible + h * JL_possible * wqdn, phiP + h * JP * wqdn, phiC_possible + h * n_possible * wqdn, D_possible * wqdn, VectorXd::Zero(nC); mxArray *lhs[1]; mxArray *rhs[] = {mxM, mxw, mxlb, mxub}; //call solver mexCallMATLAB(1, lhs, 4, rhs, "pathlcp"); Map<VectorXd> z_path(mxGetPr(lhs[0]), lcp_size); z = z_path; //clean up mxDestroyArray(lhs[0]); mxDestroyArray(mxlb); mxDestroyArray(mxub); mxDestroyArray(mxM); mxDestroyArray(mxw); VectorXd qdn = Mqdn * z + wqdn; vector<size_t> impossible_contact_indices, impossible_limit_indices; getInclusionIndices(possible_contact, impossible_contact_indices, false); getInclusionIndices(possible_jointlimit, impossible_limit_indices, false); vector<bool> penetrating_joints, penetrating_contacts; getThresholdInclusion(phiL_check + h * JL_check * qdn, 0.0, penetrating_joints); getThresholdInclusion(phiC_check + h * n_check * qdn, 0.0, penetrating_contacts); const size_t num_penetrating_joints = getNumTrue(penetrating_joints); const size_t num_penetrating_contacts = getNumTrue(penetrating_contacts); const size_t penetrations = num_penetrating_joints + num_penetrating_contacts; //check nonpenetration assumptions if (penetrations > 0) { //revise joint limit active set for (size_t i = 0; i < impossible_limit_indices.size(); i++) { if (penetrating_joints[i]) { possible_jointlimit[impossible_limit_indices[i]] = true; } } //revise contact constraint active set for (size_t i = 0; i < impossible_contact_indices.size(); i++) { if (penetrating_contacts[i]) { possible_contact[impossible_contact_indices[i]] = true; } } //throw away our old solution and try again mxDestroyArray(plhs[0]); mxDestroyArray(plhs[1]); continue; } //our initial guess was correct. we're done break; } } <|endoftext|>
<commit_before>#include <iostream> #include <cstdio> #include <algorithm> #include <queue> #include <map> #include <set> #include <stack> #include <cstring> #include <string> #include <vector> #include <iomanip> #include <cmath> #include <list> #include <bitset> using namespace std; #define ll long long #define lson l,mid,id<<1 #define rson mid+1,r,id<<1|1 typedef pair<int, int>pii; typedef pair<ll, ll>pll; typedef pair<double, double>pdd; const double eps = 1e-6; const ll LINF = 0x3f3f3f3f3f3f3f3fLL; const int INF = 0x3f3f3f3f; const double FINF = 1e18; #define x first #define y second #define REP(i,j,k) for(int i =(j);i<=(k);i++) #define REPD(i,j,k) for(int i =(j);i>=(k);i--) #define print(x) cout<<(x)<<endl; #define IOS ios::sync_with_stdio(0);cin.tie(0); const int maxn=1000+10; char a[maxn]; int dp[maxn]; int n; void Init(){ scanf("%s",a+1); return ; } void Solve(){ n=strlen(a+1); dp[0]=0; REP(i,1,n) dp[i]=inf; REP(i,1,n) { for(j=i,k=i;j<=n&&k>0;j++,k--) { if(a[j]==a[k]) dp[j]=min(dp[j],dp[k-1]+1); else break; } for(j=i+1,k=i;j<=n&&k>0;j++,k--) { if(a[j]==a[k]) dp[j]=min(dp[j],dp[k-1]+1); else break; } } printf("%d\n",dp[n]); return ; } int main(){ freopen("uoj1154.in","r",stdin); int T; scanf("%d",&T); while(T--) Init(),Solve(); return 0; }<commit_msg>update uoj1154<commit_after>#include <iostream> #include <cstdio> #include <algorithm> #include <queue> #include <map> #include <set> #include <stack> #include <cstring> #include <string> #include <vector> #include <iomanip> #include <cmath> #include <list> #include <bitset> using namespace std; #define ll long long #define lson l,mid,id<<1 #define rson mid+1,r,id<<1|1 typedef pair<int, int>pii; typedef pair<ll, ll>pll; typedef pair<double, double>pdd; const double eps = 1e-6; const ll LINF = 0x3f3f3f3f3f3f3f3fLL; const int INF = 0x3f3f3f3f; const double FINF = 1e18; #define x first #define y second #define REP(i,j,k) for(int i =(j);i<=(k);i++) #define REPD(i,j,k) for(int i =(j);i>=(k);i--) #define print(x) cout<<(x)<<endl; #define IOS ios::sync_with_stdio(0);cin.tie(0); const int maxn=1000+10; char a[maxn]; int dp[maxn]; int k,k,n; void Init(){ scanf("%s",a+1); return ; } void Solve(){ n=strlen(a+1); dp[0]=0; REP(i,1,n) dp[i]=INF; REP(i,1,n) { for(j=i,k=i;j<=n&&k>0;j++,k--) { if(a[j]==a[k]) dp[j]=min(dp[j],dp[k-1]+1); else break; } for(j=i+1,k=i;j<=n&&k>0;j++,k--) { if(a[j]==a[k]) dp[j]=min(dp[j],dp[k-1]+1); else break; } } printf("%d\n",dp[n]); return ; } int main(){ freopen("uoj1154.in","r",stdin); int T; scanf("%d",&T); while(T--) Init(),Solve(); return 0; }<|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: LayerTabBar.hxx,v $ * * $Revision: 1.4 $ * * last change: $Author: rt $ $Date: 2005-09-09 05:07:52 $ * * 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 SD_LAYER_TAB_BAR_HXX #define SD_LAYER_TAB_BAR_HXX #ifndef _TABBAR_HXX #include <svtools/tabbar.hxx> #endif #ifndef _TRANSFER_HXX #include <svtools/transfer.hxx> #endif namespace sd { /************************************************************************* |* |* TabBar fuer die Layerverwaltung |* \************************************************************************/ class DrawViewShell; class LayerTabBar : public TabBar, public DropTargetHelper { public: LayerTabBar ( DrawViewShell* pDrViewSh, ::Window* pParent); LayerTabBar ( DrawViewShell* pDrViewSh, ::Window* pParent, const ResId& rResId); virtual ~LayerTabBar (void); /** Inform all listeners of this control that the current layer has been activated. Call this method after switching the current layer and is not done elsewhere (like when using ctrl + page up/down keys). */ void SendActivatePageEvent (void); /** Inform all listeners of this control that the current layer has been deactivated. Call this method before switching the current layer and is not done elsewhere (like when using ctrl page up/down keys). */ void SendDeactivatePageEvent (void); protected: DrawViewShell* pDrViewSh; // TabBar virtual void Select(); virtual void DoubleClick(); virtual void MouseButtonDown(const MouseEvent& rMEvt); virtual void Command(const CommandEvent& rCEvt); virtual long StartRenaming(); virtual long AllowRenaming(); virtual void EndRenaming(); virtual void ActivatePage(); // DropTargetHelper virtual sal_Int8 AcceptDrop( const AcceptDropEvent& rEvt ); virtual sal_Int8 ExecuteDrop( const ExecuteDropEvent& rEvt ); }; } // end of namespace sd #endif <commit_msg>INTEGRATION: CWS changefileheader (1.4.624); FILE MERGED 2008/04/01 15:35:11 thb 1.4.624.2: #i85898# Stripping all external header guards 2008/03/31 13:58:10 rt 1.4.624.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: LayerTabBar.hxx,v $ * $Revision: 1.5 $ * * 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 SD_LAYER_TAB_BAR_HXX #define SD_LAYER_TAB_BAR_HXX #include <svtools/tabbar.hxx> #include <svtools/transfer.hxx> namespace sd { /************************************************************************* |* |* TabBar fuer die Layerverwaltung |* \************************************************************************/ class DrawViewShell; class LayerTabBar : public TabBar, public DropTargetHelper { public: LayerTabBar ( DrawViewShell* pDrViewSh, ::Window* pParent); LayerTabBar ( DrawViewShell* pDrViewSh, ::Window* pParent, const ResId& rResId); virtual ~LayerTabBar (void); /** Inform all listeners of this control that the current layer has been activated. Call this method after switching the current layer and is not done elsewhere (like when using ctrl + page up/down keys). */ void SendActivatePageEvent (void); /** Inform all listeners of this control that the current layer has been deactivated. Call this method before switching the current layer and is not done elsewhere (like when using ctrl page up/down keys). */ void SendDeactivatePageEvent (void); protected: DrawViewShell* pDrViewSh; // TabBar virtual void Select(); virtual void DoubleClick(); virtual void MouseButtonDown(const MouseEvent& rMEvt); virtual void Command(const CommandEvent& rCEvt); virtual long StartRenaming(); virtual long AllowRenaming(); virtual void EndRenaming(); virtual void ActivatePage(); // DropTargetHelper virtual sal_Int8 AcceptDrop( const AcceptDropEvent& rEvt ); virtual sal_Int8 ExecuteDrop( const ExecuteDropEvent& rEvt ); }; } // end of namespace sd #endif <|endoftext|>
<commit_before>#include "File.h" #include "gtest/gtest.h" #include <random> using namespace joedb; static const uint64_t joedb_magic = 0x0000620165646A6FULL; class File_Test: public::testing::Test { protected: virtual void SetUp() { File file("existing.tmp", Open_Mode::create_new); file.write<uint64_t>(joedb_magic); file.write<bool>(false); file.write<bool>(true); } virtual void TearDown() { std::remove("locked.tmp"); std::remove("existing.tmp"); std::remove("new.tmp"); } }; ///////////////////////////////////////////////////////////////////////////// TEST_F(File_Test, open_failure) { EXPECT_ANY_THROW ( File file("not_existing.tmp", Open_Mode::read_existing) ); EXPECT_ANY_THROW ( File file("not_existing.tmp", Open_Mode::write_existing) ); EXPECT_ANY_THROW ( File file("existing.tmp", Open_Mode::create_new) ); } ///////////////////////////////////////////////////////////////////////////// TEST_F(File_Test, open_lock) { std::remove("locked.tmp"); { File locked_file_1("locked.tmp", Open_Mode::create_new); locked_file_1.write<int>(1234); EXPECT_ANY_THROW ( File locked_file_2("locked.tmp", Open_Mode::write_existing) ); } { File locked_file_1("locked.tmp", Open_Mode::write_existing); EXPECT_ANY_THROW ( File locked_file_2("locked.tmp", Open_Mode::write_existing) ); } } ///////////////////////////////////////////////////////////////////////////// TEST_F(File_Test, open_success) { { File file("existing.tmp", Open_Mode::read_existing); EXPECT_EQ(file.get_mode(), Open_Mode::read_existing); } { std::remove("new.tmp"); File new_file("new.tmp", Open_Mode::create_new); new_file.flush(); EXPECT_EQ(new_file.get_mode(), Open_Mode::create_new); } } ///////////////////////////////////////////////////////////////////////////// TEST_F(File_Test, read_existing) { File existing("existing.tmp", Open_Mode::read_existing); EXPECT_EQ(existing.read<uint64_t>(), joedb_magic); EXPECT_EQ(existing.read<bool>(), false); EXPECT_EQ(existing.read<bool>(), true); } ///////////////////////////////////////////////////////////////////////////// TEST_F(File_Test, read_write_integer) { { std::remove("new.tmp"); File new_file("new.tmp", Open_Mode::create_new); new_file.write<uint64_t>(joedb_magic); new_file.set_position(0); EXPECT_EQ(joedb_magic, new_file.read<uint64_t>()); } #if 0 std::random_device rd; // not supported by valgrind std::mt19937_64 gen(rd()); #else std::mt19937_64 gen(0); #endif const int N = 1000; { std::remove("new.tmp"); File new_file("new.tmp", Open_Mode::create_new); for (int i = N; --i >= 0;) { uint16_t value = uint16_t(gen()); new_file.set_position(0); new_file.compact_write<uint16_t>(value); new_file.set_position(0); EXPECT_EQ(value, new_file.compact_read<uint16_t>()); } } { std::remove("new.tmp"); File new_file("new.tmp", Open_Mode::create_new); for (int i = N; --i >= 0;) { uint32_t value = uint32_t(gen()); new_file.set_position(0); new_file.compact_write<uint32_t>(value); new_file.set_position(0); EXPECT_EQ(value, new_file.compact_read<uint32_t>()); } } { std::remove("new.tmp"); File new_file("new.tmp", Open_Mode::create_new); for (int i = N; --i >= 0;) { uint64_t value = uint64_t(gen()) & 0x1fffffffffffffffULL; new_file.set_position(0); new_file.compact_write<uint64_t>(value); new_file.set_position(0); EXPECT_EQ(value, new_file.compact_read<uint64_t>()); } } } ///////////////////////////////////////////////////////////////////////////// TEST_F(File_Test, read_write_string) { std::remove("new.tmp"); File new_file("new.tmp", Open_Mode::create_new); const std::string s("joedb!!!"); new_file.write_string(s); new_file.set_position(0); EXPECT_EQ(new_file.read_string(), s); } ///////////////////////////////////////////////////////////////////////////// TEST_F(File_Test, position_test) { std::remove("new.tmp"); File file("new.tmp", Open_Mode::create_new); EXPECT_EQ(0LL, file.get_position()); file.set_position(size_t(-1)); EXPECT_EQ(0LL, file.get_position()); const int64_t N = 100; for (int i = N; --i >= 0;) file.write<uint8_t>('x'); EXPECT_EQ(N, file.get_position()); const int64_t pos = 12; file.set_position(pos); EXPECT_EQ(pos, file.get_position()); const uint8_t x = file.read<uint8_t>(); EXPECT_EQ('x', x); EXPECT_EQ(pos + 1, file.get_position()); file.set_position(N + 2); EXPECT_EQ(N + 2, file.get_position()); file.write<uint8_t>('x'); file.set_position(N + 1); const uint8_t c = file.read<uint8_t>(); EXPECT_EQ(0, c); EXPECT_FALSE(file.is_end_of_file()); EXPECT_EQ(N + 2, file.get_position()); } ///////////////////////////////////////////////////////////////////////////// TEST_F(File_Test, eof) { std::remove("new.tmp"); File file("new.tmp", Open_Mode::create_new); EXPECT_FALSE(file.is_end_of_file()); file.read<uint8_t>(); EXPECT_TRUE(file.is_end_of_file()); file.set_position(0); const int N = 100000; for (int i = N; --i >= 0;) file.write<uint8_t>('x'); EXPECT_FALSE(file.is_end_of_file()); file.set_position(N - 1); EXPECT_FALSE(file.is_end_of_file()); uint8_t c = file.read<uint8_t>(); EXPECT_EQ('x', c); EXPECT_FALSE(file.is_end_of_file()); file.read<uint8_t>(); EXPECT_TRUE(file.is_end_of_file()); } <commit_msg>Remove incorrect test: tests pass in cygwin (32-bit)<commit_after>#include "File.h" #include "gtest/gtest.h" #include <random> using namespace joedb; static const uint64_t joedb_magic = 0x0000620165646A6FULL; class File_Test: public::testing::Test { protected: virtual void SetUp() { File file("existing.tmp", Open_Mode::create_new); file.write<uint64_t>(joedb_magic); file.write<bool>(false); file.write<bool>(true); } virtual void TearDown() { std::remove("locked.tmp"); std::remove("existing.tmp"); std::remove("new.tmp"); } }; ///////////////////////////////////////////////////////////////////////////// TEST_F(File_Test, open_failure) { EXPECT_ANY_THROW ( File file("not_existing.tmp", Open_Mode::read_existing) ); EXPECT_ANY_THROW ( File file("not_existing.tmp", Open_Mode::write_existing) ); EXPECT_ANY_THROW ( File file("existing.tmp", Open_Mode::create_new) ); } ///////////////////////////////////////////////////////////////////////////// TEST_F(File_Test, open_lock) { std::remove("locked.tmp"); { File locked_file_1("locked.tmp", Open_Mode::create_new); locked_file_1.write<int>(1234); EXPECT_ANY_THROW ( File locked_file_2("locked.tmp", Open_Mode::write_existing) ); } { File locked_file_1("locked.tmp", Open_Mode::write_existing); EXPECT_ANY_THROW ( File locked_file_2("locked.tmp", Open_Mode::write_existing) ); } } ///////////////////////////////////////////////////////////////////////////// TEST_F(File_Test, open_success) { { File file("existing.tmp", Open_Mode::read_existing); EXPECT_EQ(file.get_mode(), Open_Mode::read_existing); } { std::remove("new.tmp"); File new_file("new.tmp", Open_Mode::create_new); new_file.flush(); EXPECT_EQ(new_file.get_mode(), Open_Mode::create_new); } } ///////////////////////////////////////////////////////////////////////////// TEST_F(File_Test, read_existing) { File existing("existing.tmp", Open_Mode::read_existing); EXPECT_EQ(existing.read<uint64_t>(), joedb_magic); EXPECT_EQ(existing.read<bool>(), false); EXPECT_EQ(existing.read<bool>(), true); } ///////////////////////////////////////////////////////////////////////////// TEST_F(File_Test, read_write_integer) { { std::remove("new.tmp"); File new_file("new.tmp", Open_Mode::create_new); new_file.write<uint64_t>(joedb_magic); new_file.set_position(0); EXPECT_EQ(joedb_magic, new_file.read<uint64_t>()); } #if 0 std::random_device rd; // not supported by valgrind std::mt19937_64 gen(rd()); #else std::mt19937_64 gen(0); #endif const int N = 1000; { std::remove("new.tmp"); File new_file("new.tmp", Open_Mode::create_new); for (int i = N; --i >= 0;) { uint16_t value = uint16_t(gen()); new_file.set_position(0); new_file.compact_write<uint16_t>(value); new_file.set_position(0); EXPECT_EQ(value, new_file.compact_read<uint16_t>()); } } { std::remove("new.tmp"); File new_file("new.tmp", Open_Mode::create_new); for (int i = N; --i >= 0;) { uint32_t value = uint32_t(gen()); new_file.set_position(0); new_file.compact_write<uint32_t>(value); new_file.set_position(0); EXPECT_EQ(value, new_file.compact_read<uint32_t>()); } } { std::remove("new.tmp"); File new_file("new.tmp", Open_Mode::create_new); for (int i = N; --i >= 0;) { uint64_t value = uint64_t(gen()) & 0x1fffffffffffffffULL; new_file.set_position(0); new_file.compact_write<uint64_t>(value); new_file.set_position(0); EXPECT_EQ(value, new_file.compact_read<uint64_t>()); } } } ///////////////////////////////////////////////////////////////////////////// TEST_F(File_Test, read_write_string) { std::remove("new.tmp"); File new_file("new.tmp", Open_Mode::create_new); const std::string s("joedb!!!"); new_file.write_string(s); new_file.set_position(0); EXPECT_EQ(new_file.read_string(), s); } ///////////////////////////////////////////////////////////////////////////// TEST_F(File_Test, position_test) { std::remove("new.tmp"); File file("new.tmp", Open_Mode::create_new); EXPECT_EQ(0LL, file.get_position()); // That test was not correct // https://en.cppreference.com/w/cpp/io/c/fseek // "POSIX allows seeking beyond the existing end of file..." // file.set_position(size_t(-1)); // EXPECT_EQ(0LL, file.get_position()); const int64_t N = 100; for (int i = N; --i >= 0;) file.write<uint8_t>('x'); EXPECT_EQ(N, file.get_position()); const int64_t pos = 12; file.set_position(pos); EXPECT_EQ(pos, file.get_position()); const uint8_t x = file.read<uint8_t>(); EXPECT_EQ('x', x); EXPECT_EQ(pos + 1, file.get_position()); file.set_position(N + 2); EXPECT_EQ(N + 2, file.get_position()); file.write<uint8_t>('x'); file.set_position(N + 1); const uint8_t c = file.read<uint8_t>(); EXPECT_EQ(0, c); EXPECT_FALSE(file.is_end_of_file()); EXPECT_EQ(N + 2, file.get_position()); } ///////////////////////////////////////////////////////////////////////////// TEST_F(File_Test, eof) { std::remove("new.tmp"); File file("new.tmp", Open_Mode::create_new); EXPECT_FALSE(file.is_end_of_file()); file.read<uint8_t>(); EXPECT_TRUE(file.is_end_of_file()); file.set_position(0); const int N = 100000; for (int i = N; --i >= 0;) file.write<uint8_t>('x'); EXPECT_FALSE(file.is_end_of_file()); file.set_position(N - 1); EXPECT_FALSE(file.is_end_of_file()); uint8_t c = file.read<uint8_t>(); EXPECT_EQ('x', c); EXPECT_FALSE(file.is_end_of_file()); file.read<uint8_t>(); EXPECT_TRUE(file.is_end_of_file()); } <|endoftext|>
<commit_before>// Copyright (c) 2015 The Khronos Group Inc. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and/or associated documentation files (the // "Materials"), to deal in the Materials without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Materials, and to // permit persons to whom the Materials are 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 Materials. // // MODIFICATIONS TO THIS FILE MAY MEAN IT NO LONGER ACCURATELY REFLECTS // KHRONOS STANDARDS. THE UNMODIFIED, NORMATIVE VERSIONS OF KHRONOS // SPECIFICATIONS AND HEADER INFORMATION ARE LOCATED AT // https://www.khronos.org/registry/ // // THE MATERIALS ARE 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 // MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS. #include "UnitSPIRV.h" #include "gmock/gmock.h" namespace { using spvtest::MakeVector; using ::testing::Eq; using Words = std::vector<uint32_t>; TEST(MakeVector, Samples) { EXPECT_THAT(MakeVector(""), Eq(Words{0})); EXPECT_THAT(MakeVector("a"), Eq(Words{0x0061})); EXPECT_THAT(MakeVector("ab"), Eq(Words{0x006261})); EXPECT_THAT(MakeVector("abc"), Eq(Words{0x00636261})); EXPECT_THAT(MakeVector("abcd"), Eq(Words{0x64636261, 0x00})); EXPECT_THAT(MakeVector("abcde"), Eq(Words{0x64636261, 0x0065})); } TEST(WordVectorPrintTo, PreservesFlagsAndFill) { std::stringstream s; s << std::setw(4) << std::oct << std::setfill('x') << 8 << " "; PrintTo(spvtest::WordVector({10, 16}), &s); // The octal setting and fill character should be preserved // from before the PrintTo. // Width is reset after each emission of a regular scalar type. // So set it explicitly again. s << std::setw(4) << 9; EXPECT_THAT(s.str(), Eq("xx10 0x0000000a 0x00000010 xx11")); } } // anonymous namespace <commit_msg>Fix namespace on PrintTo<commit_after>// Copyright (c) 2015 The Khronos Group Inc. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and/or associated documentation files (the // "Materials"), to deal in the Materials without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Materials, and to // permit persons to whom the Materials are 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 Materials. // // MODIFICATIONS TO THIS FILE MAY MEAN IT NO LONGER ACCURATELY REFLECTS // KHRONOS STANDARDS. THE UNMODIFIED, NORMATIVE VERSIONS OF KHRONOS // SPECIFICATIONS AND HEADER INFORMATION ARE LOCATED AT // https://www.khronos.org/registry/ // // THE MATERIALS ARE 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 // MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS. #include "UnitSPIRV.h" #include "gmock/gmock.h" namespace { using spvtest::MakeVector; using ::testing::Eq; using Words = std::vector<uint32_t>; TEST(MakeVector, Samples) { EXPECT_THAT(MakeVector(""), Eq(Words{0})); EXPECT_THAT(MakeVector("a"), Eq(Words{0x0061})); EXPECT_THAT(MakeVector("ab"), Eq(Words{0x006261})); EXPECT_THAT(MakeVector("abc"), Eq(Words{0x00636261})); EXPECT_THAT(MakeVector("abcd"), Eq(Words{0x64636261, 0x00})); EXPECT_THAT(MakeVector("abcde"), Eq(Words{0x64636261, 0x0065})); } TEST(WordVectorPrintTo, PreservesFlagsAndFill) { std::stringstream s; s << std::setw(4) << std::oct << std::setfill('x') << 8 << " "; spvtest::PrintTo(spvtest::WordVector({10, 16}), &s); // The octal setting and fill character should be preserved // from before the PrintTo. // Width is reset after each emission of a regular scalar type. // So set it explicitly again. s << std::setw(4) << 9; EXPECT_THAT(s.str(), Eq("xx10 0x0000000a 0x00000010 xx11")); } } // anonymous namespace <|endoftext|>
<commit_before>#include <QDebug> #include <QSortFilterProxyModel> #include <QTime> #include <QTimer> #include <QXmlInputSource> #include <QXmlSimpleReader> #include <cmath> #include "katlasglobe.h" #include "pntmap.h" #include "texcolorizer.h" #include "tilescissor.h" #include "katlasdirs.h" #include "katlastilecreatordialog.h" #include "placemarkmanager.h" #include "xmlhandler.h" const float rad2int = 21600.0 / M_PI; KAtlasGlobe::KAtlasGlobe( QWidget* parent ):m_parent(parent){ m_justModified = false; m_maptheme = new MapTheme(); QStringList m_mapthemedirs = MapTheme::findMapThemes( "maps" ); QString selectedmap; if ( m_mapthemedirs.count() == 0 ) { qDebug() << "Couldn't find any maps! Exiting ..."; exit(-1); } if ( m_mapthemedirs.count() >= 1 ){ QStringList tmp = m_mapthemedirs.filter("etopo2.dgml"); if ( tmp.count() >= 1 ) selectedmap = tmp[0]; else selectedmap = m_mapthemedirs[0]; } m_maptheme->open( KAtlasDirs::path( "maps/" + selectedmap) ); if ( m_maptheme->maxTileLevel() < 1 ){ qDebug("Base tiles not available. Creating Tiles ... "); KAtlasTileCreatorDialog tilecreatordlg( m_parent ); tilecreatordlg.setSummary( m_maptheme->name(), m_maptheme->description() ); TileScissor tilecreator( m_maptheme->prefix(), m_maptheme->installMap(), m_maptheme->bitmaplayer().dem); QObject::connect( &tilecreator, SIGNAL( progress( int ) ), &tilecreatordlg, SLOT( setProgress( int ) ) ); QTimer::singleShot( 0, &tilecreator, SLOT( createTiles() ) ); tilecreatordlg.exec(); } m_maptheme->detectMaxTileLevel(); texmapper = new TextureMapper( "maps/" + m_maptheme->tilePrefix() + "_" ); texmapper->setMaxTileLevel( m_maptheme->maxTileLevel() ); m_placemarkpainter->setLabelColor( m_maptheme->labelColor() ); // m_placecontainer ->clearTextPixmaps(); veccomposer = new VectorComposer(); texcolorizer = new TextureColorizer(KAtlasDirs::path("seacolors.leg"), KAtlasDirs::path("landcolors.leg")); placemarkmanager = new PlaceMarkManager(); m_placemarkmodel = new PlaceMarkModel(); QSortFilterProxyModel* sortmodel = new QSortFilterProxyModel( this ); sortmodel->setSourceModel( m_placemarkmodel ); // m_placemarkmodel -> sort( 0, Qt::AscendingOrder ); sortmodel -> sort( 0, Qt::AscendingOrder ); m_placemarkmodel = ( QAbstractItemModel* )sortmodel; m_placecontainer = new PlaceContainer("placecontainer"); m_placemarkpainter = new PlaceMarkPainter(); m_radius = 2000; m_rotAxis = Quaternion(1.0, 0.0, 0.0, 0.0); m_coastimg = new QImage(10,10,QImage::Format_ARGB32_Premultiplied); m_centered = false; m_centeredItem = 0; } void KAtlasGlobe::setMapTheme( const QString& selectedmap ){ m_maptheme->open( KAtlasDirs::path( selectedmap) ); if ( m_maptheme->maxTileLevel() < 1 ){ qDebug("Base tiles not available. Creating Tiles ... "); KAtlasTileCreatorDialog tilecreatordlg( m_parent ); tilecreatordlg.setSummary( m_maptheme->name(), m_maptheme->description() ); TileScissor tilecreator( m_maptheme->prefix(), m_maptheme->installMap(), m_maptheme->bitmaplayer().dem); QObject::connect( &tilecreator, SIGNAL( progress( int ) ), &tilecreatordlg, SLOT( setProgress( int ) ) ); QTimer::singleShot( 0, &tilecreator, SLOT( createTiles() ) ); tilecreatordlg.exec(); } m_maptheme->detectMaxTileLevel(); m_placemarkpainter->setLabelColor( m_maptheme->labelColor() ); m_placecontainer ->clearTextPixmaps(); texmapper->setMap( "maps/" + m_maptheme->tilePrefix() + "_" ); texmapper->setMaxTileLevel( m_maptheme->maxTileLevel() ); m_parent->update(); m_justModified = true; } void KAtlasGlobe::resize(){ *m_coastimg = QImage(m_canvasimg->width(),m_canvasimg->height(),QImage::Format_ARGB32_Premultiplied); texmapper->resizeMap(m_canvasimg); veccomposer->resizeMap(m_coastimg); m_justModified = true; } void KAtlasGlobe::paintGlobe(ClipPainter* painter, QRect dirty){ // QTime *timer = new QTime(); // timer->restart(); if ( needsUpdate() || m_canvasimg->isNull() || m_justModified == true ){ // Workaround // m_rotAxis.display(); texmapper->mapTexture(m_canvasimg, m_radius, m_rotAxis); // qDebug() << "Texture-Mapping:" << timer->elapsed(); // timer->restart(); if ( m_maptheme->bitmaplayer().dem == "true" ){ *m_coastimg = QImage(m_canvasimg->width(),m_canvasimg->height(),QImage::Format_ARGB32_Premultiplied); // qDebug() << "Scale & Fill: " << timer->elapsed(); // timer->restart(); veccomposer->drawTextureMap(m_coastimg, m_radius, m_rotAxis); // Create VectorMap // qDebug() << "Vectors: " << timer->elapsed(); // timer->restart(); texcolorizer->colorize(m_canvasimg, m_coastimg, m_radius); // Recolorize the heightmap using the VectorMap // qDebug() << "Colorizing: " << timer->elapsed(); // timer->restart(); } } painter->drawImage(dirty, *m_canvasimg, dirty); // paint Map on Widget if ( m_maptheme->vectorlayer().enabled == true ){ veccomposer->paintVectorMap(painter, m_radius, m_rotAxis); // Add further Vectors // qDebug() << "2. Vectors: " << timer->elapsed(); // timer->restart(); } if (m_centered == true) m_placemarkpainter->paintPlaceMark(painter, m_canvasimg->width()/2, m_canvasimg->height()/2, m_placemarkmodel, m_centeredItem); m_placemarkpainter->paintPlaceFolder(painter, m_canvasimg->width()/2, m_canvasimg->height()/2, m_radius, m_placecontainer, m_rotAxis); // qDebug() << "Placemarks: " << timer->elapsed(); // timer->restart(); m_rotAxisUpdated = m_rotAxis; m_radiusUpdated = m_radius; m_justModified = false; } void KAtlasGlobe::setCanvasImage(QImage* canvasimg){ m_canvasimg = canvasimg; } void KAtlasGlobe::zoom(const int& radius){ *m_canvasimg = QImage(m_canvasimg->width(),m_canvasimg->height(),QImage::Format_ARGB32_Premultiplied);; m_radius = radius; } void KAtlasGlobe::rotateTo(const uint& phi, const uint& theta, const uint& psi){ m_rotAxis.createFromEuler((float)(phi)/rad2int,(float)(theta)/rad2int,(float)(psi)/rad2int); // m_rotAxis.display(); } void KAtlasGlobe::rotateTo(const float& phi, const float& theta){ // m_rotAxis.createFromEuler( M_PI-(phi + 180.0) * M_PI / 180.0, M_PI+(theta + 180.0) * M_PI / 180.0, 0.0); m_rotAxis.createFromEuler( (phi + 180.0) * M_PI / 180.0, (theta + 180.0) * M_PI / 180.0, 0.0); // m_rotAxis.display(); m_centered = false; } void KAtlasGlobe::rotateBy(const Quaternion& incRot){ // m_rotAxis.createFromEuler((float)(phi)/rad2int,(float)(theta)/rad2int,(float)(psi)/rad2int); m_rotAxis = incRot * m_rotAxis; // m_rotAxis.display(); m_centered = false; } void KAtlasGlobe::rotateBy(const float& phi, const float& theta){ Quaternion rotPhi(1.0, phi, 0.0, 0.0); Quaternion rotTheta(1.0, 0.0, theta, 0.0); m_rotAxis = rotTheta * m_rotAxis; m_rotAxis *= rotPhi; m_rotAxis.normalize(); m_centered = false; } int KAtlasGlobe::northPoleY(){ GeoPoint northpole( 0.0f, (float)( -M_PI*0.5 ) ); Quaternion qpolepos = northpole.getQuatPoint(); Quaternion invRotAxis = m_rotAxis.inverse(); // invRotAxis.display(); qpolepos.rotateAroundAxis(invRotAxis); return (int)( m_radius * qpolepos.v[Q_Y] ); } int KAtlasGlobe::northPoleZ(){ GeoPoint northpole( 0.0f, (float)( -M_PI*0.5 ) ); Quaternion qpolepos = northpole.getQuatPoint(); Quaternion invRotAxis = m_rotAxis.inverse(); // invRotAxis.display(); qpolepos.rotateAroundAxis(invRotAxis); return (int)( m_radius * qpolepos.v[Q_Z] ); } bool KAtlasGlobe::screenCoordinates( const float lng, const float lat, int& x, int& y ){ Quaternion qpos = GeoPoint( lng, lat ).getQuatPoint(); Quaternion invRotAxis = m_rotAxis.inverse(); qpos.rotateAroundAxis(invRotAxis); x = (int)( m_radius * qpos.v[Q_X] ); y = (int)( -m_radius * qpos.v[Q_Y] ); if ( qpos.v[Q_Z] >= 0.0 ) return true; else return false; } void KAtlasGlobe::addPlaceMarkFile( QString filename ){ KAtlasXmlHandler handler( m_placecontainer ); QFile file( filename ); QXmlInputSource source( &file ); QXmlSimpleReader reader; reader.setContentHandler( &handler ); reader.parse( source ); qDebug() << "Number of placemarks: " << m_placecontainer->size(); } <commit_msg><commit_after>#include <QDebug> #include <QSortFilterProxyModel> #include <QTime> #include <QTimer> #include <QXmlInputSource> #include <QXmlSimpleReader> #include <cmath> #include "katlasglobe.h" #include "pntmap.h" #include "texcolorizer.h" #include "tilescissor.h" #include "katlasdirs.h" #include "katlastilecreatordialog.h" #include "placemarkmanager.h" #include "xmlhandler.h" const float rad2int = 21600.0 / M_PI; KAtlasGlobe::KAtlasGlobe( QWidget* parent ):m_parent(parent){ m_justModified = false; m_maptheme = new MapTheme(); QStringList m_mapthemedirs = MapTheme::findMapThemes( "maps" ); QString selectedmap; if ( m_mapthemedirs.count() == 0 ) { qDebug() << "Couldn't find any maps! Exiting ..."; exit(-1); } if ( m_mapthemedirs.count() >= 1 ){ QStringList tmp = m_mapthemedirs.filter("etopo2.dgml"); if ( tmp.count() >= 1 ) selectedmap = tmp[0]; else selectedmap = m_mapthemedirs[0]; } m_maptheme->open( KAtlasDirs::path( "maps/" + selectedmap) ); if ( m_maptheme->maxTileLevel() < 1 ){ qDebug("Base tiles not available. Creating Tiles ... "); KAtlasTileCreatorDialog tilecreatordlg( m_parent ); tilecreatordlg.setSummary( m_maptheme->name(), m_maptheme->description() ); TileScissor tilecreator( m_maptheme->prefix(), m_maptheme->installMap(), m_maptheme->bitmaplayer().dem); QObject::connect( &tilecreator, SIGNAL( progress( int ) ), &tilecreatordlg, SLOT( setProgress( int ) ) ); QTimer::singleShot( 0, &tilecreator, SLOT( createTiles() ) ); tilecreatordlg.exec(); } m_maptheme->detectMaxTileLevel(); texmapper = new TextureMapper( "maps/" + m_maptheme->tilePrefix() + "_" ); texmapper->setMaxTileLevel( m_maptheme->maxTileLevel() ); veccomposer = new VectorComposer(); texcolorizer = new TextureColorizer(KAtlasDirs::path("seacolors.leg"), KAtlasDirs::path("landcolors.leg")); placemarkmanager = new PlaceMarkManager(); m_placemarkmodel = new PlaceMarkModel(); QSortFilterProxyModel* sortmodel = new QSortFilterProxyModel( this ); sortmodel->setSourceModel( m_placemarkmodel ); // m_placemarkmodel -> sort( 0, Qt::AscendingOrder ); sortmodel -> sort( 0, Qt::AscendingOrder ); m_placemarkmodel = ( QAbstractItemModel* )sortmodel; m_placecontainer = new PlaceContainer("placecontainer"); m_placemarkpainter = new PlaceMarkPainter(); m_placemarkpainter->setLabelColor( m_maptheme->labelColor() ); m_placecontainer ->clearTextPixmaps(); m_radius = 2000; m_rotAxis = Quaternion(1.0, 0.0, 0.0, 0.0); m_coastimg = new QImage(10,10,QImage::Format_ARGB32_Premultiplied); m_centered = false; m_centeredItem = 0; } void KAtlasGlobe::setMapTheme( const QString& selectedmap ){ m_maptheme->open( KAtlasDirs::path( selectedmap) ); if ( m_maptheme->maxTileLevel() < 1 ){ qDebug("Base tiles not available. Creating Tiles ... "); KAtlasTileCreatorDialog tilecreatordlg( m_parent ); tilecreatordlg.setSummary( m_maptheme->name(), m_maptheme->description() ); TileScissor tilecreator( m_maptheme->prefix(), m_maptheme->installMap(), m_maptheme->bitmaplayer().dem); QObject::connect( &tilecreator, SIGNAL( progress( int ) ), &tilecreatordlg, SLOT( setProgress( int ) ) ); QTimer::singleShot( 0, &tilecreator, SLOT( createTiles() ) ); tilecreatordlg.exec(); } m_maptheme->detectMaxTileLevel(); m_placemarkpainter->setLabelColor( m_maptheme->labelColor() ); m_placecontainer ->clearTextPixmaps(); texmapper->setMap( "maps/" + m_maptheme->tilePrefix() + "_" ); texmapper->setMaxTileLevel( m_maptheme->maxTileLevel() ); m_parent->update(); m_justModified = true; } void KAtlasGlobe::resize(){ *m_coastimg = QImage(m_canvasimg->width(),m_canvasimg->height(),QImage::Format_ARGB32_Premultiplied); texmapper->resizeMap(m_canvasimg); veccomposer->resizeMap(m_coastimg); m_justModified = true; } void KAtlasGlobe::paintGlobe(ClipPainter* painter, QRect dirty){ // QTime *timer = new QTime(); // timer->restart(); if ( needsUpdate() || m_canvasimg->isNull() || m_justModified == true ){ // Workaround // m_rotAxis.display(); texmapper->mapTexture(m_canvasimg, m_radius, m_rotAxis); // qDebug() << "Texture-Mapping:" << timer->elapsed(); // timer->restart(); if ( m_maptheme->bitmaplayer().dem == "true" ){ *m_coastimg = QImage(m_canvasimg->width(),m_canvasimg->height(),QImage::Format_ARGB32_Premultiplied); // qDebug() << "Scale & Fill: " << timer->elapsed(); // timer->restart(); veccomposer->drawTextureMap(m_coastimg, m_radius, m_rotAxis); // Create VectorMap // qDebug() << "Vectors: " << timer->elapsed(); // timer->restart(); texcolorizer->colorize(m_canvasimg, m_coastimg, m_radius); // Recolorize the heightmap using the VectorMap // qDebug() << "Colorizing: " << timer->elapsed(); // timer->restart(); } } painter->drawImage(dirty, *m_canvasimg, dirty); // paint Map on Widget if ( m_maptheme->vectorlayer().enabled == true ){ veccomposer->paintVectorMap(painter, m_radius, m_rotAxis); // Add further Vectors // qDebug() << "2. Vectors: " << timer->elapsed(); // timer->restart(); } if (m_centered == true) m_placemarkpainter->paintPlaceMark(painter, m_canvasimg->width()/2, m_canvasimg->height()/2, m_placemarkmodel, m_centeredItem); m_placemarkpainter->paintPlaceFolder(painter, m_canvasimg->width()/2, m_canvasimg->height()/2, m_radius, m_placecontainer, m_rotAxis); // qDebug() << "Placemarks: " << timer->elapsed(); // timer->restart(); m_rotAxisUpdated = m_rotAxis; m_radiusUpdated = m_radius; m_justModified = false; } void KAtlasGlobe::setCanvasImage(QImage* canvasimg){ m_canvasimg = canvasimg; } void KAtlasGlobe::zoom(const int& radius){ *m_canvasimg = QImage(m_canvasimg->width(),m_canvasimg->height(),QImage::Format_ARGB32_Premultiplied);; m_radius = radius; } void KAtlasGlobe::rotateTo(const uint& phi, const uint& theta, const uint& psi){ m_rotAxis.createFromEuler((float)(phi)/rad2int,(float)(theta)/rad2int,(float)(psi)/rad2int); // m_rotAxis.display(); } void KAtlasGlobe::rotateTo(const float& phi, const float& theta){ // m_rotAxis.createFromEuler( M_PI-(phi + 180.0) * M_PI / 180.0, M_PI+(theta + 180.0) * M_PI / 180.0, 0.0); m_rotAxis.createFromEuler( (phi + 180.0) * M_PI / 180.0, (theta + 180.0) * M_PI / 180.0, 0.0); // m_rotAxis.display(); m_centered = false; } void KAtlasGlobe::rotateBy(const Quaternion& incRot){ // m_rotAxis.createFromEuler((float)(phi)/rad2int,(float)(theta)/rad2int,(float)(psi)/rad2int); m_rotAxis = incRot * m_rotAxis; // m_rotAxis.display(); m_centered = false; } void KAtlasGlobe::rotateBy(const float& phi, const float& theta){ Quaternion rotPhi(1.0, phi, 0.0, 0.0); Quaternion rotTheta(1.0, 0.0, theta, 0.0); m_rotAxis = rotTheta * m_rotAxis; m_rotAxis *= rotPhi; m_rotAxis.normalize(); m_centered = false; } int KAtlasGlobe::northPoleY(){ GeoPoint northpole( 0.0f, (float)( -M_PI*0.5 ) ); Quaternion qpolepos = northpole.getQuatPoint(); Quaternion invRotAxis = m_rotAxis.inverse(); // invRotAxis.display(); qpolepos.rotateAroundAxis(invRotAxis); return (int)( m_radius * qpolepos.v[Q_Y] ); } int KAtlasGlobe::northPoleZ(){ GeoPoint northpole( 0.0f, (float)( -M_PI*0.5 ) ); Quaternion qpolepos = northpole.getQuatPoint(); Quaternion invRotAxis = m_rotAxis.inverse(); // invRotAxis.display(); qpolepos.rotateAroundAxis(invRotAxis); return (int)( m_radius * qpolepos.v[Q_Z] ); } bool KAtlasGlobe::screenCoordinates( const float lng, const float lat, int& x, int& y ){ Quaternion qpos = GeoPoint( lng, lat ).getQuatPoint(); Quaternion invRotAxis = m_rotAxis.inverse(); qpos.rotateAroundAxis(invRotAxis); x = (int)( m_radius * qpos.v[Q_X] ); y = (int)( -m_radius * qpos.v[Q_Y] ); if ( qpos.v[Q_Z] >= 0.0 ) return true; else return false; } void KAtlasGlobe::addPlaceMarkFile( QString filename ){ KAtlasXmlHandler handler( m_placecontainer ); QFile file( filename ); QXmlInputSource source( &file ); QXmlSimpleReader reader; reader.setContentHandler( &handler ); reader.parse( source ); qDebug() << "Number of placemarks: " << m_placecontainer->size(); } <|endoftext|>
<commit_before>#ifndef RPTUI_UITOOLS_HXX #define RPTUI_UITOOLS_HXX /************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: UITools.hxx,v $ * * $Revision: 1.4 $ * * last change: $Author: vg $ $Date: 2008-02-12 13:19:02 $ * * 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 _COM_SUN_STAR_REPORT_XGROUP_HPP_ #include <com/sun/star/report/XGroup.hpp> #endif #include <com/sun/star/report/XReportControlFormat.hpp> #include <com/sun/star/awt/XWindow.hpp> #include <com/sun/star/beans/NamedValue.hpp> #include <com/sun/star/container/XIndexAccess.hpp> #include <com/sun/star/sdbc/XRowSet.hpp> #include "ReportSection.hxx" #include <rtl/ref.hxx> #include <vcl/taskpanelist.hxx> #include <comphelper/stl_types.hxx> #include <functional> class SdrPage; class SdrObject; class SdrUnoObj; class SdrView; class Rectangle; namespace comphelper { class OPropertyChangeMultiplexer; class OPropertyChangeListener; } namespace rptui { /** returns the position of the object inside the index container @param _xReportDefinition the report definition to get the groups @param _xGroup the group to search @return returns the position of the group in the list, otherwise -1 */ template<typename T> sal_Int32 getPositionInIndexAccess( const ::com::sun::star::uno::Reference< ::com::sun::star::container::XIndexAccess >& _xCollection ,const ::com::sun::star::uno::Reference< T >& _xSearch) { sal_Int32 nCount = _xCollection->getCount(); sal_Int32 i = (nCount == 0) ? -1 : 0; for (;i<nCount ; ++i) { ::com::sun::star::uno::Reference< T > xObject(_xCollection->getByIndex(i),::com::sun::star::uno::UNO_QUERY); if ( xObject == _xSearch ) break; } // for (;i<nCount ; ++i) return i; } /** set the name of the header and footer of the group by the expression appended by the localized name of the section @param _xGroup the group where the header/footer name is set by the expression of the group */ void adjustSectionName(const ::com::sun::star::uno::Reference< ::com::sun::star::report::XGroup >& _xGroup,sal_Int32 _nPos); /** add a listener for the properties size, left margin, right margin to the page style * * \param _xReportDefinition * \param _pListener * \return */ ::rtl::Reference< comphelper::OPropertyChangeMultiplexer> addStyleListener( const ::com::sun::star::uno::Reference< ::com::sun::star::report::XReportDefinition >& _xReportDefinition ,::comphelper::OPropertyChangeListener* _pListener); /** opens the common character font dialog */ bool openCharDialog( const ::com::sun::star::uno::Reference< ::com::sun::star::report::XReportControlFormat>& _xReportControlFormat, const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XWindow>& _xWindow ); /** opens the common character font dialog */ bool openCharDialog( const ::com::sun::star::uno::Reference< ::com::sun::star::report::XReportControlFormat>& _xReportControlFormat, const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XWindow>& _xWindow, ::com::sun::star::uno::Sequence< ::com::sun::star::beans::NamedValue >& _out_rNewValues ); /** applies the character settings previously obtained via openCharDialog */ void applyCharacterSettings( const ::com::sun::star::uno::Reference< ::com::sun::star::report::XReportControlFormat >& _rxReportControlFormat, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::NamedValue >& _rSettings ); /** notifySystemWindow adds or remove the given window _pToRegister at the Systemwindow found when search _pWindow. @param _pWindow The window which is used to search for the SystemWindow. @param _pToRegister The window which should be added or removed on the TaskPaneList. @param _rMemFunc The member function which should be called at the SystemWindow when found. Possible values are: ::comphelper::mem_fun(&TaskPaneList::AddWindow) ::comphelper::mem_fun(&TaskPaneList::RemoveWindow) */ void notifySystemWindow(Window* _pWindow,Window* _pToRegister, ::comphelper::mem_fun1_t<TaskPaneList,Window*> _rMemFunc); /** checks whether the given rectangle overlapps another OUnoObject object in that view. * * \param _rRect * \param _rPage * \param _bAllObjects if <TRUE/> all objects are taken into account, otherwise only not marked ones * \return the object which is overlapped, otherwise <NULL/> */ SdrObject* isOver(const Rectangle& _rRect,SdrPage& _rPage,SdrView& _rView,bool _bAllObjects = false,SdrObject* _pIgnore = NULL); SdrObject* isOver(const Rectangle& _rRect,SdrPage& _rPage,SdrView& _rView,bool _bAllObjects, SdrUnoObj* _pIgnoreList[], int _nIgnoreListLength); /** checks whether the given OUnoObject object rectangle overlapps another object in that view. * * \param _pObj * \param _rPage * \param _rView * \param _bAllObjects if <TRUE/> all objects are taken into account, otherwise only not marked ones * \return the object which is overlapped, otherwise <NULL/>. If the given object is not of type OUnoObject <NULL/> will be returned. */ SdrObject* isOver(SdrObject* _pObj,SdrPage& _rPage,SdrView& _rView,bool _bAllObjects = false); /** retrieves the names of the parameters of the command which the given RowSet is bound to */ ::com::sun::star::uno::Sequence< ::rtl::OUString > getParameterNames( const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XRowSet >& _rxRowSet ); /** ensures that no control overlaps the given one. * * \param pControl the control which should place in the section without overlapping * \param _pReportSection the section * \param _bInsert TRUE whe the control should be inserted, otherwise not. */ void correctOverlapping(SdrObject* pControl,::boost::shared_ptr<OReportSection> _pReportSection,bool _bInsert = true); /** returns a Rectangle of a given SdrObject * * \param pControl the SdrObject */ Rectangle getRectangleFromControl(SdrObject* pControl); } #endif //RPTUI_UITOOLS_HXX <commit_msg>INTEGRATION: CWS changefileheader (1.4.24); FILE MERGED 2008/04/01 12:33:14 thb 1.4.24.2: #i85898# Stripping all external header guards 2008/03/31 13:32:17 rt 1.4.24.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: UITools.hxx,v $ * $Revision: 1.5 $ * * 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 RPTUI_UITOOLS_HXX #define RPTUI_UITOOLS_HXX #include <com/sun/star/report/XGroup.hpp> #include <com/sun/star/report/XReportControlFormat.hpp> #include <com/sun/star/awt/XWindow.hpp> #include <com/sun/star/beans/NamedValue.hpp> #include <com/sun/star/container/XIndexAccess.hpp> #include <com/sun/star/sdbc/XRowSet.hpp> #include "ReportSection.hxx" #include <rtl/ref.hxx> #include <vcl/taskpanelist.hxx> #include <comphelper/stl_types.hxx> #include <functional> class SdrPage; class SdrObject; class SdrUnoObj; class SdrView; class Rectangle; namespace comphelper { class OPropertyChangeMultiplexer; class OPropertyChangeListener; } namespace rptui { /** returns the position of the object inside the index container @param _xReportDefinition the report definition to get the groups @param _xGroup the group to search @return returns the position of the group in the list, otherwise -1 */ template<typename T> sal_Int32 getPositionInIndexAccess( const ::com::sun::star::uno::Reference< ::com::sun::star::container::XIndexAccess >& _xCollection ,const ::com::sun::star::uno::Reference< T >& _xSearch) { sal_Int32 nCount = _xCollection->getCount(); sal_Int32 i = (nCount == 0) ? -1 : 0; for (;i<nCount ; ++i) { ::com::sun::star::uno::Reference< T > xObject(_xCollection->getByIndex(i),::com::sun::star::uno::UNO_QUERY); if ( xObject == _xSearch ) break; } // for (;i<nCount ; ++i) return i; } /** set the name of the header and footer of the group by the expression appended by the localized name of the section @param _xGroup the group where the header/footer name is set by the expression of the group */ void adjustSectionName(const ::com::sun::star::uno::Reference< ::com::sun::star::report::XGroup >& _xGroup,sal_Int32 _nPos); /** add a listener for the properties size, left margin, right margin to the page style * * \param _xReportDefinition * \param _pListener * \return */ ::rtl::Reference< comphelper::OPropertyChangeMultiplexer> addStyleListener( const ::com::sun::star::uno::Reference< ::com::sun::star::report::XReportDefinition >& _xReportDefinition ,::comphelper::OPropertyChangeListener* _pListener); /** opens the common character font dialog */ bool openCharDialog( const ::com::sun::star::uno::Reference< ::com::sun::star::report::XReportControlFormat>& _xReportControlFormat, const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XWindow>& _xWindow ); /** opens the common character font dialog */ bool openCharDialog( const ::com::sun::star::uno::Reference< ::com::sun::star::report::XReportControlFormat>& _xReportControlFormat, const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XWindow>& _xWindow, ::com::sun::star::uno::Sequence< ::com::sun::star::beans::NamedValue >& _out_rNewValues ); /** applies the character settings previously obtained via openCharDialog */ void applyCharacterSettings( const ::com::sun::star::uno::Reference< ::com::sun::star::report::XReportControlFormat >& _rxReportControlFormat, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::NamedValue >& _rSettings ); /** notifySystemWindow adds or remove the given window _pToRegister at the Systemwindow found when search _pWindow. @param _pWindow The window which is used to search for the SystemWindow. @param _pToRegister The window which should be added or removed on the TaskPaneList. @param _rMemFunc The member function which should be called at the SystemWindow when found. Possible values are: ::comphelper::mem_fun(&TaskPaneList::AddWindow) ::comphelper::mem_fun(&TaskPaneList::RemoveWindow) */ void notifySystemWindow(Window* _pWindow,Window* _pToRegister, ::comphelper::mem_fun1_t<TaskPaneList,Window*> _rMemFunc); /** checks whether the given rectangle overlapps another OUnoObject object in that view. * * \param _rRect * \param _rPage * \param _bAllObjects if <TRUE/> all objects are taken into account, otherwise only not marked ones * \return the object which is overlapped, otherwise <NULL/> */ SdrObject* isOver(const Rectangle& _rRect,SdrPage& _rPage,SdrView& _rView,bool _bAllObjects = false,SdrObject* _pIgnore = NULL); SdrObject* isOver(const Rectangle& _rRect,SdrPage& _rPage,SdrView& _rView,bool _bAllObjects, SdrUnoObj* _pIgnoreList[], int _nIgnoreListLength); /** checks whether the given OUnoObject object rectangle overlapps another object in that view. * * \param _pObj * \param _rPage * \param _rView * \param _bAllObjects if <TRUE/> all objects are taken into account, otherwise only not marked ones * \return the object which is overlapped, otherwise <NULL/>. If the given object is not of type OUnoObject <NULL/> will be returned. */ SdrObject* isOver(SdrObject* _pObj,SdrPage& _rPage,SdrView& _rView,bool _bAllObjects = false); /** retrieves the names of the parameters of the command which the given RowSet is bound to */ ::com::sun::star::uno::Sequence< ::rtl::OUString > getParameterNames( const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XRowSet >& _rxRowSet ); /** ensures that no control overlaps the given one. * * \param pControl the control which should place in the section without overlapping * \param _pReportSection the section * \param _bInsert TRUE whe the control should be inserted, otherwise not. */ void correctOverlapping(SdrObject* pControl,::boost::shared_ptr<OReportSection> _pReportSection,bool _bInsert = true); /** returns a Rectangle of a given SdrObject * * \param pControl the SdrObject */ Rectangle getRectangleFromControl(SdrObject* pControl); } #endif //RPTUI_UITOOLS_HXX <|endoftext|>
<commit_before>// // Created by salmon on 16-11-4. // #include <simpla/SIMPLA_config.h> #include <iostream> #include <simpla/mesh/MeshCommon.h> #include <simpla/mesh/Atlas.h> #include <simpla/physics/Field.h> #include <simpla/manifold/Calculus.h> #include <simpla/simulation/TimeIntegrator.h> using namespace simpla; class DummyMesh : public mesh::MeshBlock { public: static constexpr unsigned int ndims = 3; SP_OBJECT_HEAD(DummyMesh, mesh::MeshBlock) template<typename ...Args> DummyMesh(Args &&...args):mesh::MeshBlock(std::forward<Args>(args)...) {} ~DummyMesh() {} template<typename TV, mesh::MeshEntityType IFORM> using data_block_type= mesh::DataBlockArray<Real, IFORM>; virtual std::shared_ptr<mesh::MeshBlock> clone() const { return std::dynamic_pointer_cast<mesh::MeshBlock>(std::make_shared<DummyMesh>()); }; template<typename ...Args> Real eval(Args &&...args) const { return 1.0; }; }; template<typename TM> struct AMRTest : public mesh::Worker { typedef TM mesh_type; SP_OBJECT_HEAD(AMRTest, mesh::Worker); template<typename TV, mesh::MeshEntityType IFORM> using field_type=Field<TV, mesh_type, index_const<IFORM>>; field_type<Real, mesh::VERTEX> phi{"phi", this}; field_type<Real, mesh::EDGE> E{"E", this}; field_type<Real, mesh::FACE> B{"B", this}; void next_time_step(Real dt) { // E = grad(-2.0 * phi) * dt; // phi -= diverge(E) * 3.0 * dt; } }; namespace simpla { std::shared_ptr<simulation::TimeIntegrator> create_time_integrator(std::string const &name, std::shared_ptr<mesh::Worker> const &w); }//namespace simpla int main(int argc, char **argv) { logger::set_stdout_level(100); auto worker = std::make_shared<AMRTest<DummyMesh>>(); worker->print(std::cout); auto integrator = simpla::create_time_integrator("AMR_TEST", worker); /** test.3d.input */ /** // Refer to geom::CartesianGridGeometry and its base classes for input CartesianGeometry{ domain_boxes = [ (0,0,0) , (14,9,9) ] x_lo = 0.e0 , 0.e0 , 0.e0 // lower end of computational domain. x_up = 30.e0 , 20.e0 , 20.e0 // upper end of computational domain. } // Refer to hier::PatchHierarchy for input PatchHierarchy { max_levels = 3 // Maximum number of levels in hierarchy. // Note: For the following regridding information, data is required for each // potential in the patch hierarchy; i.e., levels 0 thru max_levels-1. // If more data values than needed are given, only the number required // will be read in. If fewer values are given, an error will result. // // Specify coarsening ratios for each level 1 through max_levels-1 ratio_to_coarser { // vector ratio to next coarser level level_1 = 2 , 2 , 2 level_2 = 2 , 2 , 2 level_3 = 2 , 2 , 2 } largest_patch_size { level_0 = 40 , 40 , 40 // largest patch allowed in hierarchy // all finer levels will use same values as level_0... } smallest_patch_size { level_0 = 9 , 9 , 9 // all finer levels will use same values as level_0... } } // Refer to mesh::GriddingAlgorithm for input GriddingAlgorithm{ } // Refer to mesh::BergerRigoutsos for input BergerRigoutsos { sort_output_nodes = TRUE // Makes results repeatable. efficiency_tolerance = 0.85e0 // min % of tag cells in new patch level combine_efficiency = 0.95e0 // chop box if sum of volumes of smaller // boxes < efficiency * vol of large box } // Refer to mesh::StandardTagAndInitialize for input StandardTagAndInitialize { tagging_method = "GRADIENT_DETECTOR" } // Refer to algs::HyperbolicLevelIntegrator for input HyperbolicLevelIntegrator{ cfl = 0.9e0 // max cfl factor used in problem cfl_init = 0.9e0 // initial cfl factor lag_dt_computation = TRUE use_ghosts_to_compute_dt = TRUE } // Refer to algs::TimeRefinementIntegrator for input TimeRefinementIntegrator{ start_time = 0.e0 // initial simulation time end_time = 100.e0 // final simulation time grow_dt = 1.1e0 // growth factor for timesteps max_integrator_steps = 10 // max number of simulation timesteps } // Refer to mesh::TreeLoadBalancer for input LoadBalancer { // using default TreeLoadBalancer configuration } */ integrator->db["CartesianGeometry"]["domain_boxes_0"] = index_box_type{{0, 0, 0}, {125, 125, 125}}; integrator->db["CartesianGeometry"]["x_lo"] = nTuple<double, 3>{0, 0, 0}; integrator->db["CartesianGeometry"]["x_up"] = nTuple<double, 3>{1, 1, 1}; integrator->db["PatchHierarchy"]["max_levels"] = int(3); // Maximum number of levels in hierarchy. integrator->db["PatchHierarchy"]["ratio_to_coarser"]["level_1"] = nTuple<int, 3>{2, 2, 2}; integrator->db["PatchHierarchy"]["ratio_to_coarser"]["level_2"] = nTuple<int, 3>{2, 2, 2}; integrator->db["PatchHierarchy"]["ratio_to_coarser"]["level_3"] = nTuple<int, 3>{2, 2, 2}; integrator->db["PatchHierarchy"]["largest_patch_size"]["level_0"] = nTuple<int, 3>{40, 40, 40}; integrator->db["PatchHierarchy"]["smallest_patch_size"]["level_0"] = nTuple<int, 3>{9, 9, 9}; integrator->db["GriddingAlgorithm"]; integrator->db["BergerRigoutsos"]["sort_output_nodes"] = true;// Makes results repeatable. integrator->db["BergerRigoutsos"]["efficiency_tolerance"] = 0.85; // min % of tag cells in new patch level integrator->db["BergerRigoutsos"]["combine_efficiency"] = 0.95; // chop box if sum of volumes of smaller // // boxes < efficiency * vol of large box // Refer to mesh::StandardTagAndInitialize for input integrator->db["StandardTagAndInitialize"]["tagging_method"] = std::string("GRADIENT_DETECTOR"); // Refer to algs::HyperbolicLevelIntegrator for input integrator->db["HyperbolicLevelIntegrator"]["cfl"] = 0.9; // max cfl factor used in problem integrator->db["HyperbolicLevelIntegrator"]["cfl_init"] = 0.9; // initial cfl factor integrator->db["HyperbolicLevelIntegrator"]["lag_dt_computation"] = true; integrator->db["HyperbolicLevelIntegrator"]["use_ghosts_to_compute_dt"] = true; // Refer to algs::TimeRefinementIntegrator for input integrator->db["TimeRefinementIntegrator"]["start_time"] = 0.e0; // initial simulation time integrator->db["TimeRefinementIntegrator"]["end_time"] = 10.e0; // final simulation time integrator->db["TimeRefinementIntegrator"]["grow_dt"] = 1.1e0; // growth factor for timesteps integrator->db["TimeRefinementIntegrator"]["max_integrator_steps"] = 10; // max number of simulation timesteps // Refer to mesh::TreeLoadBalancer for input integrator->db["LoadBalancer"]; integrator->deploy(); INFORM << "***********************************************" << std::endl; // integrator->print(std::cout); integrator->next_time_step(1.0); INFORM << "***********************************************" << std::endl; integrator->tear_down(); integrator.reset(); INFORM << " DONE !" << std::endl; DONE; } // index_type lo[3] = {0, 0, 0}, hi[3] = {40, 50, 60}; // index_type lo1[3] = {10, 20, 30}, hi1[3] = {20, 30, 40}; // // size_type gw[3] = {0, 0, 0}; // // auto atlas = std::make_shared<mesh::Atlas>(); // auto m0 = atlas->add<DummyMesh>("FirstLevel", lo, hi, gw, 0); // auto m1 = atlas->refine(m0, lo1, hi1); // // std::cout << *atlas << std::endl; // // auto worker = std::make_shared<AMRTest<DummyMesh>>(); // worker->move_to(m0); // TRY_CALL(worker->deploy()); // worker->move_to(m1); // TRY_CALL(worker->deploy()); // worker->E = 1.2; // worker->next_time_step(1.0); // std::cout << " Worker = {" << *worker << "}" << std::endl; // std::cout << "E = {" << worker->E << "}" << std::endl; // std::cout << "E = {" << *worker->E.attribute() << "}" << std::endl; // // auto m = std::make_shared<mesh::MeshBlock>(); // // auto attr = mesh::Attribute::clone(); // auto f = attr->clone(m);<commit_msg>SAMRAI: working ...<commit_after>// // Created by salmon on 16-11-4. // #include <simpla/SIMPLA_config.h> #include <iostream> #include <simpla/mesh/MeshCommon.h> #include <simpla/mesh/Atlas.h> #include <simpla/physics/Field.h> #include <simpla/manifold/Calculus.h> #include <simpla/simulation/TimeIntegrator.h> using namespace simpla; class DummyMesh : public mesh::MeshBlock { public: static constexpr unsigned int ndims = 3; SP_OBJECT_HEAD(DummyMesh, mesh::MeshBlock) template<typename ...Args> DummyMesh(Args &&...args):mesh::MeshBlock(std::forward<Args>(args)...) {} ~DummyMesh() {} template<typename TV, mesh::MeshEntityType IFORM> using data_block_type= mesh::DataBlockArray<Real, IFORM>; virtual std::shared_ptr<mesh::MeshBlock> clone() const { return std::dynamic_pointer_cast<mesh::MeshBlock>(std::make_shared<DummyMesh>()); }; template<typename ...Args> Real eval(Args &&...args) const { return 1.0; }; }; template<typename TM> struct AMRTest : public mesh::Worker { typedef TM mesh_type; SP_OBJECT_HEAD(AMRTest, mesh::Worker); template<typename TV, mesh::MeshEntityType IFORM> using field_type=Field<TV, mesh_type, index_const<IFORM>>; field_type<Real, mesh::VERTEX> phi{"phi", this}; field_type<Real, mesh::EDGE> E{"E", this}; field_type<Real, mesh::FACE> B{"B", this}; field_type<nTuple<Real,3>, mesh::VERTEX> Ev{"Ev", this}; field_type<nTuple<Real,3>, mesh::VERTEX> Bv{"Bv", this}; void next_time_step(Real dt) { // E = grad(-2.0 * phi) * dt; // phi -= diverge(E) * 3.0 * dt; } }; namespace simpla { std::shared_ptr<simulation::TimeIntegrator> create_time_integrator(std::string const &name, std::shared_ptr<mesh::Worker> const &w); }//namespace simpla int main(int argc, char **argv) { logger::set_stdout_level(100); auto worker = std::make_shared<AMRTest<DummyMesh>>(); worker->print(std::cout); auto integrator = simpla::create_time_integrator("AMR_TEST", worker); /** test.3d.input */ /** // Refer to geom::CartesianGridGeometry and its base classes for input CartesianGeometry{ domain_boxes = [ (0,0,0) , (14,9,9) ] x_lo = 0.e0 , 0.e0 , 0.e0 // lower end of computational domain. x_up = 30.e0 , 20.e0 , 20.e0 // upper end of computational domain. } // Refer to hier::PatchHierarchy for input PatchHierarchy { max_levels = 3 // Maximum number of levels in hierarchy. // Note: For the following regridding information, data is required for each // potential in the patch hierarchy; i.e., levels 0 thru max_levels-1. // If more data values than needed are given, only the number required // will be read in. If fewer values are given, an error will result. // // Specify coarsening ratios for each level 1 through max_levels-1 ratio_to_coarser { // vector ratio to next coarser level level_1 = 2 , 2 , 2 level_2 = 2 , 2 , 2 level_3 = 2 , 2 , 2 } largest_patch_size { level_0 = 40 , 40 , 40 // largest patch allowed in hierarchy // all finer levels will use same values as level_0... } smallest_patch_size { level_0 = 9 , 9 , 9 // all finer levels will use same values as level_0... } } // Refer to mesh::GriddingAlgorithm for input GriddingAlgorithm{ } // Refer to mesh::BergerRigoutsos for input BergerRigoutsos { sort_output_nodes = TRUE // Makes results repeatable. efficiency_tolerance = 0.85e0 // min % of tag cells in new patch level combine_efficiency = 0.95e0 // chop box if sum of volumes of smaller // boxes < efficiency * vol of large box } // Refer to mesh::StandardTagAndInitialize for input StandardTagAndInitialize { tagging_method = "GRADIENT_DETECTOR" } // Refer to algs::HyperbolicLevelIntegrator for input HyperbolicLevelIntegrator{ cfl = 0.9e0 // max cfl factor used in problem cfl_init = 0.9e0 // initial cfl factor lag_dt_computation = TRUE use_ghosts_to_compute_dt = TRUE } // Refer to algs::TimeRefinementIntegrator for input TimeRefinementIntegrator{ start_time = 0.e0 // initial simulation time end_time = 100.e0 // final simulation time grow_dt = 1.1e0 // growth factor for timesteps max_integrator_steps = 10 // max number of simulation timesteps } // Refer to mesh::TreeLoadBalancer for input LoadBalancer { // using default TreeLoadBalancer configuration } */ integrator->db["CartesianGeometry"]["domain_boxes_0"] = index_box_type{{0, 0, 0}, {125, 125, 125}}; integrator->db["CartesianGeometry"]["x_lo"] = nTuple<double, 3>{0, 0, 0}; integrator->db["CartesianGeometry"]["x_up"] = nTuple<double, 3>{1, 1, 1}; integrator->db["PatchHierarchy"]["max_levels"] = int(3); // Maximum number of levels in hierarchy. integrator->db["PatchHierarchy"]["ratio_to_coarser"]["level_1"] = nTuple<int, 3>{2, 2, 2}; integrator->db["PatchHierarchy"]["ratio_to_coarser"]["level_2"] = nTuple<int, 3>{2, 2, 2}; integrator->db["PatchHierarchy"]["ratio_to_coarser"]["level_3"] = nTuple<int, 3>{2, 2, 2}; integrator->db["PatchHierarchy"]["largest_patch_size"]["level_0"] = nTuple<int, 3>{40, 40, 40}; integrator->db["PatchHierarchy"]["smallest_patch_size"]["level_0"] = nTuple<int, 3>{9, 9, 9}; integrator->db["GriddingAlgorithm"]; integrator->db["BergerRigoutsos"]["sort_output_nodes"] = true;// Makes results repeatable. integrator->db["BergerRigoutsos"]["efficiency_tolerance"] = 0.85; // min % of tag cells in new patch level integrator->db["BergerRigoutsos"]["combine_efficiency"] = 0.95; // chop box if sum of volumes of smaller // // boxes < efficiency * vol of large box // Refer to mesh::StandardTagAndInitialize for input integrator->db["StandardTagAndInitialize"]["tagging_method"] = std::string("GRADIENT_DETECTOR"); // Refer to algs::HyperbolicLevelIntegrator for input integrator->db["HyperbolicLevelIntegrator"]["cfl"] = 0.9; // max cfl factor used in problem integrator->db["HyperbolicLevelIntegrator"]["cfl_init"] = 0.9; // initial cfl factor integrator->db["HyperbolicLevelIntegrator"]["lag_dt_computation"] = true; integrator->db["HyperbolicLevelIntegrator"]["use_ghosts_to_compute_dt"] = true; // Refer to algs::TimeRefinementIntegrator for input integrator->db["TimeRefinementIntegrator"]["start_time"] = 0.e0; // initial simulation time integrator->db["TimeRefinementIntegrator"]["end_time"] = 10.e0; // final simulation time integrator->db["TimeRefinementIntegrator"]["grow_dt"] = 1.1e0; // growth factor for timesteps integrator->db["TimeRefinementIntegrator"]["max_integrator_steps"] = 10; // max number of simulation timesteps // Refer to mesh::TreeLoadBalancer for input integrator->db["LoadBalancer"]; integrator->deploy(); INFORM << "***********************************************" << std::endl; // integrator->print(std::cout); integrator->next_time_step(1.0); INFORM << "***********************************************" << std::endl; integrator->tear_down(); integrator.reset(); INFORM << " DONE !" << std::endl; DONE; } // index_type lo[3] = {0, 0, 0}, hi[3] = {40, 50, 60}; // index_type lo1[3] = {10, 20, 30}, hi1[3] = {20, 30, 40}; // // size_type gw[3] = {0, 0, 0}; // // auto atlas = std::make_shared<mesh::Atlas>(); // auto m0 = atlas->add<DummyMesh>("FirstLevel", lo, hi, gw, 0); // auto m1 = atlas->refine(m0, lo1, hi1); // // std::cout << *atlas << std::endl; // // auto worker = std::make_shared<AMRTest<DummyMesh>>(); // worker->move_to(m0); // TRY_CALL(worker->deploy()); // worker->move_to(m1); // TRY_CALL(worker->deploy()); // worker->E = 1.2; // worker->next_time_step(1.0); // std::cout << " Worker = {" << *worker << "}" << std::endl; // std::cout << "E = {" << worker->E << "}" << std::endl; // std::cout << "E = {" << *worker->E.attribute() << "}" << std::endl; // // auto m = std::make_shared<mesh::MeshBlock>(); // // auto attr = mesh::Attribute::clone(); // auto f = attr->clone(m);<|endoftext|>
<commit_before>/* -*- mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*- */ // vim: ft=cpp:expandtab:ts=8:sw=4:softtabstop=4: #ident "Copyright (c) 2012-2013 Tokutek Inc. All rights reserved." #ident "$Id$" #include <fcntl.h> #include <string.h> #include <unistd.h> #include <vector> #include <valgrind/valgrind.h> #include <algorithm> #include "backup_test_helpers.h" static const int N=10; static int N_BACKUP_ITERATIONS = 100; static int N_OP_ITERATIONS = 1000000; static const int N_FNAMES = 8; static volatile long counter = N+1; static void* do_backups(void *v) { check(v==NULL); for (int i=0; i<N_BACKUP_ITERATIONS; i++) { setup_destination(); pthread_t thread; start_backup_thread(&thread); finish_backup_thread(thread); } __sync_fetch_and_add(&counter, -1); while (counter>0) { fprintf(stderr, "Doing a backup waiting for clients\n"); pthread_t thread; start_backup_thread(&thread); finish_backup_thread(thread); sched_yield(); if (RUNNING_ON_VALGRIND) usleep(100); // do some more resting to ease up on the valgrind time. } return v; } static volatile int open_results[2]; static char *fnames[N_FNAMES]; static void do_client_once(std::vector<int> *fds) { const int casesize = 2; switch(random()%casesize) { case 0: { char *name = fnames[random()%N_FNAMES]; int excl_flags = random()%2 ? O_EXCL : 0; int creat_flags = random()%2 ? O_CREAT : 0; int fd = open(name, excl_flags | O_RDWR | creat_flags, 0777); if (fd>=0) { fds->push_back(fd); } __sync_fetch_and_add(&open_results[fd>=0 ? 0 : 1], 1); break; } case 1: { if (fds->size()>0) { size_t idx = random() % fds->size(); int fd = (*fds)[idx]; int endfd = (*fds)[fds->size()-1]; (*fds)[idx] = endfd; fds->pop_back(); int r = close(fd); check(r==0); } break; } } } static void* do_client(void *v) { int me = *(int*)v; check(0<=me && me<N); std::vector<int> fds; fds.push_back(3); check(fds[0]==3); fds.pop_back(); for (int i=0; i<N_OP_ITERATIONS; i++) { do_client_once(&fds); if (RUNNING_ON_VALGRIND) { fprintf(stderr, "."); } // For some reason, printing something makes drd stop getting stuck. } fprintf(stderr, "Client %d done, doing more work till the others are done (fds.size=%ld)\n", me, fds.size()); __sync_fetch_and_add(&counter, -1); while (counter>0) { do_client_once(&fds); if (RUNNING_ON_VALGRIND) sched_yield(); // do some more resting to ease up on the valgrind time. } while (fds.size()>0) { int fd = fds[fds.size()-1]; fds.pop_back(); int r = close(fd); check(r==0); } return v; } int test_main(int argc __attribute__((__unused__)), const char *argv[] __attribute__((__unused__))) { if (RUNNING_ON_VALGRIND) { N_OP_ITERATIONS = std::max(N_OP_ITERATIONS/5000,200); // do less work if we are in valgrind N_BACKUP_ITERATIONS = std::max(N_BACKUP_ITERATIONS/10, 10); } fprintf(stderr, "N_OP_ITERATIONS=%d N_BACKUP_ITERATIONS=%d\n", N_OP_ITERATIONS, N_BACKUP_ITERATIONS); setup_source(); setup_destination(); char *src = get_src(); int len = strlen(src)+10; for (int i=0; i<N_FNAMES; i++) { fnames[i] = (char*)malloc(len); int r = snprintf(fnames[i], len, "%s/A", src); check(r<len); } pthread_t backups; { int r = pthread_create(&backups, NULL, do_backups, NULL); check(r==0); } pthread_t clients[N]; int id[N]; for (int i=0; i<N; i++) { id[i] = i; int r = pthread_create(&clients[i], NULL, do_client, &id[i]); check(r==0); } { void *v; int r = pthread_join(backups, &v); check(r==0 && v==NULL); } for (int i=0; i<N; i++) { void *v; int r = pthread_join(clients[i], &v); check(r==0 && v==(void*)&id[i]); } cleanup_dirs(); printf("open %d ok, %d failed\n", open_results[0], open_results[1]); free(src); for (int i=0; i<N_FNAMES; i++) { free(fnames[i]); } return 0; } template class std::vector<int>; <commit_msg>Fix #25<commit_after>/* -*- mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*- */ // vim: ft=cpp:expandtab:ts=8:sw=4:softtabstop=4: #ident "Copyright (c) 2012-2013 Tokutek Inc. All rights reserved." #ident "$Id$" #include <fcntl.h> #include <string.h> #include <unistd.h> #include <vector> #include <valgrind/valgrind.h> #include <algorithm> #include "backup_test_helpers.h" static const int N=10; static int N_BACKUP_ITERATIONS = 100; static int N_OP_ITERATIONS = 1000000; static const int N_FNAMES = 8; static volatile long counter = N+1; static void* do_backups(void *v) { check(v==NULL); for (int i=0; i<N_BACKUP_ITERATIONS; i++) { setup_destination(); pthread_t thread; start_backup_thread(&thread); finish_backup_thread(thread); } __sync_fetch_and_add(&counter, -1); while (counter>0) { fprintf(stderr, "Doing a backup waiting for clients\n"); setup_destination(); pthread_t thread; start_backup_thread(&thread); finish_backup_thread(thread); sched_yield(); if (RUNNING_ON_VALGRIND) usleep(100); // do some more resting to ease up on the valgrind time. } return v; } static volatile int open_results[2]; static char *fnames[N_FNAMES]; static void do_client_once(std::vector<int> *fds) { const int casesize = 2; switch(random()%casesize) { case 0: { char *name = fnames[random()%N_FNAMES]; int excl_flags = random()%2 ? O_EXCL : 0; int creat_flags = random()%2 ? O_CREAT : 0; int fd = open(name, excl_flags | O_RDWR | creat_flags, 0777); if (fd>=0) { fds->push_back(fd); } __sync_fetch_and_add(&open_results[fd>=0 ? 0 : 1], 1); break; } case 1: { if (fds->size()>0) { size_t idx = random() % fds->size(); int fd = (*fds)[idx]; int endfd = (*fds)[fds->size()-1]; (*fds)[idx] = endfd; fds->pop_back(); int r = close(fd); check(r==0); } break; } } } static void* do_client(void *v) { int me = *(int*)v; check(0<=me && me<N); std::vector<int> fds; fds.push_back(3); check(fds[0]==3); fds.pop_back(); for (int i=0; i<N_OP_ITERATIONS; i++) { do_client_once(&fds); if (RUNNING_ON_VALGRIND) { fprintf(stderr, "."); } // For some reason, printing something makes drd stop getting stuck. } fprintf(stderr, "Client %d done, doing more work till the others are done (fds.size=%ld)\n", me, fds.size()); __sync_fetch_and_add(&counter, -1); while (counter>0) { do_client_once(&fds); if (RUNNING_ON_VALGRIND) sched_yield(); // do some more resting to ease up on the valgrind time. } while (fds.size()>0) { int fd = fds[fds.size()-1]; fds.pop_back(); int r = close(fd); check(r==0); } return v; } int test_main(int argc __attribute__((__unused__)), const char *argv[] __attribute__((__unused__))) { if (RUNNING_ON_VALGRIND) { N_OP_ITERATIONS = std::max(N_OP_ITERATIONS/5000,200); // do less work if we are in valgrind N_BACKUP_ITERATIONS = std::max(N_BACKUP_ITERATIONS/10, 10); } fprintf(stderr, "N_OP_ITERATIONS=%d N_BACKUP_ITERATIONS=%d\n", N_OP_ITERATIONS, N_BACKUP_ITERATIONS); setup_source(); setup_destination(); char *src = get_src(); int len = strlen(src)+10; for (int i=0; i<N_FNAMES; i++) { fnames[i] = (char*)malloc(len); int r = snprintf(fnames[i], len, "%s/A", src); check(r<len); } pthread_t backups; { int r = pthread_create(&backups, NULL, do_backups, NULL); check(r==0); } pthread_t clients[N]; int id[N]; for (int i=0; i<N; i++) { id[i] = i; int r = pthread_create(&clients[i], NULL, do_client, &id[i]); check(r==0); } { void *v; int r = pthread_join(backups, &v); check(r==0 && v==NULL); } for (int i=0; i<N; i++) { void *v; int r = pthread_join(clients[i], &v); check(r==0 && v==(void*)&id[i]); } cleanup_dirs(); printf("open %d ok, %d failed\n", open_results[0], open_results[1]); free(src); for (int i=0; i<N_FNAMES; i++) { free(fnames[i]); } return 0; } template class std::vector<int>; <|endoftext|>