<commit_before>// {{{ Copyright notice
/* Copyright (c) 2007-2009, Adam Harvey
 *
 * 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.
 *  - The names of its contributors may not be used to endorse or promote
 *  products derived from this software without specific prior written
 *  permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */
// }}}

#include "ConnectionPage.h"
#include "ArtProvider.h"
#include "Dubnium.h"
#include "PaneMenu.h"

#include <wx/artprov.h>
#include <wx/log.h>
#include <wx/sizer.h>
#include <wx/toolbar.h>

// {{{ Event table
BEGIN_EVENT_TABLE(ConnectionPage, wxPanel)
	EVT_DBGP_STATUSCHANGE(wxID_ANY, ConnectionPage::OnStatusChange)
	EVT_DBGP_STDERR(wxID_ANY, ConnectionPage::OnStderr)
	EVT_DBGP_STDOUT(wxID_ANY, ConnectionPage::OnStdout)
	EVT_TOOL(ID_CONNECTIONPAGE_BREAK, ConnectionPage::OnBreak)
	EVT_TOOL(ID_CONNECTIONPAGE_PANES, ConnectionPage::OnPanes)
	EVT_TOOL(ID_CONNECTIONPAGE_RUN, ConnectionPage::OnRun)
	EVT_TOOL(ID_CONNECTIONPAGE_RUN_TO_CURSOR, ConnectionPage::OnRunToCursor)
	EVT_TOOL(ID_CONNECTIONPAGE_STEPINTO, ConnectionPage::OnStepInto)
	EVT_TOOL(ID_CONNECTIONPAGE_STEPOUT, ConnectionPage::OnStepOut)
	EVT_TOOL(ID_CONNECTIONPAGE_STEPOVER, ConnectionPage::OnStepOver)
END_EVENT_TABLE()
// }}}

// {{{ ConnectionPage::ConnectionPage(wxWindow *parent, DBGp::Connection *conn, const wxString &fileURI, const wxString &language)
ConnectionPage::ConnectionPage(wxWindow *parent, DBGp::Connection *conn, const wxString &fileURI, const wxString &language) : wxPanel(parent, ID_CONNECTIONPAGE), conn(conn), language(language), level(level), script(fileURI), unavailable(true) {
	config = wxConfigBase::Get();

	conn->SetEventHandler(this);
	breakSupported = conn->CommandSupported(wxT("break"));

	CreateToolBar();
	breakpoint = new BreakpointPanel(this);
	output = new OutputPanel(this);
	properties = new PropertiesPanel(this);
	source = new SourcePanel(this);
	stack = new StackPanel(this);

	SetSource(fileURI);

	wxAuiPaneInfo defaultPane;
	defaultPane.Floatable(false).CloseButton(true);

	mgr = new wxAuiManager(this);
	mgr->AddPane(toolbar, wxAuiPaneInfo().ToolbarPane().Top().Position(0).Floatable(false));
	mgr->AddPane(output, wxAuiPaneInfo(defaultPane).Bottom().Position(0).Caption(_("Output")).MinSize(wxSize(1, 150)));
	mgr->AddPane(breakpoint, wxAuiPaneInfo(defaultPane).Bottom().Position(2).Caption(_("Breakpoints")).MinSize(wxSize(1, 150)));
	mgr->AddPane(stack, wxAuiPaneInfo(defaultPane).Right().Position(0).Caption(_("Call Stack")).MinSize(wxSize(200, 1)));
	mgr->AddPane(properties, wxAuiPaneInfo(defaultPane).Right().Position(1).Caption(_("Properties")).MinSize(wxSize(200, 1)));
	mgr->AddPane(source, wxAuiPaneInfo().CentrePane().Caption(_("Source")).CaptionVisible(true));

#ifdef PERSPECTIVE
	wxString perspective(config->Read(wxT("Perspective"), wxEmptyString));
	if (perspective.Len() > 0) {
		mgr->LoadPerspective(perspective);
	}
#endif

	mgr->Update();
	RestoreStickyBreakpoints();
}
// }}}

// {{{ void ConnectionPage::BreakpointAdd(int line, bool temporary)
void ConnectionPage::BreakpointAdd(int line, bool temporary) {
	if (!unavailable) {
		DBGp::Breakpoint *bp = conn->CreateBreakpoint();

		bp->SetLineType(lastFile, line);
		if (temporary) {
			bp->SetTemporary(true);
		}
		bp->Set();

		if (temporary) {
			conn->Run();
		}
		else {
			breakpoint->Update();
		}
	}
}
// }}}
// {{{ void ConnectionPage::BreakpointRemove(const wxString &file, int line)
void ConnectionPage::BreakpointRemove(const wxString &file, int line) {
	source->tc->SetBreakpointStyle(line, false);
}
// }}}
// {{{ void ConnectionPage::BreakpointRemove(int line)
void ConnectionPage::BreakpointRemove(int line) {
	if (!unavailable) {
		DBGp::Breakpoint *bp = breakpoint->GetFileBreakpoint(lastFile, line);

		if (bp) {
			conn->RemoveBreakpoint(bp);
			breakpoint->Update();
		}
	}
}
// }}}
// {{{ DBGp::Property *ConnectionPage::GetProperty(const wxString &name)
DBGp::Property *ConnectionPage::GetProperty(const wxString &name) {
	return properties->GetProperty(name);
}
// }}}
// {{{ wxString ConnectionPage::GetPropertyValue(const wxString &name) const
wxString ConnectionPage::GetPropertyValue(const wxString &name) const {
	return properties->GetPropertyValue(name);
}
// }}}
// {{{ void ConnectionPage::SavePerspective()
void ConnectionPage::SavePerspective() {
	config->Write(wxT("Perspective"), mgr->SavePerspective());
}
// }}}
// {{{ void ConnectionPage::SetStackLevel(DBGp::StackLevel *level)
void ConnectionPage::SetStackLevel(DBGp::StackLevel *level) {
	this->level = level;
	properties->SetStackLevel(level);
	SetSource(level->GetFileName(), level->GetLineNo());
}
// }}}

// {{{ void ConnectionPage::CreateToolBar()
void ConnectionPage::CreateToolBar() {
	wxSize size(ArtProvider::toolbarSize, ArtProvider::toolbarSize);
	toolbar = new wxToolBar(this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTB_HORIZONTAL | wxNO_BORDER | wxTB_FLAT | wxTB_NODIVIDER);
	toolbar->SetToolBitmapSize(size);

	toolbar->AddTool(ID_CONNECTIONPAGE_OPEN, _("Open"), wxArtProvider::GetBitmap(wxART_FILE_OPEN, wxART_TOOLBAR, size), _("Open a source file"));
	toolbar->AddSeparator();
	toolbar->AddTool(ID_CONNECTIONPAGE_RUN, _("Run"), wxArtProvider::GetBitmap(wxT("run"), wxART_TOOLBAR, size), _("Run"));
	if (breakSupported) {
		toolbar->AddTool(ID_CONNECTIONPAGE_BREAK, _("Break"), wxArtProvider::GetBitmap(wxT("break"), wxART_TOOLBAR, size), _("Break"));
	}
	toolbar->AddTool(ID_CONNECTIONPAGE_STEPINTO, _("Step Into"), wxArtProvider::GetBitmap(wxT("step-into"), wxART_TOOLBAR, size), _("Step Into"));
	toolbar->AddTool(ID_CONNECTIONPAGE_STEPOVER, _("Step Over"), wxArtProvider::GetBitmap(wxT("step-over"), wxART_TOOLBAR, size), _("Step Over"));
	toolbar->AddTool(ID_CONNECTIONPAGE_STEPOUT, _("Step Out"), wxArtProvider::GetBitmap(wxT("step-out"), wxART_TOOLBAR, size), _("Step Out"));
	toolbar->AddSeparator();
	toolbar->AddTool(ID_CONNECTIONPAGE_RUN_TO_CURSOR, _("Run to Cursor"), wxArtProvider::GetBitmap(wxT("run-to-cursor"), wxART_TOOLBAR, size), _("Run to Cursor"));
	toolbar->AddSeparator();
	toolbar->AddTool(ID_CONNECTIONPAGE_PANES, _("Panes"), wxArtProvider::GetBitmap(wxT("panes"), wxART_TOOLBAR, size), _("Toggle which panes are displayed"));
	toolbar->Realize();

	// Disable the tools that don't make sense at the start.
	UpdateToolBar(true, false, true, false, false);
}
// }}}
// {{{ void ConnectionPage::OnBreak(wxCommandEvent &event)
void ConnectionPage::OnBreak(wxCommandEvent &event) {
	conn->Break();
}
// }}}
// {{{ void ConnectionPage::OnPanes(wxCommandEvent &event)
void ConnectionPage::OnPanes(wxCommandEvent &event) {
	PaneMenu menu(this, _("Panes"), mgr->GetAllPanes());
	PopupMenu(&menu);
	wxAuiPaneInfo *pane = menu.GetPane();
	if (pane) {
		pane->Show(!(pane->IsShown()));
		mgr->Update();
	}
}
// }}}
// {{{ void ConnectionPage::OnRun(wxCommandEvent &event)
void ConnectionPage::OnRun(wxCommandEvent &event) {
	UpdateToolBar(false, true, false, false, false);
	conn->Run();
}
// }}}
// {{{ void ConnectionPage::OnRunToCursor(wxCommandEvent &event)
void ConnectionPage::OnRunToCursor(wxCommandEvent &event) {
	DBGp::Breakpoint *bp;
	int line = source->tc->LineFromPosition(source->tc->GetCurrentPos()) + 1;

	bp = conn->CreateBreakpoint();
	bp->SetLineType(lastFile, line);
	bp->SetTemporary(true);
	bp->Set();

	UpdateToolBar(false, true, false, false, false);
	conn->Run();
}
// }}}
// {{{ void ConnectionPage::OnStatusChange(DBGp::StatusChangeEvent &event)
void ConnectionPage::OnStatusChange(DBGp::StatusChangeEvent &event) {
	if (event.GetStatus() == DBGp::Connection::BREAK) {
		UpdateToolBar(true, false, true, true, true);
		UpdateStack();
	}
	else if (event.GetStatus() == DBGp::Connection::RUNNING) {
		UpdateToolBar(false, true, false, false, false);
	}
	else {
		UpdateToolBar(false, false, false, false, false);
		breakpoint->Enable(false);
		stack->SetStack(NULL);
		properties->SetStackLevel(NULL);
		source->Unavailable(_("No source is available as execution has finished."));
		unavailable = true;
	}
}
// }}}
// {{{ void ConnectionPage::OnStderr(DBGp::StderrEvent &event)
void ConnectionPage::OnStderr(DBGp::StderrEvent &event) {
	output->AppendStderr(event.GetData());
}
// }}}
// {{{ void ConnectionPage::OnStdout(DBGp::StdoutEvent &event)
void ConnectionPage::OnStdout(DBGp::StdoutEvent &event) {
	output->AppendStdout(event.GetData());
}
// }}}
// {{{ void ConnectionPage::OnStepInto(wxCommandEvent &event)
void ConnectionPage::OnStepInto(wxCommandEvent &event) {
	conn->StepInto();
}
// }}}
// {{{ void ConnectionPage::OnStepOut(wxCommandEvent &event)
void ConnectionPage::OnStepOut(wxCommandEvent &event) {
	conn->StepOut();
}
// }}}
// {{{ void ConnectionPage::OnStepOver(wxCommandEvent &event)
void ConnectionPage::OnStepOver(wxCommandEvent &event) {
	conn->StepOver();
}
// }}}
// {{{ void ConnectionPage::RestoreStickyBreakpoints()
void ConnectionPage::RestoreStickyBreakpoints() {
	std::vector<StickyBreakpoint> breakpoints(wxGetApp().GetStickyBreakpoints(script));

	wxLogDebug(wxT("Restoring sticky breakpoints for script %s..."), script.c_str());

	for (std::vector<StickyBreakpoint>::iterator i = breakpoints.begin(); i != breakpoints.end(); i++) {
		DBGp::Breakpoint *bp = conn->CreateBreakpoint();

		switch (i->GetType()) {
			case DBGp::Breakpoint::CALL:
				wxLogDebug(wxT("Sticky breakpoint of CALL type: %s."), i->GetArgument().c_str());
				bp->SetCallType(i->GetArgument());
				break;

			case DBGp::Breakpoint::EXCEPTION:
				wxLogDebug(wxT("Sticky breakpoint of EXCEPTION type: %s."), i->GetArgument().c_str());
				bp->SetExceptionType(i->GetArgument());
				break;

			case DBGp::Breakpoint::RETURN:
				wxLogDebug(wxT("Sticky breakpoint of RETURN type: %s."), i->GetArgument().c_str());
				bp->SetReturnType(i->GetArgument());
				break;

			default:
				wxLogError(wxT("Sticky breakpoint of unknown type."));
				break;
		}

		bp->Set();
	}

	breakpoint->Update();
}
// }}}
// {{{ void ConnectionPage::SetSource(const wxString &file, int line)
void ConnectionPage::SetSource(const wxString &file, int line) {
	if (file != lastFile) {
		try {
			source->tc->SetSource(conn->Source(file), line);
			source->tc->SetLexerLanguage(language);
			lastFile = file;
			DBGp::Connection::BreakpointList list(breakpoint->GetFileBreakpoints(file));
			for (DBGp::Connection::BreakpointList::const_iterator i = list.begin(); i != list.end(); i++) {
				source->tc->SetBreakpointStyle((*i)->GetLineNo(), true);
			}
			unavailable = false;
		}
		catch (DBGp::Error e) {
			source->Unavailable(_("No source is available for this stack frame."));
			unavailable = true;
		}
	}
	else if (line >= 0) {
		source->tc->SetLine(line);
	}
}
// }}}
// {{{ void ConnectionPage::UpdateStack()
void ConnectionPage::UpdateStack() {
	DBGp::Stack stack(conn->StackGet());
	this->stack->SetStack(&stack);
	SetStackLevel(stack.GetLevel(0));
}
// }}}
// {{{ void ConnectionPage::UpdateToolBar(bool run, bool brk, bool stepInto, bool stepOver, bool stepOut)
void ConnectionPage::UpdateToolBar(bool run, bool brk, bool stepInto, bool stepOver, bool stepOut) {
	toolbar->EnableTool(ID_CONNECTIONPAGE_RUN, run);
	toolbar->EnableTool(ID_CONNECTIONPAGE_BREAK, brk);
	toolbar->EnableTool(ID_CONNECTIONPAGE_STEPINTO, stepInto);
	toolbar->EnableTool(ID_CONNECTIONPAGE_STEPOVER, stepOver);
	toolbar->EnableTool(ID_CONNECTIONPAGE_STEPOUT, stepOut);
	toolbar->EnableTool(ID_CONNECTIONPAGE_RUN_TO_CURSOR, run);
}
// }}}

// vim:set fdm=marker ts=8 sw=8 noet cin:
<commit_msg>Disabled the useless open file toolbar button.<commit_after>// {{{ Copyright notice
/* Copyright (c) 2007-2009, Adam Harvey
 *
 * 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.
 *  - The names of its contributors may not be used to endorse or promote
 *  products derived from this software without specific prior written
 *  permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */
// }}}

#include "ConnectionPage.h"
#include "ArtProvider.h"
#include "Dubnium.h"
#include "PaneMenu.h"

#include <wx/artprov.h>
#include <wx/log.h>
#include <wx/sizer.h>
#include <wx/toolbar.h>

// {{{ Event table
BEGIN_EVENT_TABLE(ConnectionPage, wxPanel)
	EVT_DBGP_STATUSCHANGE(wxID_ANY, ConnectionPage::OnStatusChange)
	EVT_DBGP_STDERR(wxID_ANY, ConnectionPage::OnStderr)
	EVT_DBGP_STDOUT(wxID_ANY, ConnectionPage::OnStdout)
	EVT_TOOL(ID_CONNECTIONPAGE_BREAK, ConnectionPage::OnBreak)
	EVT_TOOL(ID_CONNECTIONPAGE_PANES, ConnectionPage::OnPanes)
	EVT_TOOL(ID_CONNECTIONPAGE_RUN, ConnectionPage::OnRun)
	EVT_TOOL(ID_CONNECTIONPAGE_RUN_TO_CURSOR, ConnectionPage::OnRunToCursor)
	EVT_TOOL(ID_CONNECTIONPAGE_STEPINTO, ConnectionPage::OnStepInto)
	EVT_TOOL(ID_CONNECTIONPAGE_STEPOUT, ConnectionPage::OnStepOut)
	EVT_TOOL(ID_CONNECTIONPAGE_STEPOVER, ConnectionPage::OnStepOver)
END_EVENT_TABLE()
// }}}

// {{{ ConnectionPage::ConnectionPage(wxWindow *parent, DBGp::Connection *conn, const wxString &fileURI, const wxString &language)
ConnectionPage::ConnectionPage(wxWindow *parent, DBGp::Connection *conn, const wxString &fileURI, const wxString &language) : wxPanel(parent, ID_CONNECTIONPAGE), conn(conn), language(language), level(level), script(fileURI), unavailable(true) {
	config = wxConfigBase::Get();

	conn->SetEventHandler(this);
	breakSupported = conn->CommandSupported(wxT("break"));

	CreateToolBar();
	breakpoint = new BreakpointPanel(this);
	output = new OutputPanel(this);
	properties = new PropertiesPanel(this);
	source = new SourcePanel(this);
	stack = new StackPanel(this);

	SetSource(fileURI);

	wxAuiPaneInfo defaultPane;
	defaultPane.Floatable(false).CloseButton(true);

	mgr = new wxAuiManager(this);
	mgr->AddPane(toolbar, wxAuiPaneInfo().ToolbarPane().Top().Position(0).Floatable(false));
	mgr->AddPane(output, wxAuiPaneInfo(defaultPane).Bottom().Position(0).Caption(_("Output")).MinSize(wxSize(1, 150)));
	mgr->AddPane(breakpoint, wxAuiPaneInfo(defaultPane).Bottom().Position(2).Caption(_("Breakpoints")).MinSize(wxSize(1, 150)));
	mgr->AddPane(stack, wxAuiPaneInfo(defaultPane).Right().Position(0).Caption(_("Call Stack")).MinSize(wxSize(200, 1)));
	mgr->AddPane(properties, wxAuiPaneInfo(defaultPane).Right().Position(1).Caption(_("Properties")).MinSize(wxSize(200, 1)));
	mgr->AddPane(source, wxAuiPaneInfo().CentrePane().Caption(_("Source")).CaptionVisible(true));

#ifdef PERSPECTIVE
	wxString perspective(config->Read(wxT("Perspective"), wxEmptyString));
	if (perspective.Len() > 0) {
		mgr->LoadPerspective(perspective);
	}
#endif

	mgr->Update();
	RestoreStickyBreakpoints();
}
// }}}

// {{{ void ConnectionPage::BreakpointAdd(int line, bool temporary)
void ConnectionPage::BreakpointAdd(int line, bool temporary) {
	if (!unavailable) {
		DBGp::Breakpoint *bp = conn->CreateBreakpoint();

		bp->SetLineType(lastFile, line);
		if (temporary) {
			bp->SetTemporary(true);
		}
		bp->Set();

		if (temporary) {
			conn->Run();
		}
		else {
			breakpoint->Update();
		}
	}
}
// }}}
// {{{ void ConnectionPage::BreakpointRemove(const wxString &file, int line)
void ConnectionPage::BreakpointRemove(const wxString &file, int line) {
	source->tc->SetBreakpointStyle(line, false);
}
// }}}
// {{{ void ConnectionPage::BreakpointRemove(int line)
void ConnectionPage::BreakpointRemove(int line) {
	if (!unavailable) {
		DBGp::Breakpoint *bp = breakpoint->GetFileBreakpoint(lastFile, line);

		if (bp) {
			conn->RemoveBreakpoint(bp);
			breakpoint->Update();
		}
	}
}
// }}}
// {{{ DBGp::Property *ConnectionPage::GetProperty(const wxString &name)
DBGp::Property *ConnectionPage::GetProperty(const wxString &name) {
	return properties->GetProperty(name);
}
// }}}
// {{{ wxString ConnectionPage::GetPropertyValue(const wxString &name) const
wxString ConnectionPage::GetPropertyValue(const wxString &name) const {
	return properties->GetPropertyValue(name);
}
// }}}
// {{{ void ConnectionPage::SavePerspective()
void ConnectionPage::SavePerspective() {
	config->Write(wxT("Perspective"), mgr->SavePerspective());
}
// }}}
// {{{ void ConnectionPage::SetStackLevel(DBGp::StackLevel *level)
void ConnectionPage::SetStackLevel(DBGp::StackLevel *level) {
	this->level = level;
	properties->SetStackLevel(level);
	SetSource(level->GetFileName(), level->GetLineNo());
}
// }}}

// {{{ void ConnectionPage::CreateToolBar()
void ConnectionPage::CreateToolBar() {
	wxSize size(ArtProvider::toolbarSize, ArtProvider::toolbarSize);
	toolbar = new wxToolBar(this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTB_HORIZONTAL | wxNO_BORDER | wxTB_FLAT | wxTB_NODIVIDER);
	toolbar->SetToolBitmapSize(size);

#if 0
	toolbar->AddTool(ID_CONNECTIONPAGE_OPEN, _("Open"), wxArtProvider::GetBitmap(wxART_FILE_OPEN, wxART_TOOLBAR, size), _("Open a source file"));
	toolbar->AddSeparator();
#endif

	toolbar->AddTool(ID_CONNECTIONPAGE_RUN, _("Run"), wxArtProvider::GetBitmap(wxT("run"), wxART_TOOLBAR, size), _("Run"));
	if (breakSupported) {
		toolbar->AddTool(ID_CONNECTIONPAGE_BREAK, _("Break"), wxArtProvider::GetBitmap(wxT("break"), wxART_TOOLBAR, size), _("Break"));
	}
	toolbar->AddTool(ID_CONNECTIONPAGE_STEPINTO, _("Step Into"), wxArtProvider::GetBitmap(wxT("step-into"), wxART_TOOLBAR, size), _("Step Into"));
	toolbar->AddTool(ID_CONNECTIONPAGE_STEPOVER, _("Step Over"), wxArtProvider::GetBitmap(wxT("step-over"), wxART_TOOLBAR, size), _("Step Over"));
	toolbar->AddTool(ID_CONNECTIONPAGE_STEPOUT, _("Step Out"), wxArtProvider::GetBitmap(wxT("step-out"), wxART_TOOLBAR, size), _("Step Out"));
	toolbar->AddSeparator();
	toolbar->AddTool(ID_CONNECTIONPAGE_RUN_TO_CURSOR, _("Run to Cursor"), wxArtProvider::GetBitmap(wxT("run-to-cursor"), wxART_TOOLBAR, size), _("Run to Cursor"));
	toolbar->AddSeparator();
	toolbar->AddTool(ID_CONNECTIONPAGE_PANES, _("Panes"), wxArtProvider::GetBitmap(wxT("panes"), wxART_TOOLBAR, size), _("Toggle which panes are displayed"));
	toolbar->Realize();

	// Disable the tools that don't make sense at the start.
	UpdateToolBar(true, false, true, false, false);
}
// }}}
// {{{ void ConnectionPage::OnBreak(wxCommandEvent &event)
void ConnectionPage::OnBreak(wxCommandEvent &event) {
	conn->Break();
}
// }}}
// {{{ void ConnectionPage::OnPanes(wxCommandEvent &event)
void ConnectionPage::OnPanes(wxCommandEvent &event) {
	PaneMenu menu(this, _("Panes"), mgr->GetAllPanes());
	PopupMenu(&menu);
	wxAuiPaneInfo *pane = menu.GetPane();
	if (pane) {
		pane->Show(!(pane->IsShown()));
		mgr->Update();
	}
}
// }}}
// {{{ void ConnectionPage::OnRun(wxCommandEvent &event)
void ConnectionPage::OnRun(wxCommandEvent &event) {
	UpdateToolBar(false, true, false, false, false);
	conn->Run();
}
// }}}
// {{{ void ConnectionPage::OnRunToCursor(wxCommandEvent &event)
void ConnectionPage::OnRunToCursor(wxCommandEvent &event) {
	DBGp::Breakpoint *bp;
	int line = source->tc->LineFromPosition(source->tc->GetCurrentPos()) + 1;

	bp = conn->CreateBreakpoint();
	bp->SetLineType(lastFile, line);
	bp->SetTemporary(true);
	bp->Set();

	UpdateToolBar(false, true, false, false, false);
	conn->Run();
}
// }}}
// {{{ void ConnectionPage::OnStatusChange(DBGp::StatusChangeEvent &event)
void ConnectionPage::OnStatusChange(DBGp::StatusChangeEvent &event) {
	if (event.GetStatus() == DBGp::Connection::BREAK) {
		UpdateToolBar(true, false, true, true, true);
		UpdateStack();
	}
	else if (event.GetStatus() == DBGp::Connection::RUNNING) {
		UpdateToolBar(false, true, false, false, false);
	}
	else {
		UpdateToolBar(false, false, false, false, false);
		breakpoint->Enable(false);
		stack->SetStack(NULL);
		properties->SetStackLevel(NULL);
		source->Unavailable(_("No source is available as execution has finished."));
		unavailable = true;
	}
}
// }}}
// {{{ void ConnectionPage::OnStderr(DBGp::StderrEvent &event)
void ConnectionPage::OnStderr(DBGp::StderrEvent &event) {
	output->AppendStderr(event.GetData());
}
// }}}
// {{{ void ConnectionPage::OnStdout(DBGp::StdoutEvent &event)
void ConnectionPage::OnStdout(DBGp::StdoutEvent &event) {
	output->AppendStdout(event.GetData());
}
// }}}
// {{{ void ConnectionPage::OnStepInto(wxCommandEvent &event)
void ConnectionPage::OnStepInto(wxCommandEvent &event) {
	conn->StepInto();
}
// }}}
// {{{ void ConnectionPage::OnStepOut(wxCommandEvent &event)
void ConnectionPage::OnStepOut(wxCommandEvent &event) {
	conn->StepOut();
}
// }}}
// {{{ void ConnectionPage::OnStepOver(wxCommandEvent &event)
void ConnectionPage::OnStepOver(wxCommandEvent &event) {
	conn->StepOver();
}
// }}}
// {{{ void ConnectionPage::RestoreStickyBreakpoints()
void ConnectionPage::RestoreStickyBreakpoints() {
	std::vector<StickyBreakpoint> breakpoints(wxGetApp().GetStickyBreakpoints(script));

	wxLogDebug(wxT("Restoring sticky breakpoints for script %s..."), script.c_str());

	for (std::vector<StickyBreakpoint>::iterator i = breakpoints.begin(); i != breakpoints.end(); i++) {
		DBGp::Breakpoint *bp = conn->CreateBreakpoint();

		switch (i->GetType()) {
			case DBGp::Breakpoint::CALL:
				wxLogDebug(wxT("Sticky breakpoint of CALL type: %s."), i->GetArgument().c_str());
				bp->SetCallType(i->GetArgument());
				break;

			case DBGp::Breakpoint::EXCEPTION:
				wxLogDebug(wxT("Sticky breakpoint of EXCEPTION type: %s."), i->GetArgument().c_str());
				bp->SetExceptionType(i->GetArgument());
				break;

			case DBGp::Breakpoint::RETURN:
				wxLogDebug(wxT("Sticky breakpoint of RETURN type: %s."), i->GetArgument().c_str());
				bp->SetReturnType(i->GetArgument());
				break;

			default:
				wxLogError(wxT("Sticky breakpoint of unknown type."));
				break;
		}

		bp->Set();
	}

	breakpoint->Update();
}
// }}}
// {{{ void ConnectionPage::SetSource(const wxString &file, int line)
void ConnectionPage::SetSource(const wxString &file, int line) {
	if (file != lastFile) {
		try {
			source->tc->SetSource(conn->Source(file), line);
			source->tc->SetLexerLanguage(language);
			lastFile = file;
			DBGp::Connection::BreakpointList list(breakpoint->GetFileBreakpoints(file));
			for (DBGp::Connection::BreakpointList::const_iterator i = list.begin(); i != list.end(); i++) {
				source->tc->SetBreakpointStyle((*i)->GetLineNo(), true);
			}
			unavailable = false;
		}
		catch (DBGp::Error e) {
			source->Unavailable(_("No source is available for this stack frame."));
			unavailable = true;
		}
	}
	else if (line >= 0) {
		source->tc->SetLine(line);
	}
}
// }}}
// {{{ void ConnectionPage::UpdateStack()
void ConnectionPage::UpdateStack() {
	DBGp::Stack stack(conn->StackGet());
	this->stack->SetStack(&stack);
	SetStackLevel(stack.GetLevel(0));
}
// }}}
// {{{ void ConnectionPage::UpdateToolBar(bool run, bool brk, bool stepInto, bool stepOver, bool stepOut)
void ConnectionPage::UpdateToolBar(bool run, bool brk, bool stepInto, bool stepOver, bool stepOut) {
	toolbar->EnableTool(ID_CONNECTIONPAGE_RUN, run);
	toolbar->EnableTool(ID_CONNECTIONPAGE_BREAK, brk);
	toolbar->EnableTool(ID_CONNECTIONPAGE_STEPINTO, stepInto);
	toolbar->EnableTool(ID_CONNECTIONPAGE_STEPOVER, stepOver);
	toolbar->EnableTool(ID_CONNECTIONPAGE_STEPOUT, stepOut);
	toolbar->EnableTool(ID_CONNECTIONPAGE_RUN_TO_CURSOR, run);
}
// }}}

// vim:set fdm=marker ts=8 sw=8 noet cin:
<|endoftext|>


<commit_before>class Game
{
	unsigned int player_limit;
	std::list<char> bunch;
	std::map<std::string, Player> players;
	sf::Int16 peel_number {0};
	bool playing {false};
	bool ready_to_peel {false}; // game is ready for next peel
	bool waiting {false}; // waiting for clients to acknowledge critical server packets before next peel
	bool ready_to_finish {false}; // true if game just finished
	bool finished {false};

	void try_to_start();
public:
	std::string winner;

	Game(unsigned int _bunch_num, unsigned int _bunch_den, unsigned int _player_limit);

	inline bool has_player(const std::string& id) const
	{
		return players.count(id) != 0;
	}

	inline std::map<std::string, Player>& get_players()
	{
		return players;
	}

	inline const std::string& get_player_name(const std::string& id) const
	{
		return players.at(id).get_name();
	}

	inline sf::Int16 get_remaining() const
	{
		return bunch.size();
	}

	inline bool is_full() const
	{
		return players.size() == player_limit;
	}

	inline bool in_progress() const
	{
		return playing;
	}

	inline bool can_peel() const
	{
		return ready_to_peel && !waiting;
	}

	inline bool is_finished() const
	{
		return finished;
	}

	inline bool is_ready_to_finish() const
	{
		return ready_to_finish;
	}

	inline void finish()
	{
		ready_to_finish = false;
	}

	inline bool can_restart() const
	{
		return finished && !waiting;
	}

	inline void wait()
	{
		waiting = true;
	}

	void check_waiting();

	inline bool check_dump(const std::string& id, const sf::Int16& dump_n) const
	{
		return (dump_n == players.at(id).get_dump() - 1) || (dump_n == players.at(id).get_dump());
	}

	inline bool check_peel(const sf::Int16& number)
	{
		if (number == peel_number)
			ready_to_peel = true;
		return ready_to_peel;
	}

	inline const sf::Int16& get_peel() const
	{
		return peel_number;
	}

	std::string dump(const std::string& id, const sf::Int16& dump_n, char chr);

	Player& add_player(const std::string& id, const sf::IpAddress& ip, unsigned short port, const std::string& name);
	void remove_player(const std::string& id);
	void set_ready(const std::string& id, bool ready);
	bool peel();
	void start();
	void got_ack(const std::string& id, const sf::Int16& ack_num) const;
};
<commit_msg>Don't let game peel after someone wins<commit_after>class Game
{
	unsigned int player_limit;
	std::list<char> bunch;
	std::map<std::string, Player> players;
	sf::Int16 peel_number {0};
	bool playing {false};
	bool ready_to_peel {false}; // game is ready for next peel
	bool waiting {false}; // waiting for clients to acknowledge critical server packets before next peel
	bool ready_to_finish {false}; // true if game just finished
	bool finished {false};

	void try_to_start();
public:
	std::string winner;

	Game(unsigned int _bunch_num, unsigned int _bunch_den, unsigned int _player_limit);

	inline bool has_player(const std::string& id) const
	{
		return players.count(id) != 0;
	}

	inline std::map<std::string, Player>& get_players()
	{
		return players;
	}

	inline const std::string& get_player_name(const std::string& id) const
	{
		return players.at(id).get_name();
	}

	inline sf::Int16 get_remaining() const
	{
		return bunch.size();
	}

	inline bool is_full() const
	{
		return players.size() == player_limit;
	}

	inline bool in_progress() const
	{
		return playing;
	}

	inline bool can_peel() const
	{
		return ready_to_peel && !waiting && !finished;
	}

	inline bool is_finished() const
	{
		return finished;
	}

	inline bool is_ready_to_finish() const
	{
		return ready_to_finish;
	}

	inline void finish()
	{
		ready_to_finish = false;
	}

	inline bool can_restart() const
	{
		return finished && !waiting;
	}

	inline void wait()
	{
		waiting = true;
	}

	void check_waiting();

	inline bool check_dump(const std::string& id, const sf::Int16& dump_n) const
	{
		return (dump_n == players.at(id).get_dump() - 1) || (dump_n == players.at(id).get_dump());
	}

	inline bool check_peel(const sf::Int16& number)
	{
		if (number == peel_number)
			ready_to_peel = true;
		return ready_to_peel;
	}

	inline const sf::Int16& get_peel() const
	{
		return peel_number;
	}

	std::string dump(const std::string& id, const sf::Int16& dump_n, char chr);

	Player& add_player(const std::string& id, const sf::IpAddress& ip, unsigned short port, const std::string& name);
	void remove_player(const std::string& id);
	void set_ready(const std::string& id, bool ready);
	bool peel();
	void start();
	void got_ack(const std::string& id, const sf::Int16& ack_num) const;
};
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: flddropdown.cxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: hr $ $Date: 2003-06-30 15:50: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): _______________________________________
 *
 *
 ************************************************************************/

#include <algorithm>
#include <svtools/poolitem.hxx>
#ifndef _UNOFLDMID_H
#include <unofldmid.h>
#endif
#ifndef _UNOPRNMS_HXX
#include <unoprnms.hxx>
#endif
#include <flddropdown.hxx>

static String aEmptyString;

SwDropDownFieldType::SwDropDownFieldType()
    : SwFieldType(RES_DROPDOWN)
{
}

SwDropDownFieldType::~SwDropDownFieldType()
{
}

SwFieldType * SwDropDownFieldType::Copy() const
{
    return new SwDropDownFieldType;
}

SwDropDownField::SwDropDownField(SwFieldType * pTyp)
    : SwField(pTyp, 0, LANGUAGE_SYSTEM)
{
}

SwDropDownField::SwDropDownField(const SwDropDownField & rSrc)
    : SwField(rSrc.GetTyp(), rSrc.GetFormat(), rSrc.GetLanguage()),
      aValues(rSrc.aValues), aSelectedItem(rSrc.aSelectedItem),
      aName(rSrc.aName)
{
}

SwDropDownField::~SwDropDownField()
{
}

String SwDropDownField::Expand() const
{
    String sSelect = GetSelectedItem();
    if(!sSelect.Len())
    {
        vector<String>::const_iterator aIt = aValues.begin();
        if ( aIt != aValues.end())
            sSelect = *aIt;
    }
    //if still no list value is available a default text of 10 spaces is to be set
    if(!sSelect.Len())
        sSelect.AppendAscii ( RTL_CONSTASCII_STRINGPARAM ("          "));
    return sSelect;
}

SwField * SwDropDownField::Copy() const
{
    return new SwDropDownField(*this);
}

const String & SwDropDownField::GetPar1() const
{
    return GetSelectedItem();
}

String SwDropDownField::GetPar2() const
{
    return GetName();
}

void SwDropDownField::SetPar1(const String & rStr)
{
    SetSelectedItem(rStr);
}

void SwDropDownField::SetPar2(const String & rName)
{
    SetName(rName);
}

BOOL SwDropDownField::AddItem(const String & rItem)
{
    BOOL bResult = FALSE;

    if (find(aValues.begin(), aValues.end(), rItem) == aValues.end())
    {
        String aTmp = GetSelectedItem();
        aValues.push_back(rItem);
        SetSelectedItem(aTmp);

        bResult = TRUE;
    }

    return bResult;
}

BOOL SwDropDownField::RemoveItem(const String & rItem)
{
    BOOL bResult = FALSE;

    vector<String>::iterator aIt =
        find(aValues.begin(), aValues.end(), rItem);

    if ( aIt != aValues.end())
    {
        aValues.erase(aIt);

        if (rItem.Equals(aSelectedItem))
            aSelectedItem = aEmptyString;

        bResult = TRUE;
    }

    return bResult;
}

void SwDropDownField::SetItems(const vector<String> & rItems)
{
    aValues = rItems;
    aSelectedItem = aEmptyString;
}

void SwDropDownField::SetItems(const Sequence<OUString> & rItems)
{
    aValues.clear();

    sal_Int32 aCount = rItems.getLength();
    for (int i = 0; i < aCount; i++)
        aValues.push_back(rItems[i]);

    aSelectedItem = aEmptyString;
}

Sequence<OUString> SwDropDownField::GetItemSequence() const
{
    Sequence<OUString> aSeq( aValues.size() );
    OUString* pSeq = aSeq.getArray();
    int i = 0;
    vector<String>::const_iterator aIt;

    for (aIt = aValues.begin(); aIt != aValues.end(); aIt++)
    {
        pSeq[i] = rtl::OUString(*aIt);

        i++;
    }

    return aSeq;
}

vector<String> SwDropDownField::GetItems() const
{
    return aValues;
}

const String & SwDropDownField::GetSelectedItem() const
{
    return aSelectedItem;
}

const String & SwDropDownField::GetName() const
{
    return aName;
}

BOOL SwDropDownField::SetSelectedItem(const String & rItem)
{
    vector<String>::const_iterator aIt =
        find(aValues.begin(), aValues.end(), rItem);

    if (aIt != aValues.end())
        aSelectedItem = *aIt;
    else
        aSelectedItem = String();

    return (aIt != aValues.end());
}

void SwDropDownField::SetName(const String & rName)
{
    aName = rName;
}

BOOL SwDropDownField::QueryValue(Any &rVal, BYTE nMId)
    const
{
    nMId &= ~CONVERT_TWIPS;
    switch( nMId )
    {
    case FIELD_PROP_PAR1:
        rVal <<= rtl::OUString(GetSelectedItem());
        break;
    case FIELD_PROP_PAR2:
        rVal <<= rtl::OUString(GetName());
        break;
    case FIELD_PROP_STRINGS:
        rVal <<= GetItemSequence();

        break;

    default:
        DBG_ERROR("illegal property");
    }
    return sal_True;
}

BOOL SwDropDownField::PutValue(const Any &rVal,
                               BYTE nMId)
{
    nMId &= ~CONVERT_TWIPS;
    switch( nMId )
    {
    case FIELD_PROP_PAR1:
        {
            String aTmpStr;
            ::GetString( rVal, aTmpStr );

            SetSelectedItem(aTmpStr);
        }
        break;

    case FIELD_PROP_PAR2:
        {
            String aTmpStr;
            ::GetString( rVal, aTmpStr );

            SetName(aTmpStr);
        }
        break;

    case FIELD_PROP_STRINGS:
        {
            Sequence<OUString> aSeq;
            rVal >>= aSeq;
            SetItems(aSeq);
        }
        break;

    default:
        DBG_ERROR("illegal property");
    }
    return sal_True;
}
<commit_msg>INTEGRATION: CWS tune05 (1.2.488); FILE MERGED 2004/07/22 10:49:39 cmc 1.2.488.1: #i30554# unused SwDropDownField methods<commit_after>/*************************************************************************
 *
 *  $RCSfile: flddropdown.cxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: obo $ $Date: 2004-08-12 12:25:13 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#include <algorithm>
#include <svtools/poolitem.hxx>
#ifndef _UNOFLDMID_H
#include <unofldmid.h>
#endif
#ifndef _UNOPRNMS_HXX
#include <unoprnms.hxx>
#endif
#include <flddropdown.hxx>

static String aEmptyString;

SwDropDownFieldType::SwDropDownFieldType()
    : SwFieldType(RES_DROPDOWN)
{
}

SwDropDownFieldType::~SwDropDownFieldType()
{
}

SwFieldType * SwDropDownFieldType::Copy() const
{
    return new SwDropDownFieldType;
}

SwDropDownField::SwDropDownField(SwFieldType * pTyp)
    : SwField(pTyp, 0, LANGUAGE_SYSTEM)
{
}

SwDropDownField::SwDropDownField(const SwDropDownField & rSrc)
    : SwField(rSrc.GetTyp(), rSrc.GetFormat(), rSrc.GetLanguage()),
      aValues(rSrc.aValues), aSelectedItem(rSrc.aSelectedItem),
      aName(rSrc.aName)
{
}

SwDropDownField::~SwDropDownField()
{
}

String SwDropDownField::Expand() const
{
    String sSelect = GetSelectedItem();
    if(!sSelect.Len())
    {
        vector<String>::const_iterator aIt = aValues.begin();
        if ( aIt != aValues.end())
            sSelect = *aIt;
    }
    //if still no list value is available a default text of 10 spaces is to be set
    if(!sSelect.Len())
        sSelect.AppendAscii ( RTL_CONSTASCII_STRINGPARAM ("          "));
    return sSelect;
}

SwField * SwDropDownField::Copy() const
{
    return new SwDropDownField(*this);
}

const String & SwDropDownField::GetPar1() const
{
    return GetSelectedItem();
}

String SwDropDownField::GetPar2() const
{
    return GetName();
}

void SwDropDownField::SetPar1(const String & rStr)
{
    SetSelectedItem(rStr);
}

void SwDropDownField::SetPar2(const String & rName)
{
    SetName(rName);
}

void SwDropDownField::SetItems(const vector<String> & rItems)
{
    aValues = rItems;
    aSelectedItem = aEmptyString;
}

void SwDropDownField::SetItems(const Sequence<OUString> & rItems)
{
    aValues.clear();

    sal_Int32 aCount = rItems.getLength();
    for (int i = 0; i < aCount; i++)
        aValues.push_back(rItems[i]);

    aSelectedItem = aEmptyString;
}

Sequence<OUString> SwDropDownField::GetItemSequence() const
{
    Sequence<OUString> aSeq( aValues.size() );
    OUString* pSeq = aSeq.getArray();
    int i = 0;
    vector<String>::const_iterator aIt;

    for (aIt = aValues.begin(); aIt != aValues.end(); aIt++)
    {
        pSeq[i] = rtl::OUString(*aIt);

        i++;
    }

    return aSeq;
}

const String & SwDropDownField::GetSelectedItem() const
{
    return aSelectedItem;
}

const String & SwDropDownField::GetName() const
{
    return aName;
}

BOOL SwDropDownField::SetSelectedItem(const String & rItem)
{
    vector<String>::const_iterator aIt =
        find(aValues.begin(), aValues.end(), rItem);

    if (aIt != aValues.end())
        aSelectedItem = *aIt;
    else
        aSelectedItem = String();

    return (aIt != aValues.end());
}

void SwDropDownField::SetName(const String & rName)
{
    aName = rName;
}

BOOL SwDropDownField::QueryValue(Any &rVal, BYTE nMId)
    const
{
    nMId &= ~CONVERT_TWIPS;
    switch( nMId )
    {
    case FIELD_PROP_PAR1:
        rVal <<= rtl::OUString(GetSelectedItem());
        break;
    case FIELD_PROP_PAR2:
        rVal <<= rtl::OUString(GetName());
        break;
    case FIELD_PROP_STRINGS:
        rVal <<= GetItemSequence();

        break;

    default:
        DBG_ERROR("illegal property");
    }
    return sal_True;
}

BOOL SwDropDownField::PutValue(const Any &rVal,
                               BYTE nMId)
{
    nMId &= ~CONVERT_TWIPS;
    switch( nMId )
    {
    case FIELD_PROP_PAR1:
        {
            String aTmpStr;
            ::GetString( rVal, aTmpStr );

            SetSelectedItem(aTmpStr);
        }
        break;

    case FIELD_PROP_PAR2:
        {
            String aTmpStr;
            ::GetString( rVal, aTmpStr );

            SetName(aTmpStr);
        }
        break;

    case FIELD_PROP_STRINGS:
        {
            Sequence<OUString> aSeq;
            rVal >>= aSeq;
            SetItems(aSeq);
        }
        break;

    default:
        DBG_ERROR("illegal property");
    }
    return sal_True;
}
<|endoftext|>


<commit_before>#include <iostream>
#include <algorithm>
#include <iterator>
#include <stdexcept>

template<typename T,typename Alloc>
class vector
{
    public:
    typedef T value_type;
    typedef Alloc alloc_type;
    typedef value_type & reference;
    typedef value_type * pointer;
    typedef const value_type & const_reference;
    typedef const value_type * const_pointer;
    typedef value_type * iterator;
    typedef const value_type * const_iterator;
    typedef std::reverse_iterator<iterator> reverse_iterator;
    typedef std::reverse_iterator<const_iterator> const_reverse_iterator;
    typedef std::size_t size_type;
    typedef ptrdiff_t difference_type;

    iterator begin()
    {

    }
    const_iterator begin()const
    {

    }
    iterator end()
    {

    }
    const_iterator end()const
    {

    }
    reverse_iterator rbegin()
    {

    }
    const_reverse_iterator rbegin()const
    {

    }
    reverse_iterator rend()
    {

    }
    const_reverse_iterator rend()const
    {

    }

    const_iterator cbegin()const
    {

    }
    const_iterator cend()const
    {

    }
    const_reverse_iterator crbegin()const
    {

    }
    const_reverse_iterator crend()const
    {

    }
    reference front()
    {

    }
    const_reference front()const
    {

    }

    reference back()
    {

    }

    const_reference back()const
    {

    }

    pointer data()
    {

    }

    const_pointer data()const
    {

    }

    reference operator[](size_type ) const
    {

    }

    const_reference operator[](size_type ) const
    {

    }

    reference at(size_type )
    {

    }

    const_reference at(size_type )const
    {

    }
};

<commit_msg>modify vec<commit_after>#include <iostream>
#include <algorithm>
#include <iterator>
#include <stdexcept>

template<typename T,typename Alloc>
class vector
{
    public:
    typedef T value_type;
    typedef Alloc alloc_type;
    typedef value_type & reference;
    typedef value_type * pointer;
    typedef const value_type & const_reference;
    typedef const value_type * const_pointer;
    typedef value_type * iterator;
    typedef const value_type * const_iterator;
    typedef std::reverse_iterator<iterator> reverse_iterator;
    typedef std::reverse_iterator<const_iterator> const_reverse_iterator;
    typedef std::size_t size_type;
    typedef ptrdiff_t difference_type;

    vector()
    {

    }
    explicit vector(const alloc_type &)
    {

    }
    explicit vector(size_type,const alloc_type & = alloc_type() )
    {

    }
    vector(size_type,const value_type v,const alloc_type &=alloc_type() )
    {

    }
    template <typename InputIter>
    vector(InputIter begin,InputIter end,const alloc_type & = alloc_type() )
    {

    }
    template<typename U>
    vector(std::initialize_list<U>,const alloc_type & = alloc_type() )
    {

    }
    vector(const vector &)
    {

    }
    vector(const vector &,const alloc_type &)
    {

    }
    vector(vector &&)
    {

    }
    vector(vector &&,const alloc_type &)
    {

    }
    ~vector()
    {

    }

    iterator begin()
    {

    }
    const_iterator begin()const
    {

    }
    iterator end()
    {

    }
    const_iterator end()const
    {

    }
    reverse_iterator rbegin()
    {

    }
    const_reverse_iterator rbegin()const
    {

    }
    reverse_iterator rend()
    {

    }
    const_reverse_iterator rend()const
    {

    }

    const_iterator cbegin()const
    {

    }
    const_iterator cend()const
    {

    }
    const_reverse_iterator crbegin()const
    {

    }
    const_reverse_iterator crend()const
    {

    }
    reference front()
    {

    }
    const_reference front()const
    {

    }

    reference back()
    {

    }

    const_reference back()const
    {

    }

    pointer data()
    {

    }

    const_pointer data()const
    {

    }

    reference operator[](size_type ) const
    {

    }

    const_reference operator[](size_type ) const
    {

    }

    reference at(size_type )
    {

    }

    const_reference at(size_type )const
    {

    }
    void swap(vector &)noexcept
    {
    }

};

<|endoftext|>


<commit_before>//
//  EventBus.hpp
//  CatchLib
//
//  Created by Jesper Persson and Sebastian Odbjer on 2/10-12.
//  Copyright (c) 2012 Catch22. All rights reserved.
//
#include "EEvent.hpp"
#include "IEventListener.hpp"

struct EventListenerArray
{
	IEventListener** m_eventListeners;
	int m_size;
	int m_incrementBy;
	int m_index;
	EventListenerArray()
	{
		m_incrementBy = 5;
		m_index = 0;
		m_size = 0;
		m_eventListeners = 0;
	}
};

class EventBus
{
public:
	static EventBus* getSharedInstance();
	void publishEvent(EEvent event, void* source);
	void addEventListener(IEventListener* listener);
	void removeEventListener(IEventListener* listener);
private:
	EventListenerArray* m_listeners;
	~EventBus();
	EventBus();
};
<commit_msg>Added documentation for our structure<commit_after>//
//  EventBus.hpp
//  CatchLib
//
//  Created by Jesper Persson and Sebastian Odbjer on 2/10-12.
//  Copyright (c) 2012 Catch22. All rights reserved.
//
#include "EEvent.hpp"
#include "IEventListener.hpp"

/*
 * Structure for organizing our array of eventListeners.
 * m_eventListeners --  our array of eventListeners.
 * m_size -- 			the size of our array.
 * m_incrementBy -- 	how much the size of the array should be incremented
 * 						by whenever m_index == m_size.
 * m_index -- 			the index of the last element of the array, it is set to -1
 * 			  			as default to prevent events to be performed when the array
 * 			  			is empty.
 */
struct EventListenerArray
{
	IEventListener** m_eventListeners;
	int m_size;
	int m_incrementBy;
	int m_index;
	EventListenerArray()
	{
		m_incrementBy = 5;
		m_index = -1;
		m_size = 0;
		m_eventListeners = 0;
	}
};

class EventBus
{
public:
	static EventBus* getSharedInstance();
	void publishEvent(EEvent event, void* source);
	void addEventListener(IEventListener* listener);
	void removeEventListener(IEventListener* listener);
private:
	EventListenerArray* m_listeners;
	~EventBus();
	EventBus();
};
<|endoftext|>


<commit_before>/*************************************************************************
> File Name: Interface.cpp
> Project Name: Hearthstone++
> Author: Young-Joong Kim
> Purpose: Interface for Hearthstone Game Agent
> Created Time: 2017/10/24
> Copyright (c) 2017, Young-Joong Kim
*************************************************************************/
#include <Interface/Interface.h>

namespace Hearthstonepp
{
	GameInterface::GameInterface(GameAgent& agent)
		: m_agent(agent)
		, m_bufferCapacity(agent.GetBufferCapacity())
	{
		m_buffer = new BYTE[m_bufferCapacity];
	}

	GameResult GameInterface::StartGame()
	{
		GameResult result;
		std::thread *at = m_agent.StartAgent(result);

		while (true)
		{
			int result = HandleMessage();
			if (result) break;
		}

		at->join(); // join agent thread
		delete at;

		return result;
	}

	int GameInterface::HandleMessage()
	{
		m_agent.ReadBuffer(m_buffer, m_bufferCapacity);
		if (m_buffer[0] == static_cast<BYTE>(Step::FINAL_GAMEOVER))
		{
			return 1;
		}
		else if (m_handler.find(m_buffer[0]) != m_handler.end())
		{
			m_handler[m_buffer[0]](*this);
		}

		return 0;
	}

	void GameInterface::LogWriter(std::string& name, std::string message)
	{
		std::cout << "[*] " << name << " : " << message << std::endl;
	}

	void GameInterface::BeginFirst()
	{
		BeginFirstStructure *data = (BeginFirstStructure*)m_buffer;

		m_users[0] = data->m_userFirst;
		m_users[1] = data->m_userLast;

		LogWriter(m_users[0], "Begin First");
		LogWriter(m_users[1], "Begin Last");
	}

	void GameInterface::BeginShuffle()
	{
		BeginShuffleStructure *data = (BeginShuffleStructure*)m_buffer;
		LogWriter(m_users[data->m_userID], "Begin Shuffle");
	}

	void GameInterface::BeginDraw()
	{
		DrawStructure *data = (DrawStructure*)m_buffer;
		LogWriter(m_users[data->m_userID], "Begin Draw");

		for (int i = 0; i < 3; ++i)
		{
			std::cout << "[" << data->m_cards[i]->GetCardName() << "] ";
		}
		std::cout << std::endl;
	}

	void GameInterface::BeginMulligan()
	{
		BeginMulliganStructure *data = (BeginMulliganStructure*)m_buffer;
		LogWriter(m_users[data->m_userID], "Begin Mulligan");

		int numMulligan;
		while (true)
		{
			std::cout << "[*] How many cards to mulligan ? (0 ~ 3) ";
			std::cin >> numMulligan;

			if (numMulligan >= 0 && numMulligan <= 3)
			{
				break;
			}
		}

		BYTE mulligan[3] = { 0, };
		for (int i = 0; i < numMulligan; ++i)
		{
			while (true)
			{
				BYTE index = 0;
				std::cout << "[*] Input card index " << i+1 << " : ";
				std::cin >> index;

				if (index >= 0 && index <= 3)
				{
					mulligan[i] = index;
					break;
				}
			}
		}

		m_agent.WriteBuffer(mulligan, numMulligan); // send index to agent
		m_agent.ReadBuffer(m_buffer, sizeof(DrawStructure)); // get new card data

		LogWriter(m_users[data->m_userID], "Mulligan Result");

		DrawStructure *draw = (DrawStructure*)m_buffer;
		for (int i = 0; i < 3; ++i)
		{
			std::cout << "[" << draw->m_cards[i]->GetCardName() << "] ";
		}
		std::cout << std::endl;
	}
}<commit_msg>Update Interface - Fix Mulligan System reference invalid addr<commit_after>/*************************************************************************
> File Name: Interface.cpp
> Project Name: Hearthstone++
> Author: Young-Joong Kim
> Purpose: Interface for Hearthstone Game Agent
> Created Time: 2017/10/24
> Copyright (c) 2017, Young-Joong Kim
*************************************************************************/
#include <Interface/Interface.h>

namespace Hearthstonepp
{
	GameInterface::GameInterface(GameAgent& agent)
		: m_agent(agent)
		, m_bufferCapacity(agent.GetBufferCapacity())
	{
		m_buffer = new BYTE[m_bufferCapacity];
	}

	GameResult GameInterface::StartGame()
	{
		GameResult result;
		std::thread *at = m_agent.StartAgent(result);

		while (true)
		{
			int result = HandleMessage();
			if (result) break;
		}

		at->join(); // join agent thread
		delete at;

		return result;
	}

	int GameInterface::HandleMessage()
	{
		m_agent.ReadBuffer(m_buffer, m_bufferCapacity);
		if (m_buffer[0] == static_cast<BYTE>(Step::FINAL_GAMEOVER))
		{
			return 1;
		}
		else if (m_handler.find(m_buffer[0]) != m_handler.end())
		{
			m_handler[m_buffer[0]](*this);
		}

		return 0;
	}

	void GameInterface::LogWriter(std::string& name, std::string message)
	{
		std::cout << "[*] " << name << " : " << message << std::endl;
	}

	void GameInterface::BeginFirst()
	{
		BeginFirstStructure *data = (BeginFirstStructure*)m_buffer;

		m_users[0] = data->m_userFirst;
		m_users[1] = data->m_userLast;

		LogWriter(m_users[0], "Begin First");
		LogWriter(m_users[1], "Begin Last");
	}

	void GameInterface::BeginShuffle()
	{
		BeginShuffleStructure *data = (BeginShuffleStructure*)m_buffer;
		LogWriter(m_users[data->m_userID], "Begin Shuffle");
	}

	void GameInterface::BeginDraw()
	{
		DrawStructure *data = (DrawStructure*)m_buffer;
		LogWriter(m_users[data->m_userID], "Begin Draw");

		for (int i = 0; i < 3; ++i)
		{
			std::cout << "[" << data->m_cards[i]->GetCardName() << "] ";
		}
		std::cout << std::endl;
	}

	void GameInterface::BeginMulligan()
	{
		BeginMulliganStructure *data = (BeginMulliganStructure*)m_buffer;
		LogWriter(m_users[data->m_userID], "Begin Mulligan");

		int numMulligan;
		while (true)
		{
			std::cout << "[*] How many cards to mulligan ? (0 ~ 3) ";
			std::cin >> numMulligan;

			if (numMulligan >= 0 && numMulligan <= 3)
			{
				break;
			}
		}

		BYTE mulligan[3] = { 0, };
		for (int i = 0; i < numMulligan; ++i)
		{
			while (true)
			{
				int index = 0;
				std::cout << "[*] Input card index " << i+1 << " (0 ~ 2) : ";
				std::cin >> index;

				if (index >= 0 && index <= 2)
				{
					mulligan[i] = index;
					break;
				}
			}
		}

		m_agent.WriteBuffer(mulligan, numMulligan); // send index to agent
		m_agent.ReadBuffer(m_buffer, sizeof(DrawStructure)); // get new card data

		LogWriter(m_users[data->m_userID], "Mulligan Result");

		DrawStructure *draw = (DrawStructure*)m_buffer;
		for (int i = 0; i < 3; ++i)
		{
			std::cout << "[" << draw->m_cards[i]->GetCardName() << "] ";
		}
		std::cout << std::endl;
	}
}<|endoftext|>


<commit_before>// This code is based on Sabberstone project.
// Copyright (c) 2017-2018 SabberStone Team, darkfriend77 & rnilva
// Hearthstone++ is hearthstone simulator using C++ with reinforcement learning.
// Copyright (c) 2018 Chris Ohk, Youngjoong Kim, SeungHyun Jeon

#include <hspp/Actions/Choose.hpp>
#include <hspp/Actions/Generic.hpp>

#include <iostream>

namespace Hearthstonepp::Generic
{
void ChoiceMulligan(Player& player, std::vector<std::size_t> choices)
{
    // Block it if player tries to mulligan in a non-mulligan choice
    if (player.choice.value().choiceType != +ChoiceType::MULLIGAN)
    {
        return;
    }

    // Block it if player tries to mulligan a card that doesn't exist
    Choice& choice = player.choice.value();
    for (auto& choosedID : choices)
    {
        if (std::find(choice.choices.begin(), choice.choices.end(),
                      choosedID) == choice.choices.end())
        {
            return;
        }
    }

    // Process mulligan by choice action
    switch (player.choice.value().choiceAction)
    {
        case ChoiceAction::HAND:
        {
            // Process mulligan state
            player.mulliganState = Mulligan::DEALING;

            auto& hand = player.GetHand();
            auto& deck = player.GetDeck();

            // Collect cards to redraw
            std::vector<Entity*> mulliganList;
            for (const auto& entity : hand.GetAllCards())
            {
                bool isExist = std::find(choices.begin(), choices.end(),
                                         entity->id) == choices.end();
                if (isExist && entity->card.id != "GAME_005")
                {
                    mulliganList.push_back(entity);
                }
            }

            // Process redraw
            for (const auto& entity : mulliganList)
            {
                Entity& newCard = deck.RemoveCard(*deck.GetTopCard());
                Generic::AddCardToHand(player, &newCard);
                hand.SwapCard(*entity, newCard);

                Generic::RemoveCardFromHand(player, entity);
                deck.AddCard(*entity);
                deck.Shuffle();
            }

            // It's done! - Reset choice
            player.choice = std::nullopt;

            break;
        }
        default:
            throw std::invalid_argument(
                "ChoiceMulligan() - Invalid choice action!");
    }
}

void CreateChoice(Player& player, ChoiceType type, ChoiceAction action,
                  std::vector<std::size_t> choices)
{
    // Block it if choice is exist
    if (player.choice != std::nullopt)
    {
        return;
    }

    // Create a choice for player
    Choice choice;
    choice.choiceType = type;
    choice.choiceAction = action;
    choice.choices = choices;
    player.choice = choice;
}
}  // namespace Hearthstonepp::Generic<commit_msg>fix: Correct type matching (non-reference vs reference)<commit_after>// This code is based on Sabberstone project.
// Copyright (c) 2017-2018 SabberStone Team, darkfriend77 & rnilva
// Hearthstone++ is hearthstone simulator using C++ with reinforcement learning.
// Copyright (c) 2018 Chris Ohk, Youngjoong Kim, SeungHyun Jeon

#include <hspp/Actions/Choose.hpp>
#include <hspp/Actions/Generic.hpp>

namespace Hearthstonepp::Generic
{
void ChoiceMulligan(Player& player, std::vector<std::size_t> choices)
{
    // Block it if player tries to mulligan in a non-mulligan choice
    if (player.choice.value().choiceType != +ChoiceType::MULLIGAN)
    {
        return;
    }

    // Block it if player tries to mulligan a card that doesn't exist
    Choice& choice = player.choice.value();
    for (const auto choosedID : choices)
    {
        if (std::find(choice.choices.begin(), choice.choices.end(),
                      choosedID) == choice.choices.end())
        {
            return;
        }
    }

    // Process mulligan by choice action
    switch (player.choice.value().choiceAction)
    {
        case ChoiceAction::HAND:
        {
            // Process mulligan state
            player.mulliganState = Mulligan::DEALING;

            auto& hand = player.GetHand();
            auto& deck = player.GetDeck();

            // Collect cards to redraw
            std::vector<Entity*> mulliganList;
            for (const auto entity : hand.GetAllCards())
            {
                bool isExist = std::find(choices.begin(), choices.end(),
                                         entity->id) == choices.end();
                if (isExist && entity->card.id != "GAME_005")
                {
                    mulliganList.push_back(entity);
                }
            }

            // Process redraw
            for (const auto& entity : mulliganList)
            {
                Entity& newCard = deck.RemoveCard(*deck.GetTopCard());
                Generic::AddCardToHand(player, &newCard);
                hand.SwapCard(*entity, newCard);

                Generic::RemoveCardFromHand(player, entity);
                deck.AddCard(*entity);
                deck.Shuffle();
            }

            // It's done! - Reset choice
            player.choice = std::nullopt;

            break;
        }
        default:
            throw std::invalid_argument(
                "ChoiceMulligan() - Invalid choice action!");
    }
}

void CreateChoice(Player& player, ChoiceType type, ChoiceAction action,
                  std::vector<std::size_t> choices)
{
    // Block it if choice is exist
    if (player.choice != std::nullopt)
    {
        return;
    }

    // Create a choice for player
    Choice choice;
    choice.choiceType = type;
    choice.choiceAction = action;
    choice.choices = choices;
    player.choice = choice;
}
}  // namespace Hearthstonepp::Generic<|endoftext|>


<commit_before>/*
 *  Copyright (c) 2015, Nagoya University
 *  All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *
 *  * Redistributions of source code must retain the above copyright notice, this
 *    list of conditions and the following disclaimer.
 *
 *  * Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 *
 *  * Neither the name of Autoware 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 <ros/ros.h>
#include <std_msgs/String.h>
#include <geometry_msgs/Twist.h>
#include <geometry_msgs/TwistStamped.h>
#include <geometry_msgs/PoseWithCovarianceStamped.h>
#include <nav_msgs/Odometry.h>
#include <tf/transform_broadcaster.h>
#include <tf/transform_listener.h>
#include <tf/tf.h>
#include <iostream>

#include "waypoint_follower/libwaypoint_follower.h"
static geometry_msgs::Twist _current_velocity;

static const std::string SIMULATION_FRAME = "sim_base_link";
static const std::string MAP_FRAME = "map";

static geometry_msgs::Pose _initial_pose;
static std::string _use_pose;
static bool _initial_set = false;
static bool _pose_set = false;
static bool _waypoint_set = false;
static int _closest_waypoint = -1;
//Path _path_og;
WayPoints _current_waypoints;

static void NDTCallback(const geometry_msgs::PoseStamped::ConstPtr& input)
{
  if (_use_pose != "NDT")
    return;

  if(_initial_set)
    return;

  _initial_pose = input->pose;
  _initial_set = true;
  _pose_set = false;

}

static void GNSSCallback(const geometry_msgs::PoseStamped::ConstPtr& input)
{
  if (_use_pose != "GNSS")
    return;

  if(_initial_set)
    return;

  _initial_pose = input->pose;
  _initial_set = true;
  _pose_set = false;

}

static void CmdCallBack(const geometry_msgs::TwistStampedConstPtr &msg)
{
  _current_velocity = msg->twist;
}

static void initialposeCallback(const geometry_msgs::PoseWithCovarianceStampedConstPtr &input)
{
  if (_use_pose != "Initial Pos")
    return;

    static tf::TransformListener listener;
    tf::StampedTransform transform;
    bool tf_flag = false;
    while (!tf_flag)
    {
      try
      {
        listener.lookupTransform("map", "world", ros::Time(0), transform);
        tf_flag = true;
      }
      catch (tf::TransformException ex)
      {
        ROS_ERROR("%s", ex.what());
        ros::Duration(1.0).sleep();
      }

    }

    _initial_pose.position.x = input->pose.pose.position.x + transform.getOrigin().x();
    _initial_pose.position.y = input->pose.pose.position.y + transform.getOrigin().y();
    _initial_pose.position.z = input->pose.pose.position.z + transform.getOrigin().z();
    _initial_pose.orientation = input->pose.pose.orientation;

    _initial_set = true;
    _pose_set = false;

}

static void waypointCallback(const waypoint_follower::laneConstPtr &msg)
{
 // _path_og.setPath(msg);
  _current_waypoints.setPath(*msg);
  _waypoint_set = true;
  ROS_INFO_STREAM("waypoint subscribed");
}

int main(int argc, char **argv)
{
  ros::init(argc, argv, "odom_gen");

  ros::NodeHandle nh;
  ros::NodeHandle private_nh("~");
//publish topic
  ros::Publisher odometry_publisher = nh.advertise<nav_msgs::Odometry>("odom_pose", 10);

//subscribe topic
  ros::Subscriber cmd_subscriber = nh.subscribe("twist_cmd", 10, CmdCallBack);
  ros::Subscriber ndt_subscriber = nh.subscribe("control_pose", 10, NDTCallback);
  ros::Subscriber initialpose_subscriber = nh.subscribe("initialpose", 10, initialposeCallback);
  ros::Subscriber gnss_subscriber = nh.subscribe("gnss_pose", 1000, GNSSCallback);

  ros::Subscriber waypoint_subcscriber = nh.subscribe("base_waypoints", 10, waypointCallback);

//transform
  tf::TransformBroadcaster odom_broadcaster;

  private_nh.getParam("use_pose", _use_pose);

  ros::Time current_time, last_time;
  current_time = ros::Time::now();
  last_time = ros::Time::now();

  geometry_msgs::Pose pose;
  double th = 0;

  ros::Rate loop_rate(50); // 50Hz
  while (ros::ok())
  {
    ros::spinOnce(); //check subscribe topic

    if (!_waypoint_set)
      continue;

    if (!_initial_set)
      continue;

    if (!_pose_set)
    {
      pose.position = _initial_pose.position;
      pose.orientation = _initial_pose.orientation;
      tf::Quaternion q(pose.orientation.x, pose.orientation.y, pose.orientation.z, pose.orientation.w);
      tf::Matrix3x3 m(q);
      double roll, pitch, yaw;
      m.getRPY(roll, pitch, yaw);
      th = yaw;
      std::cout << "pose set : (" << pose.position.x << " " << pose.position.y << " " << pose.position.z << " " << th
	    << ")" << std::endl << std::endl;
      _pose_set = true;
    }

  /*  tf::Transform inverse;
    tf::poseMsgToTF(pose, inverse);
    _path_og.setTransform(inverse.inverse());

    int closest_waypoint = _path_og.getClosestWaypoint();
    if (closest_waypoint == -1)
    {
      ROS_INFO_STREAM("waypoint is not closed");
      _initial_set = false;
      continue;
    }
    pose.position.z = _path_og.getWaypointPosition(closest_waypoint).z;
*/
    int closest_waypoint = getClosestWaypoint(_current_waypoints.getCurrentWaypoints(),pose);
    pose.position.z = _current_waypoints.getWaypointPosition(closest_waypoint).z;

    double vx = _current_velocity.linear.x;
    double vth = _current_velocity.angular.z;
    current_time = ros::Time::now();

    //compute odometry in a typical way given the velocities of the robot
    double dt = (current_time - last_time).toSec();
    double delta_x = (vx * cos(th)) * dt;
    double delta_y = (vx * sin(th)) * dt;
    double delta_th = vth * dt;

    pose.position.x += delta_x;
    pose.position.y += delta_y;
    th += delta_th;
    pose.orientation = tf::createQuaternionMsgFromYaw(th);

    // std::cout << "delta (x y th) : (" << delta_x << " " << delta_y << " " << delta_th << ")" << std::endl;
    //std::cout << "current_velocity(linear.x angular.z) : (" << _current_velocity.linear.x << " " << _current_velocity.angular.z << ")"<< std::endl;
    //    std::cout << "current_pose : (" << pose.position.x << " " << pose.position.y<< " " << pose.position.z << " " << th << ")" << std::endl << std::endl;

    //first, we'll publish the transform over tf
    geometry_msgs::TransformStamped odom_trans;
    odom_trans.header.stamp = current_time;
    odom_trans.header.frame_id = MAP_FRAME;
    odom_trans.child_frame_id = SIMULATION_FRAME;

    odom_trans.transform.translation.x = pose.position.x;
    odom_trans.transform.translation.y = pose.position.y;
    odom_trans.transform.translation.z = pose.position.z;
    odom_trans.transform.rotation = pose.orientation;

    //send the transform
    odom_broadcaster.sendTransform(odom_trans);

    //next, we'll publish the odometry message over ROS
    nav_msgs::Odometry odom;
    odom.header.stamp = current_time;
    odom.header.frame_id = MAP_FRAME;

    //set the position
    odom.pose.pose = pose;

    //set the velocity
    odom.child_frame_id = SIMULATION_FRAME;
    odom.twist.twist.linear.x = vx;
    odom.twist.twist.angular.z = vth;
    //publish the message
    odometry_publisher.publish(odom);

    last_time = current_time;

    loop_rate.sleep();
  }

  return 0;
}
<commit_msg>Add sleep<commit_after>/*
 *  Copyright (c) 2015, Nagoya University
 *  All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *
 *  * Redistributions of source code must retain the above copyright notice, this
 *    list of conditions and the following disclaimer.
 *
 *  * Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 *
 *  * Neither the name of Autoware 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 <ros/ros.h>
#include <std_msgs/String.h>
#include <geometry_msgs/Twist.h>
#include <geometry_msgs/TwistStamped.h>
#include <geometry_msgs/PoseWithCovarianceStamped.h>
#include <nav_msgs/Odometry.h>
#include <tf/transform_broadcaster.h>
#include <tf/transform_listener.h>
#include <tf/tf.h>
#include <iostream>

#include "waypoint_follower/libwaypoint_follower.h"
static geometry_msgs::Twist _current_velocity;

static const std::string SIMULATION_FRAME = "sim_base_link";
static const std::string MAP_FRAME = "map";

static geometry_msgs::Pose _initial_pose;
static std::string _use_pose;
static bool _initial_set = false;
static bool _pose_set = false;
static bool _waypoint_set = false;
static int _closest_waypoint = -1;
//Path _path_og;
WayPoints _current_waypoints;

static void NDTCallback(const geometry_msgs::PoseStamped::ConstPtr& input)
{
  if (_use_pose != "NDT")
    return;

  if(_initial_set)
    return;

  _initial_pose = input->pose;
  _initial_set = true;
  _pose_set = false;

}

static void GNSSCallback(const geometry_msgs::PoseStamped::ConstPtr& input)
{
  if (_use_pose != "GNSS")
    return;

  if(_initial_set)
    return;

  _initial_pose = input->pose;
  _initial_set = true;
  _pose_set = false;

}

static void CmdCallBack(const geometry_msgs::TwistStampedConstPtr &msg)
{
  _current_velocity = msg->twist;
}

static void initialposeCallback(const geometry_msgs::PoseWithCovarianceStampedConstPtr &input)
{
  if (_use_pose != "Initial Pos")
    return;

    static tf::TransformListener listener;
    tf::StampedTransform transform;
    bool tf_flag = false;
    while (!tf_flag)
    {
      try
      {
        listener.lookupTransform("map", "world", ros::Time(0), transform);
        tf_flag = true;
      }
      catch (tf::TransformException ex)
      {
        ROS_ERROR("%s", ex.what());
        ros::Duration(1.0).sleep();
      }

    }

    _initial_pose.position.x = input->pose.pose.position.x + transform.getOrigin().x();
    _initial_pose.position.y = input->pose.pose.position.y + transform.getOrigin().y();
    _initial_pose.position.z = input->pose.pose.position.z + transform.getOrigin().z();
    _initial_pose.orientation = input->pose.pose.orientation;

    _initial_set = true;
    _pose_set = false;

}

static void waypointCallback(const waypoint_follower::laneConstPtr &msg)
{
 // _path_og.setPath(msg);
  _current_waypoints.setPath(*msg);
  _waypoint_set = true;
  ROS_INFO_STREAM("waypoint subscribed");
}

int main(int argc, char **argv)
{
  ros::init(argc, argv, "odom_gen");

  ros::NodeHandle nh;
  ros::NodeHandle private_nh("~");
//publish topic
  ros::Publisher odometry_publisher = nh.advertise<nav_msgs::Odometry>("odom_pose", 10);

//subscribe topic
  ros::Subscriber cmd_subscriber = nh.subscribe("twist_cmd", 10, CmdCallBack);
  ros::Subscriber ndt_subscriber = nh.subscribe("control_pose", 10, NDTCallback);
  ros::Subscriber initialpose_subscriber = nh.subscribe("initialpose", 10, initialposeCallback);
  ros::Subscriber gnss_subscriber = nh.subscribe("gnss_pose", 1000, GNSSCallback);

  ros::Subscriber waypoint_subcscriber = nh.subscribe("base_waypoints", 10, waypointCallback);

//transform
  tf::TransformBroadcaster odom_broadcaster;

  private_nh.getParam("use_pose", _use_pose);

  ros::Time current_time, last_time;
  current_time = ros::Time::now();
  last_time = ros::Time::now();

  geometry_msgs::Pose pose;
  double th = 0;

  ros::Rate loop_rate(50); // 50Hz
  while (ros::ok())
  {
    ros::spinOnce(); //check subscribe topic

    if (!_waypoint_set) {
      loop_rate.sleep();
      continue;
    }

    if (!_initial_set) {
      loop_rate.sleep();
      continue;
    }

    if (!_pose_set)
    {
      pose.position = _initial_pose.position;
      pose.orientation = _initial_pose.orientation;
      tf::Quaternion q(pose.orientation.x, pose.orientation.y, pose.orientation.z, pose.orientation.w);
      tf::Matrix3x3 m(q);
      double roll, pitch, yaw;
      m.getRPY(roll, pitch, yaw);
      th = yaw;
      std::cout << "pose set : (" << pose.position.x << " " << pose.position.y << " " << pose.position.z << " " << th
	    << ")" << std::endl << std::endl;
      _pose_set = true;
    }

  /*  tf::Transform inverse;
    tf::poseMsgToTF(pose, inverse);
    _path_og.setTransform(inverse.inverse());

    int closest_waypoint = _path_og.getClosestWaypoint();
    if (closest_waypoint == -1)
    {
      ROS_INFO_STREAM("waypoint is not closed");
      _initial_set = false;
      continue;
    }
    pose.position.z = _path_og.getWaypointPosition(closest_waypoint).z;
*/
    int closest_waypoint = getClosestWaypoint(_current_waypoints.getCurrentWaypoints(),pose);
    pose.position.z = _current_waypoints.getWaypointPosition(closest_waypoint).z;

    double vx = _current_velocity.linear.x;
    double vth = _current_velocity.angular.z;
    current_time = ros::Time::now();

    //compute odometry in a typical way given the velocities of the robot
    double dt = (current_time - last_time).toSec();
    double delta_x = (vx * cos(th)) * dt;
    double delta_y = (vx * sin(th)) * dt;
    double delta_th = vth * dt;

    pose.position.x += delta_x;
    pose.position.y += delta_y;
    th += delta_th;
    pose.orientation = tf::createQuaternionMsgFromYaw(th);

    // std::cout << "delta (x y th) : (" << delta_x << " " << delta_y << " " << delta_th << ")" << std::endl;
    //std::cout << "current_velocity(linear.x angular.z) : (" << _current_velocity.linear.x << " " << _current_velocity.angular.z << ")"<< std::endl;
    //    std::cout << "current_pose : (" << pose.position.x << " " << pose.position.y<< " " << pose.position.z << " " << th << ")" << std::endl << std::endl;

    //first, we'll publish the transform over tf
    geometry_msgs::TransformStamped odom_trans;
    odom_trans.header.stamp = current_time;
    odom_trans.header.frame_id = MAP_FRAME;
    odom_trans.child_frame_id = SIMULATION_FRAME;

    odom_trans.transform.translation.x = pose.position.x;
    odom_trans.transform.translation.y = pose.position.y;
    odom_trans.transform.translation.z = pose.position.z;
    odom_trans.transform.rotation = pose.orientation;

    //send the transform
    odom_broadcaster.sendTransform(odom_trans);

    //next, we'll publish the odometry message over ROS
    nav_msgs::Odometry odom;
    odom.header.stamp = current_time;
    odom.header.frame_id = MAP_FRAME;

    //set the position
    odom.pose.pose = pose;

    //set the velocity
    odom.child_frame_id = SIMULATION_FRAME;
    odom.twist.twist.linear.x = vx;
    odom.twist.twist.angular.z = vth;
    //publish the message
    odometry_publisher.publish(odom);

    last_time = current_time;

    loop_rate.sleep();
  }

  return 0;
}
<|endoftext|>


<commit_before>#include "feStats.h"

const feStats feStats::ZERO = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };

bool feStats::operator==(const feStats &rhs) const {
	return (hp == rhs.hp
			&& str == rhs.str
			&& mag == rhs.mag
			&& skl == rhs.skl
			&& spd == rhs.spd
			&& lck == rhs.lck
			&& def == rhs.def
			&& res == rhs.res
			&& con == rhs.con
			&& mov == rhs.mov);
}

feStats feStats::operator%(const feStats &rhs) const {
	feStats ret = {
		hp % rhs.hp,
	  str % rhs.str,
	  mag % rhs.mag,
	  skl % rhs.skl,
	  spd % rhs.spd,
	  lck % rhs.lck,
	  def % rhs.def,
	  res % rhs.res,
	  con % rhs.con,
	  mov % rhs.mov
	};
	return ret;
}

feStats feStats::operator+(const feStats &rhs) const {
}

feStats feStats::operator-(const feStats &rhs) const {
}

feStats feStats::operator*(const feStats &rhs) const {
}

feStats feStats::operator/(const feStats &rhs) const {
}

feStats &feStats::operator=(const feStats &rhs) {
}

feStats &feStats::operator+=(const feStats &rhs) {
}

feStats &feStats::operator-=(const feStats &rhs) {
}

feStats &feStats::operator*=(const feStats &rhs) {
}

feStats &feStats::operator/=(const feStats &rhs) {
}
<commit_msg>operator overloads for feStats<commit_after>#include "feStats.h"

const feStats feStats::ZERO = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };

bool feStats::operator==(const feStats &rhs) const {
	return (hp == rhs.hp
			&& str == rhs.str
			&& mag == rhs.mag
			&& skl == rhs.skl
			&& spd == rhs.spd
			&& lck == rhs.lck
			&& def == rhs.def
			&& res == rhs.res
			&& con == rhs.con
			&& mov == rhs.mov);
}

feStats feStats::operator%(const feStats &rhs) const {
	feStats ret = {
		hp % rhs.hp,
	  str % rhs.str,
	  mag % rhs.mag,
	  skl % rhs.skl,
	  spd % rhs.spd,
	  lck % rhs.lck,
	  def % rhs.def,
	  res % rhs.res,
	  con % rhs.con,
	  mov % rhs.mov
	};
	return ret;
}

feStats feStats::operator+(const feStats &rhs) const {
	feStats sum = {
		hp  += rhs.hp,
		str += rhs.str,
		mag += rhs.mag,
		skl += rhs.skl,
		lck += rhs.lck,
		def += rhs.def,
		res += rhs.res,
		con += rhs.con,
		mov += rhs.mov};
	return sum;
}

feStats feStats::operator-(const feStats &rhs) const {
	feStats diff = {
		hp  -= rhs.hp,
		str -= rhs.str,
		mag -= rhs.mag,
		skl -= rhs.skl,
		lck -= rhs.lck,
		def -= rhs.def,
		res -= rhs.res,
		con -= rhs.con,
		mov -= rhs.mov};
	return diff;
}

feStats feStats::operator*(const feStats &rhs) const {
	feStats prod = {
		hp  *= rhs.hp,
		str *= rhs.str,
		mag *= rhs.mag,
		skl *= rhs.skl,
		lck *= rhs.lck,
		def *= rhs.def,
		res *= rhs.res,
		con *= rhs.con,
		mov *= rhs.mov};
	return prod;
}

feStats feStats::operator/(const feStats &rhs) const {
	feStats sum = {
		hp  /= rhs.hp,
		str /= rhs.str,
		mag /= rhs.mag,
		skl /= rhs.skl,
		lck /= rhs.lck,
		def /= rhs.def,
		res /= rhs.res,
		con /= rhs.con,
		mov /= rhs.mov};
	return sum;
}

feStats &feStats::operator=(const feStats &rhs) {
	this->hp  = rhs.hp;
	this->str = rhs.str;
	this->mag = rhs.mag;
	this->skl = rhs.skl;
	this->lck = rhs.lck;
	this->def = rhs.def;
	this->res = rhs.res;
	this->con = rhs.con;
	this->mov = rhs.mov;
	return *this;
}

feStats &feStats::operator+=(const feStats &rhs) {
	this->hp  += rhs.hp;
	this->str += rhs.str;
	this->mag += rhs.mag;
	this->skl += rhs.skl;
	this->lck += rhs.lck;
	this->def += rhs.def;
	this->res += rhs.res;
	this->con += rhs.con;
	this->mov += rhs.mov;
	return *this;
}

feStats &feStats::operator-=(const feStats &rhs) {
	this->hp  -= rhs.hp;
	this->str -= rhs.str;
	this->mag -= rhs.mag;
	this->skl -= rhs.skl;
	this->lck -= rhs.lck;
	this->def -= rhs.def;
	this->res -= rhs.res;
	this->con -= rhs.con;
	this->mov -= rhs.mov;
	return *this;
}

feStats &feStats::operator*=(const feStats &rhs) {
	this->hp  *= rhs.hp;
	this->str *= rhs.str;
	this->mag *= rhs.mag;
	this->skl *= rhs.skl;
	this->lck *= rhs.lck;
	this->def *= rhs.def;
	this->res *= rhs.res;
	this->con *= rhs.con;
	this->mov *= rhs.mov;
	return *this;
}

feStats &feStats::operator/=(const feStats &rhs) {
	this->hp  /= rhs.hp;
	this->str /= rhs.str;
	this->mag /= rhs.mag;
	this->skl /= rhs.skl;
	this->lck /= rhs.lck;
	this->def /= rhs.def;
	this->res /= rhs.res;
	this->con /= rhs.con;
	this->mov /= rhs.mov;
	return *this;
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: chgviset.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 17:27:10 $
 *
 *  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 SC_CHGVISET_HXX
#define SC_CHGVISET_HXX

#ifndef _DATETIME_HXX //autogen
#include <tools/datetime.hxx>
#endif

#ifndef _STRING_HXX //autogen
#include <tools/string.hxx>
#endif

#ifndef SC_RANGELST_HXX
#include "rangelst.hxx"
#endif

enum ScChgsDateMode{    SCDM_DATE_BEFORE=0,SCDM_DATE_SINCE=1,SCDM_DATE_EQUAL=2,
                        SCDM_DATE_NOTEQUAL=3,SCDM_DATE_BETWEEN=4, SCDM_DATE_SAVE=5,
                        SCDM_NO_DATEMODE=6};

namespace utl {
    class TextSearch;
}

class ScDocument;

class ScChangeViewSettings
{
private:

    utl::TextSearch*    pCommentSearcher;
    DateTime            aFirstDateTime;
    DateTime            aLastDateTime;
    String              aAuthorToShow;
    String              aComment;
    ScRangeList         aRangeList;
    ScChgsDateMode      eDateMode;
    BOOL                bShowIt;
    BOOL                bIsDate;
    BOOL                bIsAuthor;
    BOOL                bIsComment;
    BOOL                bIsRange;
    BOOL                bEveryoneButMe;
    BOOL                bShowAccepted;
    BOOL                bShowRejected;

public:

                        ScChangeViewSettings()
                        {
                            pCommentSearcher=NULL;
                            bIsDate=FALSE;
                            bIsAuthor=FALSE;
                            bIsRange=FALSE;
                            bIsComment=FALSE;
                            bShowIt=FALSE;
                            eDateMode=SCDM_DATE_BEFORE;
                            bEveryoneButMe=FALSE;
                            bShowAccepted=FALSE;
                            bShowRejected=FALSE;
                        }

                        ScChangeViewSettings( const ScChangeViewSettings& r );

                        ~ScChangeViewSettings();

    BOOL                ShowChanges() const {return bShowIt;}
    void                SetShowChanges(BOOL nFlag=TRUE){bShowIt=nFlag;}

    BOOL                HasDate() const {return bIsDate;}
    void                SetHasDate(BOOL nFlag=TRUE) {bIsDate=nFlag;}

    void                SetTheDateMode(ScChgsDateMode eDatMod){ eDateMode=eDatMod; }
    ScChgsDateMode      GetTheDateMode() const { return eDateMode; }

    void                SetTheFirstDateTime(const DateTime& aDateTime) {aFirstDateTime=aDateTime;}
    const DateTime&     GetTheFirstDateTime()const {return aFirstDateTime;}

    void                SetTheLastDateTime(const DateTime& aDateTime) {aLastDateTime=aDateTime;}
    const DateTime&     GetTheLastDateTime()const {return aLastDateTime;}

    BOOL                HasAuthor() const {return bIsAuthor;}
    void                SetHasAuthor(BOOL nFlag=TRUE) {bIsAuthor=nFlag;}

    String              GetTheAuthorToShow()const {return aAuthorToShow;}
    void                SetTheAuthorToShow(const String& aString){aAuthorToShow=aString;}

    BOOL                HasComment() const {return bIsComment;}
    void                SetHasComment(BOOL nFlag=TRUE) {bIsComment=nFlag;}

    String              GetTheComment()const {return aComment;}
    void                SetTheComment(const String& aString);

    BOOL                IsValidComment(const String* pCommentStr) const;

    BOOL                IsEveryoneButMe() const {return bEveryoneButMe;}
    void                SetEveryoneButMe(BOOL nFlag=TRUE) {bEveryoneButMe=nFlag;}

    BOOL                HasRange() const {return bIsRange;}
    void                SetHasRange(BOOL nFlag=TRUE) {bIsRange=nFlag;}

    const ScRangeList&  GetTheRangeList()const {return aRangeList;}
    void                SetTheRangeList(const ScRangeList& aRl){aRangeList=aRl;}

    BOOL                IsShowAccepted() const { return bShowAccepted; }
    void                SetShowAccepted( BOOL bVal ) { bShowAccepted = bVal; }

    BOOL                IsShowRejected() const { return bShowRejected; }
    void                SetShowRejected( BOOL bVal ) { bShowRejected = bVal; }

    void                Load( SvStream& rStream, USHORT nVer );
    void                Store( SvStream& rStream ) const;

    ScChangeViewSettings&   operator=   ( const ScChangeViewSettings& r );

                        /// Adjust dates according to selected DateMode
    void                AdjustDateMode( const ScDocument& rDoc );

};

#endif

<commit_msg>INTEGRATION: CWS calcshare_DEV300 (1.4.524); FILE MERGED 2007/12/04 12:59:09 tbe 1.4.524.1: #i8811# Allow multiple users to edit the same spreadsheet through workbook sharing<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: chgviset.hxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: kz $ $Date: 2008-03-07 12:15:05 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/
#ifndef SC_CHGVISET_HXX
#define SC_CHGVISET_HXX

#ifndef _DATETIME_HXX //autogen
#include <tools/datetime.hxx>
#endif

#ifndef _STRING_HXX //autogen
#include <tools/string.hxx>
#endif

#ifndef SC_RANGELST_HXX
#include "rangelst.hxx"
#endif

enum ScChgsDateMode{    SCDM_DATE_BEFORE=0,SCDM_DATE_SINCE=1,SCDM_DATE_EQUAL=2,
                        SCDM_DATE_NOTEQUAL=3,SCDM_DATE_BETWEEN=4, SCDM_DATE_SAVE=5,
                        SCDM_NO_DATEMODE=6};

namespace utl {
    class TextSearch;
}

class ScDocument;

class ScChangeViewSettings
{
private:

    utl::TextSearch*    pCommentSearcher;
    DateTime            aFirstDateTime;
    DateTime            aLastDateTime;
    String              aAuthorToShow;
    String              aComment;
    ScRangeList         aRangeList;
    ScChgsDateMode      eDateMode;
    BOOL                bShowIt;
    BOOL                bIsDate;
    BOOL                bIsAuthor;
    BOOL                bIsComment;
    BOOL                bIsRange;
    BOOL                bEveryoneButMe;
    BOOL                bShowAccepted;
    BOOL                bShowRejected;
    bool                mbIsActionRange;
    ULONG               mnFirstAction;
    ULONG               mnLastAction;

public:

                        ScChangeViewSettings()
                        {
                            pCommentSearcher=NULL;
                            bIsDate=FALSE;
                            bIsAuthor=FALSE;
                            bIsRange=FALSE;
                            bIsComment=FALSE;
                            bShowIt=FALSE;
                            eDateMode=SCDM_DATE_BEFORE;
                            bEveryoneButMe=FALSE;
                            bShowAccepted=FALSE;
                            bShowRejected=FALSE;
                            mbIsActionRange = false;
                        }

                        ScChangeViewSettings( const ScChangeViewSettings& r );

                        ~ScChangeViewSettings();

    BOOL                ShowChanges() const {return bShowIt;}
    void                SetShowChanges(BOOL nFlag=TRUE){bShowIt=nFlag;}

    BOOL                HasDate() const {return bIsDate;}
    void                SetHasDate(BOOL nFlag=TRUE) {bIsDate=nFlag;}

    void                SetTheDateMode(ScChgsDateMode eDatMod){ eDateMode=eDatMod; }
    ScChgsDateMode      GetTheDateMode() const { return eDateMode; }

    void                SetTheFirstDateTime(const DateTime& aDateTime) {aFirstDateTime=aDateTime;}
    const DateTime&     GetTheFirstDateTime()const {return aFirstDateTime;}

    void                SetTheLastDateTime(const DateTime& aDateTime) {aLastDateTime=aDateTime;}
    const DateTime&     GetTheLastDateTime()const {return aLastDateTime;}

    BOOL                HasAuthor() const {return bIsAuthor;}
    void                SetHasAuthor(BOOL nFlag=TRUE) {bIsAuthor=nFlag;}

    String              GetTheAuthorToShow()const {return aAuthorToShow;}
    void                SetTheAuthorToShow(const String& aString){aAuthorToShow=aString;}

    BOOL                HasComment() const {return bIsComment;}
    void                SetHasComment(BOOL nFlag=TRUE) {bIsComment=nFlag;}

    String              GetTheComment()const {return aComment;}
    void                SetTheComment(const String& aString);

    BOOL                IsValidComment(const String* pCommentStr) const;

    BOOL                IsEveryoneButMe() const {return bEveryoneButMe;}
    void                SetEveryoneButMe(BOOL nFlag=TRUE) {bEveryoneButMe=nFlag;}

    BOOL                HasRange() const {return bIsRange;}
    void                SetHasRange(BOOL nFlag=TRUE) {bIsRange=nFlag;}

    const ScRangeList&  GetTheRangeList()const {return aRangeList;}
    void                SetTheRangeList(const ScRangeList& aRl){aRangeList=aRl;}

    BOOL                IsShowAccepted() const { return bShowAccepted; }
    void                SetShowAccepted( BOOL bVal ) { bShowAccepted = bVal; }

    BOOL                IsShowRejected() const { return bShowRejected; }
    void                SetShowRejected( BOOL bVal ) { bShowRejected = bVal; }

    void                Load( SvStream& rStream, USHORT nVer );
    void                Store( SvStream& rStream ) const;

    ScChangeViewSettings&   operator=   ( const ScChangeViewSettings& r );

                        /// Adjust dates according to selected DateMode
    void                AdjustDateMode( const ScDocument& rDoc );

    bool                HasActionRange() const { return mbIsActionRange; }
    void                SetHasActionRange( bool nFlag = true ) { mbIsActionRange = nFlag; }
    void                GetTheActionRange( ULONG& nFirst, ULONG& nLast ) const { nFirst = mnFirstAction; nLast = mnLastAction; }
    void                SetTheActionRange( ULONG nFirst, ULONG nLast ) { mnFirstAction = nFirst; mnLastAction = nLast; }
};

#endif

<|endoftext|>