<commit_before>#include "connection.h"
#include <QTcpSocket>
#include <QMessageBox>
#include <tlv_parser/tlv_encoder.h>
#include "utils.h"
#include "utils_history.h"
#include "controlbarcommon.h"
#include "mainwindow.h"
#include <ui_controlbarcommon.h>

QString Connection::getClosestPresetName ()
{
	// bit clumsy, but no time to loose
	QString preset_name;
	QString const conn_name = m_control_bar->ui->presetComboBox->currentText();
	QString const parent_name = m_main_window->getCurrentPresetName();
	if (!parent_name.isEmpty() && validatePresetName(parent_name))
		preset_name = parent_name;
	else if (!conn_name.isEmpty() && validatePresetName(conn_name))
		preset_name = conn_name;
	else
		preset_name = g_defaultPresetName;
	return preset_name;
}

E_FeatureStates Connection::getClosestFeatureState (E_DataWidgetType type) const
{
	switch (type)
	{
		case e_data_log  : return static_cast<E_FeatureStates>(m_control_bar->ui->logSlider->value());
		case e_data_plot : return static_cast<E_FeatureStates>(m_control_bar->ui->plotSlider->value());
		case e_data_table: return static_cast<E_FeatureStates>(m_control_bar->ui->tableSlider->value());
		case e_data_gantt: return static_cast<E_FeatureStates>(m_control_bar->ui->ganttSlider->value());
		case e_data_frame: return static_cast<E_FeatureStates>(m_control_bar->ui->ganttSlider->value());
		default: return e_FtrDisabled;
	}
}

void Connection::setConfigValuesToUI (ConnectionConfig const & cfg)
{
	m_control_bar->ui->levelSpinBox->setValue(cfg.m_level);
	m_control_bar->ui->buffCheckBox->setChecked(cfg.m_buffered);
	syncHistoryToWidget(m_control_bar->ui->presetComboBox, cfg.m_preset_history);
	m_control_bar->ui->logSlider->setValue(cfg.m_logs_recv_level);
	m_control_bar->ui->plotSlider->setValue(cfg.m_plots_recv_level);
	m_control_bar->ui->tableSlider->setValue(cfg.m_tables_recv_level);
	m_control_bar->ui->ganttSlider->setValue(cfg.m_gantts_recv_level);
}

void Connection::setUIValuesToConfig (ConnectionConfig & cfg)
{
	cfg.m_level = m_control_bar->ui->levelSpinBox->value();
	cfg.m_buffered = m_control_bar->ui->buffCheckBox->isChecked();
	//
	cfg.m_logs_recv_level = static_cast<E_FeatureStates>(m_control_bar->ui->logSlider->value());
	cfg.m_plots_recv_level = static_cast<E_FeatureStates>(m_control_bar->ui->plotSlider->value());
	cfg.m_tables_recv_level = static_cast<E_FeatureStates>(m_control_bar->ui->tableSlider->value());
	cfg.m_gantts_recv_level = static_cast<E_FeatureStates>(m_control_bar->ui->ganttSlider->value());
}

void Connection::setLevelValue (int i) { m_control_bar->ui->levelSpinBox->setValue(i); }
void Connection::setBufferingState (int state) { m_control_bar->ui->buffCheckBox->setChecked(state); }
void Connection::setLogsState (int state) { m_control_bar->ui->logSlider->setValue(state); }
void Connection::setPlotsState (int state) { m_control_bar->ui->plotSlider->setValue(state); }
void Connection::setTablesState (int state) { m_control_bar->ui->tableSlider->setValue(state); }
void Connection::setGanttsState (int state) { m_control_bar->ui->ganttSlider->setValue(state); }

void Connection::onLogsStateChanged (int state)
{
	m_config.m_logs_recv_level = state;
}
void Connection::onPlotsStateChanged (int state)
{
	m_config.m_plots_recv_level = state;
}
void Connection::onTablesStateChanged (int state)
{
	m_config.m_tables_recv_level = state;
}
void Connection::onGanttsStateChanged (int state)
{
	m_config.m_gantts_recv_level = state;
}

void Connection::onLevelValueChanged (int val)
{
	char tlv_buff[16];
#ifdef __linux__
	int const result = snprintf(tlv_buff, 16, "%u", val);
#else
	int const result = _snprintf_s(tlv_buff, 16, "%u", val);
#endif

	if (result > 0)
	{
		m_config.m_level = val;
		char buff[256];
		using namespace tlv;
		Encoder e(cmd_set_level, buff, 256);
		e.Encode(TLV(tag_lvl, tlv_buff));
		if (m_tcpstream && e.Commit())
			m_tcpstream->write(e.buffer, e.total_len); /// @TODO: async write
	}
}

void Connection::onBufferingStateChanged (int state)
{
	bool const buffering_enabled = state == Qt::Checked;

	char tlv_buff[16];
#ifdef __linux__
	int const result = snprintf(tlv_buff, 16, "%u", buffering_enabled);
#else
	int const result = _snprintf_s(tlv_buff, 16, "%u", buffering_enabled);
#endif

	if (result > 0)
	{
		m_config.m_buffered = buffering_enabled;

		qDebug("Connection::onBufferingStateChanged to_state=%i", buffering_enabled);
		char buff[256];
		using namespace tlv;
		Encoder e(cmd_set_buffering, buff, 256);
		e.Encode(TLV(tag_bool, tlv_buff));
		if (m_tcpstream && e.Commit())
			m_tcpstream->write(e.buffer, e.total_len); /// @TODO: async write
	}
}

void Connection::onPresetChanged (int idx)
{
	m_config.m_preset_history.m_current_item = idx;
	QString const preset_name = getCurrentPresetName();
	QString const path = mkAppPresetPath(getGlobalConfig().m_appdir, m_app_name, preset_name);
	m_config.saveHistory(path);
}

void Connection::onPresetApply ()
{
	QString const txt = getCurrentPresetName();
	onPresetApply(txt);
}

void Connection::onPresetSave ()
{
	QString const txt = getCurrentPresetName();
	onPresetSave(txt);
}

void Connection::onPresetAdd ()
{
	qDebug("%s", __FUNCTION__);
	QString const preset_name = promptAndCreatePresetName();
	onPresetSave(preset_name);
}

void Connection::onPresetRm ()
{
	qDebug("%s", __FUNCTION__);
	QString const preset_name = m_control_bar->ui->presetComboBox->currentText();

	if (preset_name.isEmpty())
		return;

	qDebug("removing preset_name=%s", preset_name.toStdString().c_str());

	QString const path = mkAppPresetPath(getGlobalConfig().m_appdir, m_app_name, preset_name);
	qDebug("confirm to remove session file=%s", path.toStdString().c_str());

	QMessageBox msg_box;
	QPushButton * b_del = msg_box.addButton(tr("Yes, Delete"), QMessageBox::ActionRole);
	QPushButton * b_abort = msg_box.addButton(QMessageBox::Abort);
	msg_box.exec();
	if (msg_box.clickedButton() == b_abort)
		return;

	QFile qf(path);
	qf.remove();

	removeStringFromHistory(preset_name, m_control_bar->ui->presetComboBox, m_config.m_preset_history);
	m_control_bar->ui->presetComboBox->setCurrentIndex(-1);
}

void Connection::onPresetReset ()
{
}

//////////////////////////////////////////////////

QString Connection::getCurrentPresetName () const
{
	QString txt = m_control_bar->ui->presetComboBox->currentText();
	if (txt.isEmpty())
		txt = g_defaultPresetName;
	return txt;
}

void Connection::setPresetAsCurrent (QString const & pname)
{
	m_control_bar->ui->presetComboBox->setCurrentIndex(m_control_bar->ui->presetComboBox->findText(pname));
}

void Connection::onPresetApply (QString const & preset_name)
{
	QString const path = mkAppPresetPath(getGlobalConfig().m_appdir, m_app_name, preset_name);
	mentionStringInHistory_Ref(preset_name, m_control_bar->ui->presetComboBox, m_config.m_preset_history);
	m_config.saveHistory(path);
	setPresetAsCurrent(preset_name);

	if (checkAppPresetPath(getGlobalConfig().m_appdir, m_app_name, preset_name))
	{
		m_curr_preset = preset_name;

		loadConfigs(path);
		applyConfigs();
		m_main_window->loadLayout(path + "/" + g_presetLayoutName);
	}
	else
	{
		removeStringFromHistory(preset_name, m_control_bar->ui->presetComboBox, m_config.m_preset_history);
		m_config.saveHistory(path);
		m_control_bar->ui->presetComboBox->setCurrentIndex(-1);
	}
}

void Connection::onPresetSave (QString const & preset_name)
{
	qDebug("%s %s", __FUNCTION__, preset_name.toStdString().c_str());
	if (!validatePresetName(preset_name))
		return;

	qDebug("SaveAs to preset_name=%s", preset_name.toStdString().c_str());
	QString const path = mkAppPresetPath(getGlobalConfig().m_appdir, m_app_name, preset_name);
	mentionStringInHistory_Ref(preset_name, m_control_bar->ui->presetComboBox, m_config.m_preset_history);
	m_config.saveHistory(path);
	setPresetAsCurrent(preset_name);

	createAppPresetPath(getGlobalConfig().m_appdir, m_app_name, preset_name);

	m_curr_preset = preset_name; // @TODO: ?? or only on apply preset?

	saveConfigs(path);
	m_main_window->saveLayout(path + "/" + g_presetLayoutName);
}

/*void Connection::mentionInPresetHistory (QString const & str)
{
	if (str.isEmpty() || !validatePresetName(str))
		return;

	mentionStringInHistory_NoRef(str, m_control_bar->ui->presetComboBox, m_config.m_preset_history);
	QString const path = mkAppPresetPath(getGlobalConfig().m_appdir, m_app_name, preset_name);
	m_config.saveHistory(path);
}*/

<commit_msg>+ flush commands sent back to client<commit_after>#include "connection.h"
#include <QTcpSocket>
#include <QMessageBox>
#include <tlv_parser/tlv_encoder.h>
#include "utils.h"
#include "utils_history.h"
#include "controlbarcommon.h"
#include "mainwindow.h"
#include <ui_controlbarcommon.h>

QString Connection::getClosestPresetName ()
{
	// bit clumsy, but no time to loose
	QString preset_name;
	QString const conn_name = m_control_bar->ui->presetComboBox->currentText();
	QString const parent_name = m_main_window->getCurrentPresetName();
	if (!parent_name.isEmpty() && validatePresetName(parent_name))
		preset_name = parent_name;
	else if (!conn_name.isEmpty() && validatePresetName(conn_name))
		preset_name = conn_name;
	else
		preset_name = g_defaultPresetName;
	return preset_name;
}

E_FeatureStates Connection::getClosestFeatureState (E_DataWidgetType type) const
{
	switch (type)
	{
		case e_data_log  : return static_cast<E_FeatureStates>(m_control_bar->ui->logSlider->value());
		case e_data_plot : return static_cast<E_FeatureStates>(m_control_bar->ui->plotSlider->value());
		case e_data_table: return static_cast<E_FeatureStates>(m_control_bar->ui->tableSlider->value());
		case e_data_gantt: return static_cast<E_FeatureStates>(m_control_bar->ui->ganttSlider->value());
		case e_data_frame: return static_cast<E_FeatureStates>(m_control_bar->ui->ganttSlider->value());
		default: return e_FtrDisabled;
	}
}

void Connection::setConfigValuesToUI (ConnectionConfig const & cfg)
{
	m_control_bar->ui->levelSpinBox->setValue(cfg.m_level);
	m_control_bar->ui->buffCheckBox->setChecked(cfg.m_buffered);
	syncHistoryToWidget(m_control_bar->ui->presetComboBox, cfg.m_preset_history);
	m_control_bar->ui->logSlider->setValue(cfg.m_logs_recv_level);
	m_control_bar->ui->plotSlider->setValue(cfg.m_plots_recv_level);
	m_control_bar->ui->tableSlider->setValue(cfg.m_tables_recv_level);
	m_control_bar->ui->ganttSlider->setValue(cfg.m_gantts_recv_level);
}

void Connection::setUIValuesToConfig (ConnectionConfig & cfg)
{
	cfg.m_level = m_control_bar->ui->levelSpinBox->value();
	cfg.m_buffered = m_control_bar->ui->buffCheckBox->isChecked();
	//
	cfg.m_logs_recv_level = static_cast<E_FeatureStates>(m_control_bar->ui->logSlider->value());
	cfg.m_plots_recv_level = static_cast<E_FeatureStates>(m_control_bar->ui->plotSlider->value());
	cfg.m_tables_recv_level = static_cast<E_FeatureStates>(m_control_bar->ui->tableSlider->value());
	cfg.m_gantts_recv_level = static_cast<E_FeatureStates>(m_control_bar->ui->ganttSlider->value());
}

void Connection::setLevelValue (int i) { m_control_bar->ui->levelSpinBox->setValue(i); }
void Connection::setBufferingState (int state) { m_control_bar->ui->buffCheckBox->setChecked(state); }
void Connection::setLogsState (int state) { m_control_bar->ui->logSlider->setValue(state); }
void Connection::setPlotsState (int state) { m_control_bar->ui->plotSlider->setValue(state); }
void Connection::setTablesState (int state) { m_control_bar->ui->tableSlider->setValue(state); }
void Connection::setGanttsState (int state) { m_control_bar->ui->ganttSlider->setValue(state); }

void Connection::onLogsStateChanged (int state)
{
	m_config.m_logs_recv_level = state;
}
void Connection::onPlotsStateChanged (int state)
{
	m_config.m_plots_recv_level = state;
}
void Connection::onTablesStateChanged (int state)
{
	m_config.m_tables_recv_level = state;
}
void Connection::onGanttsStateChanged (int state)
{
	m_config.m_gantts_recv_level = state;
}

void Connection::onLevelValueChanged (int val)
{
	char tlv_buff[16];
#ifdef __linux__
	int const result = snprintf(tlv_buff, 16, "%u", val);
#else
	int const result = _snprintf_s(tlv_buff, 16, "%u", val);
#endif

	if (result > 0)
	{
		m_config.m_level = val;
		char buff[256];
		using namespace tlv;
		Encoder e(cmd_set_level, buff, 256);
		e.Encode(TLV(tag_lvl, tlv_buff));
		if (m_tcpstream && e.Commit())
		{
			m_tcpstream->write(e.buffer, e.total_len);
			m_tcpstream->flush();
		}
	}
}

void Connection::onBufferingStateChanged (int state)
{
	bool const buffering_enabled = state == Qt::Checked;

	char tlv_buff[16];
#ifdef __linux__
	int const result = snprintf(tlv_buff, 16, "%u", buffering_enabled);
#else
	int const result = _snprintf_s(tlv_buff, 16, "%u", buffering_enabled);
#endif

	if (result > 0)
	{
		m_config.m_buffered = buffering_enabled;

		qDebug("Connection::onBufferingStateChanged to_state=%i", buffering_enabled);
		char buff[256];
		using namespace tlv;
		Encoder e(cmd_set_buffering, buff, 256);
		e.Encode(TLV(tag_bool, tlv_buff));
		if (m_tcpstream && e.Commit())
		{
			m_tcpstream->write(e.buffer, e.total_len);
			m_tcpstream->flush();
		}
	}
}

void Connection::onPresetChanged (int idx)
{
	m_config.m_preset_history.m_current_item = idx;
	QString const preset_name = getCurrentPresetName();
	QString const path = mkAppPresetPath(getGlobalConfig().m_appdir, m_app_name, preset_name);
	m_config.saveHistory(path);
}

void Connection::onPresetApply ()
{
	QString const txt = getCurrentPresetName();
	onPresetApply(txt);
}

void Connection::onPresetSave ()
{
	QString const txt = getCurrentPresetName();
	onPresetSave(txt);
}

void Connection::onPresetAdd ()
{
	qDebug("%s", __FUNCTION__);
	QString const preset_name = promptAndCreatePresetName();
	onPresetSave(preset_name);
}

void Connection::onPresetRm ()
{
	qDebug("%s", __FUNCTION__);
	QString const preset_name = m_control_bar->ui->presetComboBox->currentText();

	if (preset_name.isEmpty())
		return;

	qDebug("removing preset_name=%s", preset_name.toStdString().c_str());

	QString const path = mkAppPresetPath(getGlobalConfig().m_appdir, m_app_name, preset_name);
	qDebug("confirm to remove session file=%s", path.toStdString().c_str());

	QMessageBox msg_box;
	QPushButton * b_del = msg_box.addButton(tr("Yes, Delete"), QMessageBox::ActionRole);
	QPushButton * b_abort = msg_box.addButton(QMessageBox::Abort);
	msg_box.exec();
	if (msg_box.clickedButton() == b_abort)
		return;

	QFile qf(path);
	qf.remove();

	removeStringFromHistory(preset_name, m_control_bar->ui->presetComboBox, m_config.m_preset_history);
	m_control_bar->ui->presetComboBox->setCurrentIndex(-1);
}

void Connection::onPresetReset ()
{
}

//////////////////////////////////////////////////

QString Connection::getCurrentPresetName () const
{
	QString txt = m_control_bar->ui->presetComboBox->currentText();
	if (txt.isEmpty())
		txt = g_defaultPresetName;
	return txt;
}

void Connection::setPresetAsCurrent (QString const & pname)
{
	m_control_bar->ui->presetComboBox->setCurrentIndex(m_control_bar->ui->presetComboBox->findText(pname));
}

void Connection::onPresetApply (QString const & preset_name)
{
	QString const path = mkAppPresetPath(getGlobalConfig().m_appdir, m_app_name, preset_name);
	mentionStringInHistory_Ref(preset_name, m_control_bar->ui->presetComboBox, m_config.m_preset_history);
	m_config.saveHistory(path);
	setPresetAsCurrent(preset_name);

	if (checkAppPresetPath(getGlobalConfig().m_appdir, m_app_name, preset_name))
	{
		m_curr_preset = preset_name;

		loadConfigs(path);
		applyConfigs();
		m_main_window->loadLayout(path + "/" + g_presetLayoutName);
	}
	else
	{
		removeStringFromHistory(preset_name, m_control_bar->ui->presetComboBox, m_config.m_preset_history);
		m_config.saveHistory(path);
		m_control_bar->ui->presetComboBox->setCurrentIndex(-1);
	}
}

void Connection::onPresetSave (QString const & preset_name)
{
	qDebug("%s %s", __FUNCTION__, preset_name.toStdString().c_str());
	if (!validatePresetName(preset_name))
		return;

	qDebug("SaveAs to preset_name=%s", preset_name.toStdString().c_str());
	QString const path = mkAppPresetPath(getGlobalConfig().m_appdir, m_app_name, preset_name);
	mentionStringInHistory_Ref(preset_name, m_control_bar->ui->presetComboBox, m_config.m_preset_history);
	m_config.saveHistory(path);
	setPresetAsCurrent(preset_name);

	createAppPresetPath(getGlobalConfig().m_appdir, m_app_name, preset_name);

	m_curr_preset = preset_name; // @TODO: ?? or only on apply preset?

	saveConfigs(path);
	m_main_window->saveLayout(path + "/" + g_presetLayoutName);
}

/*void Connection::mentionInPresetHistory (QString const & str)
{
	if (str.isEmpty() || !validatePresetName(str))
		return;

	mentionStringInHistory_NoRef(str, m_control_bar->ui->presetComboBox, m_config.m_preset_history);
	QString const path = mkAppPresetPath(getGlobalConfig().m_appdir, m_app_name, preset_name);
	m_config.saveHistory(path);
}*/

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: QueryViewSwitch.cxx,v $
 *
 *  $Revision: 1.28 $
 *
 *  last change: $Author: kz $ $Date: 2007-05-10 10:38:41 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_dbaccess.hxx"
#ifndef DBAUI_QUERYVIEWSWITCH_HXX
#include "QueryViewSwitch.hxx"
#endif
#ifndef DBAUI_QUERYDESIGNVIEW_HXX
#include "QueryDesignView.hxx"
#endif
#ifndef DBAUI_QUERYVIEW_TEXT_HXX
#include "QueryTextView.hxx"
#endif
#ifndef DBAUI_QUERYCONTAINERWINDOW_HXX
#include "querycontainerwindow.hxx"
#endif
#ifndef _DBAUI_MODULE_DBU_HXX_
#include "moduledbu.hxx"
#endif
#ifndef _DBU_QRY_HRC_
#include "dbu_qry.hrc"
#endif
#ifndef DBACCESS_UI_BROWSER_ID_HXX
#include "browserids.hxx"
#endif
#ifndef DBAUI_QYDLGTAB_HXX
#include "adtabdlg.hxx"
#endif
#ifndef DBAUI_QUERYCONTROLLER_HXX
#include "querycontroller.hxx"
#endif
#ifndef DBAUI_SQLEDIT_HXX
#include "sqledit.hxx"
#endif
#ifndef DBAUI_QUERYCONTAINERWINDOW_HXX
#include "querycontainerwindow.hxx"
#endif

using namespace dbaui;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;

DBG_NAME(OQueryViewSwitch)
OQueryViewSwitch::OQueryViewSwitch(OQueryContainerWindow* _pParent, OQueryController* _pController,const Reference< XMultiServiceFactory >& _rFactory)
: m_bAddTableDialogWasVisible(sal_False)
{
    DBG_CTOR(OQueryViewSwitch,NULL);

    m_pTextView     = new OQueryTextView(_pParent);
    m_pDesignView   = new OQueryDesignView(_pParent,_pController,_rFactory);
}
// -----------------------------------------------------------------------------
OQueryViewSwitch::~OQueryViewSwitch()
{
    DBG_DTOR(OQueryViewSwitch,NULL);
    {
        ::std::auto_ptr<Window> aTemp(m_pTextView);
        m_pTextView = NULL;
    }
    {
        ::std::auto_ptr<Window> aTemp(m_pDesignView);
        m_pDesignView = NULL;
    }
}
// -------------------------------------------------------------------------
void OQueryViewSwitch::Construct()
{
    m_pDesignView->Construct( );
}
// -----------------------------------------------------------------------------
void OQueryViewSwitch::initialize()
{
    // initially be in SQL mode
    m_pTextView->Show();
    m_pDesignView->initialize();
}
// -------------------------------------------------------------------------
void OQueryViewSwitch::resizeDocumentView(Rectangle& _rPlayground)
{
    m_pTextView->SetPosSizePixel( _rPlayground.TopLeft(), _rPlayground.GetSize() );
    m_pDesignView->SetPosSizePixel( _rPlayground.TopLeft(), _rPlayground.GetSize() );

    // just for completeness: there is no space left, we occupied it all ...
    _rPlayground.SetPos( _rPlayground.BottomRight() );
    _rPlayground.SetSize( Size( 0, 0 ) );
}
// -----------------------------------------------------------------------------
sal_Bool OQueryViewSwitch::checkStatement()
{
    if(m_pTextView->IsVisible())
        return m_pTextView->checkStatement();
    return m_pDesignView->checkStatement();
}
// -----------------------------------------------------------------------------
::rtl::OUString OQueryViewSwitch::getStatement()
{
    if(m_pTextView->IsVisible())
        return m_pTextView->getStatement();
    return m_pDesignView->getStatement();
}
// -----------------------------------------------------------------------------
void OQueryViewSwitch::setReadOnly(sal_Bool _bReadOnly)
{
    if(m_pTextView->IsVisible())
        m_pTextView->setReadOnly(_bReadOnly);
    else
        m_pDesignView->setReadOnly(_bReadOnly);
}
// -----------------------------------------------------------------------------
void OQueryViewSwitch::clear()
{
    if(m_pTextView->IsVisible())
        m_pTextView->clear();
    else
        m_pDesignView->clear();
}
// -----------------------------------------------------------------------------
void OQueryViewSwitch::GrabFocus()
{
    if ( m_pTextView && m_pTextView->IsVisible() )
        m_pTextView->GrabFocus();
    else if ( m_pDesignView && m_pDesignView->IsVisible() )
        m_pDesignView->GrabFocus();
}
// -----------------------------------------------------------------------------
void OQueryViewSwitch::setStatement(const ::rtl::OUString& _rsStatement)
{
    if(m_pTextView->IsVisible())
        m_pTextView->setStatement(_rsStatement);
    else
        m_pDesignView->setStatement(_rsStatement);
}
// -----------------------------------------------------------------------------
void OQueryViewSwitch::copy()
{
    if(m_pTextView->IsVisible())
        m_pTextView->copy();
    else
        m_pDesignView->copy();
}
// -----------------------------------------------------------------------------
sal_Bool OQueryViewSwitch::isCutAllowed()
{
    if(m_pTextView->IsVisible())
        return m_pTextView->isCutAllowed();
    return m_pDesignView->isCutAllowed();
}
// -----------------------------------------------------------------------------
sal_Bool OQueryViewSwitch::isCopyAllowed()
{
    if(m_pTextView->IsVisible())
        return m_pTextView->isCopyAllowed();
    return m_pDesignView->isCopyAllowed();
}
// -----------------------------------------------------------------------------
sal_Bool OQueryViewSwitch::isPasteAllowed()
{
    if(m_pTextView->IsVisible())
        return m_pTextView->isPasteAllowed();
    return m_pDesignView->isPasteAllowed();
}
// -----------------------------------------------------------------------------
void OQueryViewSwitch::cut()
{
    if(m_pTextView->IsVisible())
        m_pTextView->cut();
    else
        m_pDesignView->cut();
}
// -----------------------------------------------------------------------------
void OQueryViewSwitch::paste()
{
    if(m_pTextView->IsVisible())
        m_pTextView->paste();
    else
        m_pDesignView->paste();
}
// -----------------------------------------------------------------------------
OQueryContainerWindow* OQueryViewSwitch::getContainer() const
{
    Window* pDesignParent = getDesignView() ? getDesignView()->GetParent() : NULL;
    return static_cast< OQueryContainerWindow* >( pDesignParent );
}

// -----------------------------------------------------------------------------
sal_Bool OQueryViewSwitch::switchView()
{
    sal_Bool bRet = sal_True;
    sal_Bool bGraphicalDesign = static_cast<OQueryController*>(m_pDesignView->getController())->isDesignMode();

    OAddTableDlg* pAddTabDialog( getAddTableDialog() );

    if ( !bGraphicalDesign ) // we have to hide the add table dialog
    {
        m_bAddTableDialogWasVisible = pAddTabDialog ? pAddTabDialog->IsVisible() : false;
        if ( m_bAddTableDialogWasVisible )
            pAddTabDialog->Hide();
    }

    OQueryContainerWindow* pContainer = getContainer();
    if ( !bGraphicalDesign )
    {
        m_pDesignView->stopTimer();
        m_pTextView->getSqlEdit()->startTimer();

        m_pTextView->clear();
        m_pTextView->setStatement(static_cast<OQueryController*>(m_pDesignView->getController())->getStatement());
    }
    else
    {
        ::rtl::OUString sOldStatement = static_cast<OQueryController*>(m_pDesignView->getController())->getStatement();
        // we have to stop the sqledit from our textview
        m_pTextView->getSqlEdit()->stopTimer();

        if ( pAddTabDialog )
            pAddTabDialog->Update();
        bRet = m_pDesignView->InitFromParseNode();

        // only show the view when the data is inserted
        m_pDesignView->startTimer();
    }

    if ( bRet )
    {
        m_pTextView->Show   ( !bGraphicalDesign );
        m_pDesignView->Show ( bGraphicalDesign );
        if ( bGraphicalDesign && m_bAddTableDialogWasVisible && pAddTabDialog )
            pAddTabDialog->Show();

        GrabFocus();
    }

    if ( pContainer )
        pContainer->Resize();

    m_pDesignView->getController()->getUndoMgr()->Clear();
    m_pDesignView->getController()->InvalidateAll();

    return bRet;
}
// -----------------------------------------------------------------------------
OAddTableDlg* OQueryViewSwitch::getAddTableDialog()
{
    if ( !m_pDesignView )
        return NULL;
    if ( !m_pDesignView->getController() )
        return NULL;
    return m_pDesignView->getController()->getAddTableDialog();
}
// -----------------------------------------------------------------------------
sal_Bool OQueryViewSwitch::isSlotEnabled(sal_Int32 _nSlotId)
{
    return m_pDesignView->isSlotEnabled(_nSlotId);
}
// -----------------------------------------------------------------------------
void OQueryViewSwitch::setSlotEnabled(sal_Int32 _nSlotId,sal_Bool _bEnable)
{
    m_pDesignView->setSlotEnabled(_nSlotId,_bEnable);
}
// -----------------------------------------------------------------------------
void OQueryViewSwitch::SaveUIConfig()
{
    if(m_pDesignView->IsVisible())
        m_pDesignView->SaveUIConfig();
}
// -----------------------------------------------------------------------------
void OQueryViewSwitch::SetPosSizePixel( Point _rPt,Size _rSize)
{
    m_pDesignView->SetPosSizePixel( _rPt,_rSize);
    m_pDesignView->Resize();
    m_pTextView->SetPosSizePixel( _rPt,_rSize);
}
// -----------------------------------------------------------------------------
Reference< XMultiServiceFactory > OQueryViewSwitch::getORB() const
{
    return m_pDesignView->getORB();
}
// -----------------------------------------------------------------------------
void OQueryViewSwitch::reset()
{
    m_pDesignView->reset();
    if ( m_pDesignView->InitFromParseNode() )
        switchView();
}
// -----------------------------------------------------------------------------
void OQueryViewSwitch::setNoneVisbleRow(sal_Int32 _nRows)
{
    if(m_pDesignView)
        m_pDesignView->setNoneVisbleRow(_nRows);
}
// -----------------------------------------------------------------------------
<commit_msg>INTEGRATION: CWS oj14 (1.24.8); FILE MERGED 2007/06/04 18:53:42 oj 1.24.8.6: RESYNC: (1.27-1.28); FILE MERGED 2006/11/07 09:44:06 oj 1.24.8.5: RESYNC: (1.25-1.27); FILE MERGED 2006/07/04 08:18:20 oj 1.24.8.4: RESYNC: (1.24-1.25); FILE MERGED 2006/04/25 12:49:33 oj 1.24.8.3: new include 2006/03/20 07:48:53 oj 1.24.8.2: use of module client helper 2006/01/03 07:49:23 oj 1.24.8.1: changed module client<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: QueryViewSwitch.cxx,v $
 *
 *  $Revision: 1.29 $
 *
 *  last change: $Author: rt $ $Date: 2007-07-06 08:39:32 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_dbaccess.hxx"
#ifndef DBAUI_QUERYVIEWSWITCH_HXX
#include "QueryViewSwitch.hxx"
#endif
#ifndef DBAUI_QUERYDESIGNVIEW_HXX
#include "QueryDesignView.hxx"
#endif
#ifndef DBAUI_QUERYVIEW_TEXT_HXX
#include "QueryTextView.hxx"
#endif
#ifndef DBAUI_QUERYCONTAINERWINDOW_HXX
#include "querycontainerwindow.hxx"
#endif
#ifndef _DBU_QRY_HRC_
#include "dbu_qry.hrc"
#endif
#ifndef DBACCESS_UI_BROWSER_ID_HXX
#include "browserids.hxx"
#endif
#ifndef DBAUI_QYDLGTAB_HXX
#include "adtabdlg.hxx"
#endif
#ifndef DBAUI_QUERYCONTROLLER_HXX
#include "querycontroller.hxx"
#endif
#ifndef DBAUI_SQLEDIT_HXX
#include "sqledit.hxx"
#endif
#ifndef DBAUI_QUERYCONTAINERWINDOW_HXX
#include "querycontainerwindow.hxx"
#endif

using namespace dbaui;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;

DBG_NAME(OQueryViewSwitch)
OQueryViewSwitch::OQueryViewSwitch(OQueryContainerWindow* _pParent, OQueryController* _pController,const Reference< XMultiServiceFactory >& _rFactory)
: m_bAddTableDialogWasVisible(sal_False)
{
    DBG_CTOR(OQueryViewSwitch,NULL);

    m_pTextView     = new OQueryTextView(_pParent);
    m_pDesignView   = new OQueryDesignView(_pParent,_pController,_rFactory);
}
// -----------------------------------------------------------------------------
OQueryViewSwitch::~OQueryViewSwitch()
{
    DBG_DTOR(OQueryViewSwitch,NULL);
    {
        ::std::auto_ptr<Window> aTemp(m_pTextView);
        m_pTextView = NULL;
    }
    {
        ::std::auto_ptr<Window> aTemp(m_pDesignView);
        m_pDesignView = NULL;
    }
}
// -------------------------------------------------------------------------
void OQueryViewSwitch::Construct()
{
    m_pDesignView->Construct( );
}
// -----------------------------------------------------------------------------
void OQueryViewSwitch::initialize()
{
    // initially be in SQL mode
    m_pTextView->Show();
    m_pDesignView->initialize();
}
// -------------------------------------------------------------------------
void OQueryViewSwitch::resizeDocumentView(Rectangle& _rPlayground)
{
    m_pTextView->SetPosSizePixel( _rPlayground.TopLeft(), _rPlayground.GetSize() );
    m_pDesignView->SetPosSizePixel( _rPlayground.TopLeft(), _rPlayground.GetSize() );

    // just for completeness: there is no space left, we occupied it all ...
    _rPlayground.SetPos( _rPlayground.BottomRight() );
    _rPlayground.SetSize( Size( 0, 0 ) );
}
// -----------------------------------------------------------------------------
sal_Bool OQueryViewSwitch::checkStatement()
{
    if(m_pTextView->IsVisible())
        return m_pTextView->checkStatement();
    return m_pDesignView->checkStatement();
}
// -----------------------------------------------------------------------------
::rtl::OUString OQueryViewSwitch::getStatement()
{
    if(m_pTextView->IsVisible())
        return m_pTextView->getStatement();
    return m_pDesignView->getStatement();
}
// -----------------------------------------------------------------------------
void OQueryViewSwitch::setReadOnly(sal_Bool _bReadOnly)
{
    if(m_pTextView->IsVisible())
        m_pTextView->setReadOnly(_bReadOnly);
    else
        m_pDesignView->setReadOnly(_bReadOnly);
}
// -----------------------------------------------------------------------------
void OQueryViewSwitch::clear()
{
    if(m_pTextView->IsVisible())
        m_pTextView->clear();
    else
        m_pDesignView->clear();
}
// -----------------------------------------------------------------------------
void OQueryViewSwitch::GrabFocus()
{
    if ( m_pTextView && m_pTextView->IsVisible() )
        m_pTextView->GrabFocus();
    else if ( m_pDesignView && m_pDesignView->IsVisible() )
        m_pDesignView->GrabFocus();
}
// -----------------------------------------------------------------------------
void OQueryViewSwitch::setStatement(const ::rtl::OUString& _rsStatement)
{
    if(m_pTextView->IsVisible())
        m_pTextView->setStatement(_rsStatement);
    else
        m_pDesignView->setStatement(_rsStatement);
}
// -----------------------------------------------------------------------------
void OQueryViewSwitch::copy()
{
    if(m_pTextView->IsVisible())
        m_pTextView->copy();
    else
        m_pDesignView->copy();
}
// -----------------------------------------------------------------------------
sal_Bool OQueryViewSwitch::isCutAllowed()
{
    if(m_pTextView->IsVisible())
        return m_pTextView->isCutAllowed();
    return m_pDesignView->isCutAllowed();
}
// -----------------------------------------------------------------------------
sal_Bool OQueryViewSwitch::isCopyAllowed()
{
    if(m_pTextView->IsVisible())
        return m_pTextView->isCopyAllowed();
    return m_pDesignView->isCopyAllowed();
}
// -----------------------------------------------------------------------------
sal_Bool OQueryViewSwitch::isPasteAllowed()
{
    if(m_pTextView->IsVisible())
        return m_pTextView->isPasteAllowed();
    return m_pDesignView->isPasteAllowed();
}
// -----------------------------------------------------------------------------
void OQueryViewSwitch::cut()
{
    if(m_pTextView->IsVisible())
        m_pTextView->cut();
    else
        m_pDesignView->cut();
}
// -----------------------------------------------------------------------------
void OQueryViewSwitch::paste()
{
    if(m_pTextView->IsVisible())
        m_pTextView->paste();
    else
        m_pDesignView->paste();
}
// -----------------------------------------------------------------------------
OQueryContainerWindow* OQueryViewSwitch::getContainer() const
{
    Window* pDesignParent = getDesignView() ? getDesignView()->GetParent() : NULL;
    return static_cast< OQueryContainerWindow* >( pDesignParent );
}

// -----------------------------------------------------------------------------
sal_Bool OQueryViewSwitch::switchView()
{
    sal_Bool bRet = sal_True;
    sal_Bool bGraphicalDesign = static_cast<OQueryController*>(m_pDesignView->getController())->isDesignMode();

    OAddTableDlg* pAddTabDialog( getAddTableDialog() );

    if ( !bGraphicalDesign ) // we have to hide the add table dialog
    {
        m_bAddTableDialogWasVisible = pAddTabDialog ? pAddTabDialog->IsVisible() : false;
        if ( m_bAddTableDialogWasVisible )
            pAddTabDialog->Hide();
    }

    OQueryContainerWindow* pContainer = getContainer();
    if ( !bGraphicalDesign )
    {
        m_pDesignView->stopTimer();
        m_pTextView->getSqlEdit()->startTimer();

        m_pTextView->clear();
        m_pTextView->setStatement(static_cast<OQueryController*>(m_pDesignView->getController())->getStatement());
    }
    else
    {
        ::rtl::OUString sOldStatement = static_cast<OQueryController*>(m_pDesignView->getController())->getStatement();
        // we have to stop the sqledit from our textview
        m_pTextView->getSqlEdit()->stopTimer();

        if ( pAddTabDialog )
            pAddTabDialog->Update();
        bRet = m_pDesignView->InitFromParseNode();

        // only show the view when the data is inserted
        m_pDesignView->startTimer();
    }

    if ( bRet )
    {
        m_pTextView->Show   ( !bGraphicalDesign );
        m_pDesignView->Show ( bGraphicalDesign );
        if ( bGraphicalDesign && m_bAddTableDialogWasVisible && pAddTabDialog )
            pAddTabDialog->Show();

        GrabFocus();
    }

    if ( pContainer )
        pContainer->Resize();

    m_pDesignView->getController()->getUndoMgr()->Clear();
    m_pDesignView->getController()->InvalidateAll();

    return bRet;
}
// -----------------------------------------------------------------------------
OAddTableDlg* OQueryViewSwitch::getAddTableDialog()
{
    if ( !m_pDesignView )
        return NULL;
    if ( !m_pDesignView->getController() )
        return NULL;
    return m_pDesignView->getController()->getAddTableDialog();
}
// -----------------------------------------------------------------------------
sal_Bool OQueryViewSwitch::isSlotEnabled(sal_Int32 _nSlotId)
{
    return m_pDesignView->isSlotEnabled(_nSlotId);
}
// -----------------------------------------------------------------------------
void OQueryViewSwitch::setSlotEnabled(sal_Int32 _nSlotId,sal_Bool _bEnable)
{
    m_pDesignView->setSlotEnabled(_nSlotId,_bEnable);
}
// -----------------------------------------------------------------------------
void OQueryViewSwitch::SaveUIConfig()
{
    if(m_pDesignView->IsVisible())
        m_pDesignView->SaveUIConfig();
}
// -----------------------------------------------------------------------------
void OQueryViewSwitch::SetPosSizePixel( Point _rPt,Size _rSize)
{
    m_pDesignView->SetPosSizePixel( _rPt,_rSize);
    m_pDesignView->Resize();
    m_pTextView->SetPosSizePixel( _rPt,_rSize);
}
// -----------------------------------------------------------------------------
Reference< XMultiServiceFactory > OQueryViewSwitch::getORB() const
{
    return m_pDesignView->getORB();
}
// -----------------------------------------------------------------------------
void OQueryViewSwitch::reset()
{
    m_pDesignView->reset();
    if ( m_pDesignView->InitFromParseNode() )
        switchView();
}
// -----------------------------------------------------------------------------
void OQueryViewSwitch::setNoneVisbleRow(sal_Int32 _nRows)
{
    if(m_pDesignView)
        m_pDesignView->setNoneVisbleRow(_nRows);
}
// -----------------------------------------------------------------------------
<|endoftext|>


<commit_before>//===- llvm/ADT/SmallVector.cpp - 'Normally small' vectors ----------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License.
// ==============================================================================
// LLVM Release License
// ==============================================================================
// University of Illinois/NCSA
// Open Source License
//
// Copyright (c) 2003-2010 University of Illinois at Urbana-Champaign.
// All rights reserved.
//
// Developed by:
//
// LLVM Team
//
// University of Illinois at Urbana-Champaign
//
// http://llvm.org
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal with
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
// of the Software, and to permit persons to whom the Software is furnished to do
// so, subject to the following conditions:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimers.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimers in the
// documentation and/or other materials provided with the distribution.
//
// * Neither the names of the LLVM Team, University of Illinois at
// Urbana-Champaign, nor the names of its contributors may be used to
// endorse or promote products derived from this Software without specific
// prior written permission.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
// CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS WITH THE
// SOFTWARE.
//
//===----------------------------------------------------------------------===//
//
// This file implements the SmallVector class.
//
//===----------------------------------------------------------------------===//

#include "OgreSmallVector.h"

namespace Ogre {

/// grow_pod - This is an implementation of the grow() method which only works
/// on POD-like datatypes and is out of line to reduce code duplication.
void SmallVectorBase::grow_pod(size_t MinSizeInBytes, size_t TSize) {
	size_t CurSizeBytes = size_in_bytes();
  size_t NewCapacityInBytes = 2 * capacity_in_bytes() + TSize; // Always grow.
	if (NewCapacityInBytes < MinSizeInBytes)
		NewCapacityInBytes = MinSizeInBytes;

  void *NewElts;
  if (this->isSmall()) {
    NewElts = malloc(NewCapacityInBytes);

	// Copy the elements over.  No need to run dtors on PODs.
	memcpy(NewElts, this->BeginX, CurSizeBytes);
  } else {
    // If this wasn't grown from the inline copy, grow the allocated space.
    NewElts = realloc(this->BeginX, NewCapacityInBytes);
  }

	this->EndX = (char*)NewElts+CurSizeBytes;
	this->BeginX = NewElts;
	this->CapacityX = (char*)this->BeginX + NewCapacityInBytes;
}

}<commit_msg>Added missing #include "OgreStableHeaders.h" to OgreSmallVector.cpp.<commit_after>//===- llvm/ADT/SmallVector.cpp - 'Normally small' vectors ----------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License.
// ==============================================================================
// LLVM Release License
// ==============================================================================
// University of Illinois/NCSA
// Open Source License
//
// Copyright (c) 2003-2010 University of Illinois at Urbana-Champaign.
// All rights reserved.
//
// Developed by:
//
// LLVM Team
//
// University of Illinois at Urbana-Champaign
//
// http://llvm.org
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal with
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
// of the Software, and to permit persons to whom the Software is furnished to do
// so, subject to the following conditions:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimers.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimers in the
// documentation and/or other materials provided with the distribution.
//
// * Neither the names of the LLVM Team, University of Illinois at
// Urbana-Champaign, nor the names of its contributors may be used to
// endorse or promote products derived from this Software without specific
// prior written permission.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
// CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS WITH THE
// SOFTWARE.
//
//===----------------------------------------------------------------------===//
//
// This file implements the SmallVector class.
//
//===----------------------------------------------------------------------===//

#include "OgreStableHeaders.h"

#include "OgreSmallVector.h"

namespace Ogre {

/// grow_pod - This is an implementation of the grow() method which only works
/// on POD-like datatypes and is out of line to reduce code duplication.
void SmallVectorBase::grow_pod(size_t MinSizeInBytes, size_t TSize) {
	size_t CurSizeBytes = size_in_bytes();
  size_t NewCapacityInBytes = 2 * capacity_in_bytes() + TSize; // Always grow.
	if (NewCapacityInBytes < MinSizeInBytes)
		NewCapacityInBytes = MinSizeInBytes;

  void *NewElts;
  if (this->isSmall()) {
    NewElts = malloc(NewCapacityInBytes);

	// Copy the elements over.  No need to run dtors on PODs.
	memcpy(NewElts, this->BeginX, CurSizeBytes);
  } else {
    // If this wasn't grown from the inline copy, grow the allocated space.
    NewElts = realloc(this->BeginX, NewCapacityInBytes);
  }

	this->EndX = (char*)NewElts+CurSizeBytes;
	this->BeginX = NewElts;
	this->CapacityX = (char*)this->BeginX + NewCapacityInBytes;
}

}<|endoftext|>


<commit_before>//
//  OpenGL.h
//  Clock Signal
//
//  Created by Thomas Harte on 07/02/2016.
//  Copyright © 2016 Thomas Harte. All rights reserved.
//

#ifndef OpenGL_h
#define OpenGL_h

// TODO: figure out correct include paths for other platforms.
#include <OpenGL/OpenGL.h>
#include <OpenGL/gl3.h>

#endif /* OpenGL_h */
<commit_msg>Wrapped this up as explicitly only the Mac thing to do.<commit_after>//
//  OpenGL.h
//  Clock Signal
//
//  Created by Thomas Harte on 07/02/2016.
//  Copyright © 2016 Thomas Harte. All rights reserved.
//

#ifndef OpenGL_h
#define OpenGL_h

// TODO: figure out correct include paths for other platforms.
#ifdef __APPLE__
	#if TARGET_OS_IPHONE
	#else
		#include <OpenGL/OpenGL.h>
		#include <OpenGL/gl3.h>
	#endif
#endif

#endif /* OpenGL_h */
<|endoftext|>


<commit_before>/* Copyright 2013-2016 CyberTech Labs Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License. */

#include "trikKitInterpreterCommon/trikKitInterpreterPluginBase.h"

#include <QtWidgets/QApplication>
#include <QtWidgets/QLineEdit>

#include <twoDModel/engine/twoDModelEngineFacade.h>
#include <qrkernel/settingsManager.h>
#include <qrkernel/settingsListener.h>

#include <qrgui/textEditor/qscintillaTextEdit.h>
#include <qrgui/textEditor/languageInfo.h>

using namespace trik;
using namespace qReal;

const Id robotDiagramType = Id("RobotsMetamodel", "RobotsDiagram", "RobotsDiagramNode");
const Id subprogramDiagramType = Id("RobotsMetamodel", "RobotsDiagram", "SubprogramDiagram");

TrikKitInterpreterPluginBase::TrikKitInterpreterPluginBase() :
	mStart(tr("Start QTS"), nullptr), mStop(tr("Stop QTS"), nullptr)
{
}

TrikKitInterpreterPluginBase::~TrikKitInterpreterPluginBase()
{
	if (mOwnsAdditionalPreferences) {
		delete mAdditionalPreferences;
	}

	if (mOwnsBlocksFactory) {
		delete mBlocksFactory;
	}
}

void TrikKitInterpreterPluginBase::initKitInterpreterPluginBase
		(robotModel::TrikRobotModelBase * const realRobotModel
		, robotModel::twoD::TrikTwoDRobotModel * const twoDRobotModel
		, blocks::TrikBlocksFactoryBase * const blocksFactory
		)
{
	mRealRobotModel.reset(realRobotModel);
	mTwoDRobotModel.reset(twoDRobotModel);
	mBlocksFactory = blocksFactory;

	const auto modelEngine = new twoDModel::engine::TwoDModelEngineFacade(*mTwoDRobotModel);

	mTwoDRobotModel->setEngine(modelEngine->engine());
	mTwoDModel.reset(modelEngine);

	connectDevicesConfigurationProvider(devicesConfigurationProvider()); // ... =(

	mAdditionalPreferences = new TrikAdditionalPreferences({ mRealRobotModel->name() });

	mQtsInterpreter.reset(new TrikQtsInterpreter(mTwoDRobotModel));
}

void TrikKitInterpreterPluginBase::startJSInterpretation(const QString &code)
{
	emit codeInterpretationStarted(code);

	auto model = mTwoDRobotModel;
	model->stopRobot(); // testStop?
	const QString modelName = model->robotId();

	for (const kitBase::robotModel::PortInfo &port : model->configurablePorts()) {
		const kitBase::robotModel::DeviceInfo deviceInfo = currentConfiguration(modelName, port);
		model->configureDevice(port, deviceInfo);
	}

	model->applyConfiguration();

	qtsInterpreter()->init();

	qtsInterpreter()->setCurrentDir(mProjectManager->saveFilePath());
	qtsInterpreter()->setRunning(true);
	emit started();
	qtsInterpreter()->interpretScript(code);
}

void TrikKitInterpreterPluginBase::startJSInterpretation(const QString &code, const QString &inputs)
{
	// we are in exercise mode (maybe rename it later)
	emit codeInterpretationStarted(code);

	auto model = mTwoDRobotModel;
	model->stopRobot(); // testStop?
	const QString modelName = model->robotId();

	for (const kitBase::robotModel::PortInfo &port : model->configurablePorts()) {
		const kitBase::robotModel::DeviceInfo deviceInfo = currentConfiguration(modelName, port);
		model->configureDevice(port, deviceInfo);
	}

	model->applyConfiguration();

	qtsInterpreter()->init();

	qtsInterpreter()->setCurrentDir(mProjectManager->saveFilePath());
	qtsInterpreter()->setRunning(true);
	emit started();
	qtsInterpreter()->interpretScriptExercise(code, inputs);
}

TrikQtsInterpreter * TrikKitInterpreterPluginBase::qtsInterpreter() const
{
	return mQtsInterpreter.data();
}

void TrikKitInterpreterPluginBase::init(const kitBase::KitPluginConfigurator &configurer)
{
	connect(&configurer.eventsForKitPlugin()
			, &kitBase::EventsForKitPluginInterface::robotModelChanged
			, [this](const QString &modelName) { mCurrentlySelectedModelName = modelName; });

	qReal::gui::MainWindowInterpretersInterface &interpretersInterface
			= configurer.qRealConfigurator().mainWindowInterpretersInterface();

	mProjectManager = &configurer.qRealConfigurator().projectManager();

	mTwoDModel->init(configurer.eventsForKitPlugin()
			, configurer.qRealConfigurator().systemEvents()
			, configurer.qRealConfigurator().logicalModelApi()
			, configurer.qRealConfigurator().controller()
			, interpretersInterface
			, configurer.qRealConfigurator().mainWindowDockInterface()
			, configurer.qRealConfigurator().projectManager()
			, configurer.interpreterControl());

	mRealRobotModel->setErrorReporter(*interpretersInterface.errorReporter());
	mTwoDRobotModel->setErrorReporter(*interpretersInterface.errorReporter());

	mQtsInterpreter->setErrorReporter(*interpretersInterface.errorReporter());

	mMainWindow = &configurer.qRealConfigurator().mainWindowInterpretersInterface();

	mSystemEvents = &configurer.qRealConfigurator().systemEvents();

	/// @todo: refactor?
	mStart.setObjectName("runQts");
	mStart.setText(tr("Run program"));
	mStart.setIcon(QIcon(":/trik/qts/images/run.png"));

	mStop.setObjectName("stopQts");
	mStop.setText(tr("Stop robot"));
	mStop.setIcon(QIcon(":/trik/qts/images/stop.png"));

	mStop.setVisible(false);
	mStart.setVisible(false);

	connect(&configurer.eventsForKitPlugin()
			, &kitBase::EventsForKitPluginInterface::interpretCode
			, [this](const QString &code, const QString &inputs){
		if (mIsModelSelected) {
			startJSInterpretation(code, inputs);
		}
	});

	connect(&configurer.robotModelManager()
			, &kitBase::robotModel::RobotModelManagerInterface::robotModelChanged
			, [this](kitBase::robotModel::RobotModelInterface &model){
		mIsModelSelected = robotModels().contains(&model);
		/// @todo: would probably make sense to make the current opened tab info available globally somewhere
		bool isCodeTabOpen = dynamic_cast<qReal::text::QScintillaTextEdit *>(mMainWindow->currentTab()) != nullptr;
		/// @todo: bad, relies on the slot order, because of another @todo in actionManager (custom visibility logic)
		bool isQtsInterp = mQtsInterpreter->supportedRobotModelNames().contains(model.name());
		mStart.setVisible(mIsModelSelected && isCodeTabOpen && isQtsInterp);
		mStop.setVisible(false); // interpretation should always stop when switching models?
	});

	connect(&configurer.interpreterControl()
			, &kitBase::InterpreterControlInterface::stopAllInterpretation
			, this
			, [this](qReal::interpretation::StopReason) {
		if (mQtsInterpreter->isRunning()) {
			testStop();
		}
	});

	connect(&configurer.interpreterControl()
			, &kitBase::InterpreterControlInterface::startJsInterpretation
			, this
			, [this]() {
		if (!mQtsInterpreter->isRunning() && mIsModelSelected) { // temporary
			testStart();
		}
	});

	connect(&mStart, &QAction::triggered, this, &TrikKitInterpreterPluginBase::testStart);
	connect(&mStop, &QAction::triggered, this, &TrikKitInterpreterPluginBase::testStop);
	connect(mQtsInterpreter.data()
			, &TrikQtsInterpreter::completed
			, this
			, &TrikKitInterpreterPluginBase::testStop);
	// refactor?
	connect(this
			, &TrikKitInterpreterPluginBase::started
			, &configurer.eventsForKitPlugin()
			, &kitBase::EventsForKitPluginInterface::interpretationStarted
			);

	connect(this
			, &TrikKitInterpreterPluginBase::stopped
			, &configurer.eventsForKitPlugin()
			, &kitBase::EventsForKitPluginInterface::interpretationStopped
			);

//	connect(&configurer.qRealConfigurator().systemEvents(),
//			&kitBase::EventsForKitPluginInterface:)

	connect(&configurer.eventsForKitPlugin()
			, &kitBase::EventsForKitPluginInterface::interpretationStarted
			, [this](){ /// @todo
		const bool isQtsInt = mQtsInterpreter->isRunning();
		mStart.setEnabled(isQtsInt);
		mStop.setEnabled(isQtsInt);
	}
	);

	QObject::connect(
				this
				, &TrikKitInterpreterPluginBase::codeInterpretationStarted
				, &configurer.eventsForKitPlugin()
				, &kitBase::EventsForKitPluginInterface::codeInterpretationStarted
				);

	QObject::connect(
				&configurer.eventsForKitPlugin()
				, &kitBase::EventsForKitPluginInterface::interpretationStopped
				, [this](qReal::interpretation::StopReason reason){ /// @todo
		Q_UNUSED(reason);
		mStart.setEnabled(true);
		mStop.setEnabled(true);
	}
	);

	connect(mSystemEvents
			, &qReal::SystemEvents::activeTabChanged
			, this
			, &TrikKitInterpreterPluginBase::onTabChanged);

	connect(mAdditionalPreferences, &TrikAdditionalPreferences::settingsChanged
			, mRealRobotModel.data(), &robotModel::TrikRobotModelBase::rereadSettings);

	connect(mAdditionalPreferences, &TrikAdditionalPreferences::settingsChanged
			, mTwoDRobotModel.data(), &robotModel::twoD::TrikTwoDRobotModel::rereadSettings);
}

QList<kitBase::robotModel::RobotModelInterface *> TrikKitInterpreterPluginBase::robotModels()
{
	return {mRealRobotModel.data(), mTwoDRobotModel.data()};
}

kitBase::blocksBase::BlocksFactoryInterface *TrikKitInterpreterPluginBase::blocksFactoryFor(
		const kitBase::robotModel::RobotModelInterface *model)
{
	Q_UNUSED(model);

	mOwnsBlocksFactory = false;
	return mBlocksFactory;
}

kitBase::robotModel::RobotModelInterface *TrikKitInterpreterPluginBase::defaultRobotModel()
{
	return mTwoDRobotModel.data();
}

QList<kitBase::AdditionalPreferences *> TrikKitInterpreterPluginBase::settingsWidgets()
{
	mOwnsAdditionalPreferences = false;
	return {mAdditionalPreferences};
}

QWidget *TrikKitInterpreterPluginBase::quickPreferencesFor(const kitBase::robotModel::RobotModelInterface &model)
{
	return model.name().toLower().contains("twod")
			? nullptr
			: produceIpAddressConfigurer();
}

QList<qReal::ActionInfo> TrikKitInterpreterPluginBase::customActions()
{
	return { qReal::ActionInfo(&mStart, "interpreters", "tools"), qReal::ActionInfo(&mStop, "interpreters", "tools") };
}

QList<HotKeyActionInfo> TrikKitInterpreterPluginBase::hotKeyActions()
{
	return {};
}

QString TrikKitInterpreterPluginBase::defaultSettingsFile() const
{
	return ":/trikDefaultSettings.ini";
}

QIcon TrikKitInterpreterPluginBase::iconForFastSelector(
		const kitBase::robotModel::RobotModelInterface &robotModel) const
{
	return &robotModel == mRealRobotModel.data()
			? QIcon(":/icons/switch-real-trik.svg")
			: &robotModel == mTwoDRobotModel.data()
					? QIcon(":/icons/switch-2d.svg")
					: QIcon();
}

kitBase::DevicesConfigurationProvider *TrikKitInterpreterPluginBase::devicesConfigurationProvider()
{
	return &mTwoDModel->devicesConfigurationProvider();
}

QWidget *TrikKitInterpreterPluginBase::produceIpAddressConfigurer()
{
	QLineEdit * const quickPreferences = new QLineEdit;
	quickPreferences->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed);
	quickPreferences->setPlaceholderText(tr("Enter robot`s IP-address here..."));
	const auto updateQuickPreferences = [quickPreferences]() {
		const QString ip = qReal::SettingsManager::value("TrikTcpServer").toString();
		if (quickPreferences->text() != ip) {
			quickPreferences->setText(ip);
		}
	};

	updateQuickPreferences();
	connect(mAdditionalPreferences, &TrikAdditionalPreferences::settingsChanged, updateQuickPreferences);
	qReal::SettingsListener::listen("TrikTcpServer", updateQuickPreferences, this);
	connect(quickPreferences, &QLineEdit::textChanged, [](const QString &text) {
		qReal::SettingsManager::setValue("TrikTcpServer", text);
	});

	connect(this, &QObject::destroyed, [quickPreferences]() { delete quickPreferences; });
	return quickPreferences;
}

void TrikKitInterpreterPluginBase::testStart()
{
	mStop.setVisible(true);
	mStart.setVisible(false);
	/// todo: bad

	auto texttab = dynamic_cast<qReal::text::QScintillaTextEdit *>(mMainWindow->currentTab());
	auto isJS = [](const QString &ext){ return ext == "js" || ext == "qts"; };

	if (texttab && isJS(texttab->currentLanguage().extension)) {
		startJSInterpretation(texttab->text());
	} else {
		qDebug("wrong tab selected");
		mStop.setVisible(false);
		mStart.setVisible(true);
		/// todo: refactor the whole button shenanigans
	}
}

void TrikKitInterpreterPluginBase::testStop()
{
	mStop.setVisible(false);
	mStart.setVisible(true);

	qtsInterpreter()->abort();
	mTwoDRobotModel->stopRobot();
	emit stopped(qReal::interpretation::StopReason::userStop);
}

void TrikKitInterpreterPluginBase::onTabChanged(const TabInfo &info)
{
	if (!mIsModelSelected) {
		return;
	}
	const bool isCodeTab = info.type() == qReal::TabInfo::TabType::code;
	const bool isQtsInterp = mQtsInterpreter->supportedRobotModelNames().contains(mCurrentlySelectedModelName);

	if (isCodeTab) {
		auto texttab = dynamic_cast<qReal::text::QScintillaTextEdit *>(mMainWindow->currentTab());
		auto isJS = [](const QString &ext){ return ext == "js" || ext == "qts"; };
		bool enable = texttab && isJS(texttab->currentLanguage().extension) && isQtsInterp;
		mStart.setEnabled(enable);
		mStop.setEnabled(enable);
		//mStart.setVisible(enable);
	} else {
		mStart.setEnabled(false); // Should matter
		mStop.setEnabled(false);
	}
	if (mQtsInterpreter->isRunning()) {
		mStop.trigger(); // Should interpretation should always stops at the change of tabs or not?
	}
	mStart.setVisible(isCodeTab && isQtsInterp);
	mStop.setVisible(false);
}
<commit_msg>Implemented clearing js errors when interpretation starts.<commit_after>/* Copyright 2013-2016 CyberTech Labs Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License. */

#include "trikKitInterpreterCommon/trikKitInterpreterPluginBase.h"

#include <QtWidgets/QApplication>
#include <QtWidgets/QLineEdit>

#include <twoDModel/engine/twoDModelEngineFacade.h>
#include <qrkernel/settingsManager.h>
#include <qrkernel/settingsListener.h>

#include <qrgui/textEditor/qscintillaTextEdit.h>
#include <qrgui/textEditor/languageInfo.h>

using namespace trik;
using namespace qReal;

const Id robotDiagramType = Id("RobotsMetamodel", "RobotsDiagram", "RobotsDiagramNode");
const Id subprogramDiagramType = Id("RobotsMetamodel", "RobotsDiagram", "SubprogramDiagram");

TrikKitInterpreterPluginBase::TrikKitInterpreterPluginBase() :
	mStart(tr("Start QTS"), nullptr), mStop(tr("Stop QTS"), nullptr)
{
}

TrikKitInterpreterPluginBase::~TrikKitInterpreterPluginBase()
{
	if (mOwnsAdditionalPreferences) {
		delete mAdditionalPreferences;
	}

	if (mOwnsBlocksFactory) {
		delete mBlocksFactory;
	}
}

void TrikKitInterpreterPluginBase::initKitInterpreterPluginBase
		(robotModel::TrikRobotModelBase * const realRobotModel
		, robotModel::twoD::TrikTwoDRobotModel * const twoDRobotModel
		, blocks::TrikBlocksFactoryBase * const blocksFactory
		)
{
	mRealRobotModel.reset(realRobotModel);
	mTwoDRobotModel.reset(twoDRobotModel);
	mBlocksFactory = blocksFactory;

	const auto modelEngine = new twoDModel::engine::TwoDModelEngineFacade(*mTwoDRobotModel);

	mTwoDRobotModel->setEngine(modelEngine->engine());
	mTwoDModel.reset(modelEngine);

	connectDevicesConfigurationProvider(devicesConfigurationProvider()); // ... =(

	mAdditionalPreferences = new TrikAdditionalPreferences({ mRealRobotModel->name() });

	mQtsInterpreter.reset(new TrikQtsInterpreter(mTwoDRobotModel));
}

void TrikKitInterpreterPluginBase::startJSInterpretation(const QString &code)
{
	emit codeInterpretationStarted(code);

	auto model = mTwoDRobotModel;
	model->stopRobot(); // testStop?
	const QString modelName = model->robotId();

	for (const kitBase::robotModel::PortInfo &port : model->configurablePorts()) {
		const kitBase::robotModel::DeviceInfo deviceInfo = currentConfiguration(modelName, port);
		model->configureDevice(port, deviceInfo);
	}

	model->applyConfiguration();

	mMainWindow->errorReporter()->clear();
	qtsInterpreter()->init();

	qtsInterpreter()->setCurrentDir(mProjectManager->saveFilePath());
	qtsInterpreter()->setRunning(true);
	emit started();
	qtsInterpreter()->interpretScript(code);
}

void TrikKitInterpreterPluginBase::startJSInterpretation(const QString &code, const QString &inputs)
{
	// we are in exercise mode (maybe rename it later)
	emit codeInterpretationStarted(code);

	auto model = mTwoDRobotModel;
	model->stopRobot(); // testStop?
	const QString modelName = model->robotId();

	for (const kitBase::robotModel::PortInfo &port : model->configurablePorts()) {
		const kitBase::robotModel::DeviceInfo deviceInfo = currentConfiguration(modelName, port);
		model->configureDevice(port, deviceInfo);
	}

	model->applyConfiguration();

	mMainWindow->errorReporter()->clear();
	qtsInterpreter()->init();

	qtsInterpreter()->setCurrentDir(mProjectManager->saveFilePath());
	qtsInterpreter()->setRunning(true);
	emit started();
	qtsInterpreter()->interpretScriptExercise(code, inputs);
}

TrikQtsInterpreter * TrikKitInterpreterPluginBase::qtsInterpreter() const
{
	return mQtsInterpreter.data();
}

void TrikKitInterpreterPluginBase::init(const kitBase::KitPluginConfigurator &configurer)
{
	connect(&configurer.eventsForKitPlugin()
			, &kitBase::EventsForKitPluginInterface::robotModelChanged
			, [this](const QString &modelName) { mCurrentlySelectedModelName = modelName; });

	qReal::gui::MainWindowInterpretersInterface &interpretersInterface
			= configurer.qRealConfigurator().mainWindowInterpretersInterface();

	mProjectManager = &configurer.qRealConfigurator().projectManager();

	mTwoDModel->init(configurer.eventsForKitPlugin()
			, configurer.qRealConfigurator().systemEvents()
			, configurer.qRealConfigurator().logicalModelApi()
			, configurer.qRealConfigurator().controller()
			, interpretersInterface
			, configurer.qRealConfigurator().mainWindowDockInterface()
			, configurer.qRealConfigurator().projectManager()
			, configurer.interpreterControl());

	mRealRobotModel->setErrorReporter(*interpretersInterface.errorReporter());
	mTwoDRobotModel->setErrorReporter(*interpretersInterface.errorReporter());

	mQtsInterpreter->setErrorReporter(*interpretersInterface.errorReporter());

	mMainWindow = &configurer.qRealConfigurator().mainWindowInterpretersInterface();

	mSystemEvents = &configurer.qRealConfigurator().systemEvents();

	/// @todo: refactor?
	mStart.setObjectName("runQts");
	mStart.setText(tr("Run program"));
	mStart.setIcon(QIcon(":/trik/qts/images/run.png"));

	mStop.setObjectName("stopQts");
	mStop.setText(tr("Stop robot"));
	mStop.setIcon(QIcon(":/trik/qts/images/stop.png"));

	mStop.setVisible(false);
	mStart.setVisible(false);

	connect(&configurer.eventsForKitPlugin()
			, &kitBase::EventsForKitPluginInterface::interpretCode
			, [this](const QString &code, const QString &inputs){
		if (mIsModelSelected) {
			startJSInterpretation(code, inputs);
		}
	});

	connect(&configurer.robotModelManager()
			, &kitBase::robotModel::RobotModelManagerInterface::robotModelChanged
			, [this](kitBase::robotModel::RobotModelInterface &model){
		mIsModelSelected = robotModels().contains(&model);
		/// @todo: would probably make sense to make the current opened tab info available globally somewhere
		bool isCodeTabOpen = dynamic_cast<qReal::text::QScintillaTextEdit *>(mMainWindow->currentTab()) != nullptr;
		/// @todo: bad, relies on the slot order, because of another @todo in actionManager (custom visibility logic)
		bool isQtsInterp = mQtsInterpreter->supportedRobotModelNames().contains(model.name());
		mStart.setVisible(mIsModelSelected && isCodeTabOpen && isQtsInterp);
		mStop.setVisible(false); // interpretation should always stop when switching models?
	});

	connect(&configurer.interpreterControl()
			, &kitBase::InterpreterControlInterface::stopAllInterpretation
			, this
			, [this](qReal::interpretation::StopReason) {
		if (mQtsInterpreter->isRunning()) {
			testStop();
		}
	});

	connect(&configurer.interpreterControl()
			, &kitBase::InterpreterControlInterface::startJsInterpretation
			, this
			, [this]() {
		if (!mQtsInterpreter->isRunning() && mIsModelSelected) { // temporary
			testStart();
		}
	});

	connect(&mStart, &QAction::triggered, this, &TrikKitInterpreterPluginBase::testStart);
	connect(&mStop, &QAction::triggered, this, &TrikKitInterpreterPluginBase::testStop);
	connect(mQtsInterpreter.data()
			, &TrikQtsInterpreter::completed
			, this
			, &TrikKitInterpreterPluginBase::testStop);
	// refactor?
	connect(this
			, &TrikKitInterpreterPluginBase::started
			, &configurer.eventsForKitPlugin()
			, &kitBase::EventsForKitPluginInterface::interpretationStarted
			);

	connect(this
			, &TrikKitInterpreterPluginBase::stopped
			, &configurer.eventsForKitPlugin()
			, &kitBase::EventsForKitPluginInterface::interpretationStopped
			);

//	connect(&configurer.qRealConfigurator().systemEvents(),
//			&kitBase::EventsForKitPluginInterface:)

	connect(&configurer.eventsForKitPlugin()
			, &kitBase::EventsForKitPluginInterface::interpretationStarted
			, [this](){ /// @todo
		const bool isQtsInt = mQtsInterpreter->isRunning();
		mStart.setEnabled(isQtsInt);
		mStop.setEnabled(isQtsInt);
	}
	);

	QObject::connect(
				this
				, &TrikKitInterpreterPluginBase::codeInterpretationStarted
				, &configurer.eventsForKitPlugin()
				, &kitBase::EventsForKitPluginInterface::codeInterpretationStarted
				);

	QObject::connect(
				&configurer.eventsForKitPlugin()
				, &kitBase::EventsForKitPluginInterface::interpretationStopped
				, [this](qReal::interpretation::StopReason reason){ /// @todo
		Q_UNUSED(reason);
		mStart.setEnabled(true);
		mStop.setEnabled(true);
	}
	);

	connect(mSystemEvents
			, &qReal::SystemEvents::activeTabChanged
			, this
			, &TrikKitInterpreterPluginBase::onTabChanged);

	connect(mAdditionalPreferences, &TrikAdditionalPreferences::settingsChanged
			, mRealRobotModel.data(), &robotModel::TrikRobotModelBase::rereadSettings);

	connect(mAdditionalPreferences, &TrikAdditionalPreferences::settingsChanged
			, mTwoDRobotModel.data(), &robotModel::twoD::TrikTwoDRobotModel::rereadSettings);
}

QList<kitBase::robotModel::RobotModelInterface *> TrikKitInterpreterPluginBase::robotModels()
{
	return {mRealRobotModel.data(), mTwoDRobotModel.data()};
}

kitBase::blocksBase::BlocksFactoryInterface *TrikKitInterpreterPluginBase::blocksFactoryFor(
		const kitBase::robotModel::RobotModelInterface *model)
{
	Q_UNUSED(model);

	mOwnsBlocksFactory = false;
	return mBlocksFactory;
}

kitBase::robotModel::RobotModelInterface *TrikKitInterpreterPluginBase::defaultRobotModel()
{
	return mTwoDRobotModel.data();
}

QList<kitBase::AdditionalPreferences *> TrikKitInterpreterPluginBase::settingsWidgets()
{
	mOwnsAdditionalPreferences = false;
	return {mAdditionalPreferences};
}

QWidget *TrikKitInterpreterPluginBase::quickPreferencesFor(const kitBase::robotModel::RobotModelInterface &model)
{
	return model.name().toLower().contains("twod")
			? nullptr
			: produceIpAddressConfigurer();
}

QList<qReal::ActionInfo> TrikKitInterpreterPluginBase::customActions()
{
	return { qReal::ActionInfo(&mStart, "interpreters", "tools"), qReal::ActionInfo(&mStop, "interpreters", "tools") };
}

QList<HotKeyActionInfo> TrikKitInterpreterPluginBase::hotKeyActions()
{
	return {};
}

QString TrikKitInterpreterPluginBase::defaultSettingsFile() const
{
	return ":/trikDefaultSettings.ini";
}

QIcon TrikKitInterpreterPluginBase::iconForFastSelector(
		const kitBase::robotModel::RobotModelInterface &robotModel) const
{
	return &robotModel == mRealRobotModel.data()
			? QIcon(":/icons/switch-real-trik.svg")
			: &robotModel == mTwoDRobotModel.data()
					? QIcon(":/icons/switch-2d.svg")
					: QIcon();
}

kitBase::DevicesConfigurationProvider *TrikKitInterpreterPluginBase::devicesConfigurationProvider()
{
	return &mTwoDModel->devicesConfigurationProvider();
}

QWidget *TrikKitInterpreterPluginBase::produceIpAddressConfigurer()
{
	QLineEdit * const quickPreferences = new QLineEdit;
	quickPreferences->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed);
	quickPreferences->setPlaceholderText(tr("Enter robot`s IP-address here..."));
	const auto updateQuickPreferences = [quickPreferences]() {
		const QString ip = qReal::SettingsManager::value("TrikTcpServer").toString();
		if (quickPreferences->text() != ip) {
			quickPreferences->setText(ip);
		}
	};

	updateQuickPreferences();
	connect(mAdditionalPreferences, &TrikAdditionalPreferences::settingsChanged, updateQuickPreferences);
	qReal::SettingsListener::listen("TrikTcpServer", updateQuickPreferences, this);
	connect(quickPreferences, &QLineEdit::textChanged, [](const QString &text) {
		qReal::SettingsManager::setValue("TrikTcpServer", text);
	});

	connect(this, &QObject::destroyed, [quickPreferences]() { delete quickPreferences; });
	return quickPreferences;
}

void TrikKitInterpreterPluginBase::testStart()
{
	mStop.setVisible(true);
	mStart.setVisible(false);
	/// todo: bad

	auto texttab = dynamic_cast<qReal::text::QScintillaTextEdit *>(mMainWindow->currentTab());
	auto isJS = [](const QString &ext){ return ext == "js" || ext == "qts"; };

	if (texttab && isJS(texttab->currentLanguage().extension)) {
		startJSInterpretation(texttab->text());
	} else {
		qDebug("wrong tab selected");
		mStop.setVisible(false);
		mStart.setVisible(true);
		/// todo: refactor the whole button shenanigans
	}
}

void TrikKitInterpreterPluginBase::testStop()
{
	mStop.setVisible(false);
	mStart.setVisible(true);

	qtsInterpreter()->abort();
	mTwoDRobotModel->stopRobot();
	emit stopped(qReal::interpretation::StopReason::userStop);
}

void TrikKitInterpreterPluginBase::onTabChanged(const TabInfo &info)
{
	if (!mIsModelSelected) {
		return;
	}
	const bool isCodeTab = info.type() == qReal::TabInfo::TabType::code;
	const bool isQtsInterp = mQtsInterpreter->supportedRobotModelNames().contains(mCurrentlySelectedModelName);

	if (isCodeTab) {
		auto texttab = dynamic_cast<qReal::text::QScintillaTextEdit *>(mMainWindow->currentTab());
		auto isJS = [](const QString &ext){ return ext == "js" || ext == "qts"; };
		bool enable = texttab && isJS(texttab->currentLanguage().extension) && isQtsInterp;
		mStart.setEnabled(enable);
		mStop.setEnabled(enable);
		//mStart.setVisible(enable);
	} else {
		mStart.setEnabled(false); // Should matter
		mStop.setEnabled(false);
	}
	if (mQtsInterpreter->isRunning()) {
		mStop.trigger(); // Should interpretation should always stops at the change of tabs or not?
	}
	mStart.setVisible(isCodeTab && isQtsInterp);
	mStop.setVisible(false);
}
<|endoftext|>


<commit_before>#ifndef _SNARKFRONT_DSL_UTILITY_HPP_
#define _SNARKFRONT_DSL_UTILITY_HPP_

#include <array>
#include <cstdint>
#include <iostream>
#include <istream>
#include <ostream>
#include <vector>
#include "Alg.hpp"
#include "AST.hpp"
#include "BitwiseAST.hpp"
#include <Util.hpp> // snarklib

namespace snarkfront {

////////////////////////////////////////////////////////////////////////////////
// elliptic curve pairing
//

// check if string name is: BN128, Edwards
bool validPairingName(const std::string& name);

// returns true if "BN128"
bool pairingBN128(const std::string& name);

// returns true if "Edwards"
bool pairingEdwards(const std::string& name);

////////////////////////////////////////////////////////////////////////////////
// SHA-2
//

// check if: "1", "224", "256", "384", "512", "512_224", "512_256"
bool validSHA2Name(const std::string& shaBits);

// check if: 1, 224, 256, 384, 512
bool validSHA2Name(const std::size_t shaBits);

// returns true if "SHA256"
bool nameSHA256(const std::string& shaBits);

// returns true if "SHA512"
bool nameSHA512(const std::string& shaBits);

////////////////////////////////////////////////////////////////////////////////
// AES
//

// check if: 128, 192, 256
bool validAESName(const std::size_t aesBits);

////////////////////////////////////////////////////////////////////////////////
// powers of 2
//

template <typename ALG>
std::size_t sizeBits(const AST_Const<ALG>&) {
    typename AST_Const<ALG>::ValueType dummy;
    return sizeBits(dummy);
}

template <typename ALG>
std::size_t sizeBits(const AST_Var<ALG>&) {
    typename AST_Var<ALG>::ValueType dummy;
    return sizeBits(dummy);
}

////////////////////////////////////////////////////////////////////////////////
// serialize hash digests and preimages
//

#define DEFN_ARRAY_OUT(UINT)                                    \
template <std::size_t N>                                        \
std::ostream& operator<< (                                      \
    std::ostream& os,                                           \
    const std::array<UINT, N>& a)                               \
{                                                               \
    const char *ptr = reinterpret_cast<const char*>(a.data());  \
    if (snarklib::is_big_endian<int>()) {                       \
        for (std::size_t i = 0; i < N; ++i) {                   \
            for (int j = sizeof(UINT) - 1; j >= 0; --j) {       \
                os.put(ptr[i * sizeof(UINT) + j]);              \
            }                                                   \
        }                                                       \
    } else {                                                    \
        os.write(ptr, sizeof(a));                               \
    }                                                           \
    return os;                                                  \
}

DEFN_ARRAY_OUT(std::uint8_t)
DEFN_ARRAY_OUT(std::uint32_t)
DEFN_ARRAY_OUT(std::uint64_t)

#undef DEFN_ARRAY_OUT

#define DEFN_VECTOR_ARRAY_OUT(UINT)                     \
template <std::size_t N>                                \
std::ostream& operator<< (                              \
    std::ostream& os,                                   \
    const std::vector<std::array<UINT, N>>& a)          \
{                                                       \
    os << a.size() << ' ';                              \
    for (const auto& r : a)                             \
        os << r;                                        \
    return os;                                          \
}

DEFN_VECTOR_ARRAY_OUT(std::uint8_t)
DEFN_VECTOR_ARRAY_OUT(std::uint32_t)
DEFN_VECTOR_ARRAY_OUT(std::uint64_t)

#undef DEFN_VECTOR_ARRAY_OUT

#define DEFN_ARRAY_IN(UINT)                                     \
template <std::size_t N>                                        \
std::istream& operator>> (                                      \
    std::istream& is,                                           \
    std::array<UINT, N>& a)                                     \
{                                                               \
    char *ptr = reinterpret_cast<char*>(a.data());              \
    if (snarklib::is_big_endian<int>()) {                       \
        for (std::size_t i = 0; i < N; ++i) {                   \
            for (int j = sizeof(UINT) - 1; j >= 0; --j) {       \
                if (! is.get(ptr[i * sizeof(UINT) + j]))        \
                    return is;                                  \
            }                                                   \
        }                                                       \
    } else {                                                    \
        is.read(ptr, sizeof(a));                                \
    }                                                           \
    return is;                                                  \
}

DEFN_ARRAY_IN(std::uint8_t)
DEFN_ARRAY_IN(std::uint32_t)
DEFN_ARRAY_IN(std::uint64_t)

#undef DEFN_ARRAY_IN

#define DEFN_VECTOR_ARRAY_IN(UINT)              \
template <std::size_t N>                        \
std::istream& operator>> (                      \
    std::istream& is,                           \
    std::vector<std::array<UINT, N>>& a)        \
{                                               \
    std::size_t len = -1;                       \
    if (!(is >> len) || (-1 == len)) return is; \
    char c;                                     \
    if (!is.get(c) || (' ' != c)) return is;    \
    a.resize(len);                              \
    for (auto& r : a)                           \
        if (!(is >> r)) break;                  \
    return is;                                  \
}

DEFN_VECTOR_ARRAY_IN(std::uint8_t)
DEFN_VECTOR_ARRAY_IN(std::uint32_t)
DEFN_VECTOR_ARRAY_IN(std::uint64_t)

#undef DEFN_VECTOR_ARRAY_IN

////////////////////////////////////////////////////////////////////////////////
// lookup table for unsigned integer types
//

template <typename T, typename U, typename VAL, typename BITWISE>
class BitwiseLUT
{
public:
    template <std::size_t N>
    BitwiseLUT(const std::array<VAL, N>& table_elements)
        : m_value(table_elements.begin(),
                  table_elements.end())
    {}

    std::size_t size() const { return m_value.size(); }

    U operator[] (const T& x) const
    {
        const auto N = m_value.size();

        auto sum = BITWISE::_AND(BITWISE::_constant(m_value[0]),
                                 BITWISE::_CMPLMNT(BITWISE::_bitmask(0 != x)));

        for (std::size_t i = 1; i < N - 1; ++i) {
            sum = BITWISE::_ADDMOD(sum,
                                   BITWISE::_AND(
                                       BITWISE::_constant(m_value[i]),
                                       BITWISE::_CMPLMNT(BITWISE::_bitmask(i != x))));
        }

        return BITWISE::ADDMOD(sum,
                               BITWISE::_AND(
                                   BITWISE::_constant(m_value[N - 1]),
                                   BITWISE::_CMPLMNT(BITWISE::_bitmask((N-1) != x))));
    }

private:
    const std::vector<VAL> m_value;
};

template <typename FR> using
array_uint8 = BitwiseLUT<AST_Node<Alg_uint8<FR>>,
                         AST_Op<Alg_uint8<FR>>,
                         std::uint8_t,
                         BitwiseAST<Alg_uint8<FR>>>;

template <typename FR> using
array_uint32 = BitwiseLUT<AST_Node<Alg_uint32<FR>>,
                          AST_Op<Alg_uint32<FR>>,
                          std::uint32_t,
                          BitwiseAST<Alg_uint32<FR>>>;

template <typename FR> using
array_uint64 = BitwiseLUT<AST_Node<Alg_uint64<FR>>,
                          AST_Op<Alg_uint64<FR>>,
                          std::uint64_t,
                          BitwiseAST<Alg_uint64<FR>>>;

} // namespace snarkfront

#endif
<commit_msg>asciiHex()<commit_after>#ifndef _SNARKFRONT_DSL_UTILITY_HPP_
#define _SNARKFRONT_DSL_UTILITY_HPP_

#include <array>
#include <cstdint>
#include <iostream>
#include <istream>
#include <ostream>
#include <string>
#include <vector>

#include <snarklib/Util.hpp>

#include <snarkfront/Alg.hpp>
#include <snarkfront/AST.hpp>
#include <snarkfront/BitwiseAST.hpp>
#include <snarkfront/DSL_base.hpp>
#include <snarkfront/HexUtil.hpp>

namespace snarkfront {

////////////////////////////////////////////////////////////////////////////////
// elliptic curve pairing
//

// check if string name is: BN128, Edwards
bool validPairingName(const std::string& name);

// returns true if "BN128"
bool pairingBN128(const std::string& name);

// returns true if "Edwards"
bool pairingEdwards(const std::string& name);

////////////////////////////////////////////////////////////////////////////////
// SHA-2
//

// check if: "1", "224", "256", "384", "512", "512_224", "512_256"
bool validSHA2Name(const std::string& shaBits);

// check if: 1, 224, 256, 384, 512
bool validSHA2Name(const std::size_t shaBits);

// returns true if "SHA256"
bool nameSHA256(const std::string& shaBits);

// returns true if "SHA512"
bool nameSHA512(const std::string& shaBits);

////////////////////////////////////////////////////////////////////////////////
// AES
//

// check if: 128, 192, 256
bool validAESName(const std::size_t aesBits);

////////////////////////////////////////////////////////////////////////////////
// powers of 2
//

template <typename ALG>
std::size_t sizeBits(const AST_Const<ALG>&) {
    typename AST_Const<ALG>::ValueType dummy;
    return sizeBits(dummy);
}

template <typename ALG>
std::size_t sizeBits(const AST_Var<ALG>&) {
    typename AST_Var<ALG>::ValueType dummy;
    return sizeBits(dummy);
}

////////////////////////////////////////////////////////////////////////////////
// convert between hexadecimal ASCII and binary
//

#define DEFN_ASCII_HEX_ARRAY(BITS)                      \
template <typename FR, std::size_t N>                   \
std::string asciiHex(                                   \
    const std::array<uint ## BITS ## _x<FR>, N>& a,     \
    const bool space = false)                           \
{                                                       \
    std::array<uint ## BITS ## _t, N> tmp;              \
    for (std::size_t i = 0; i < N; ++i)                 \
        tmp[i] = a[i]->value();                         \
    return asciiHex(tmp, space);                        \
}

DEFN_ASCII_HEX_ARRAY(8)
DEFN_ASCII_HEX_ARRAY(32)
DEFN_ASCII_HEX_ARRAY(64)

#undef DEFN_ASCII_HEX_ARRAY

#define DEFN_ASCII_HEX_VECTOR(BITS)                 \
template <typename FR, std::size_t N>               \
std::string asciiHex(                               \
    const std::vector<uint ## BITS ## _x<FR>>& a,   \
    const bool space = false)                       \
{                                                   \
    std::vector<uint ## BITS ## _t> tmp;            \
    for (std::size_t i = 0; i < N; ++i)             \
        tmp[i] = a[i]->value();                     \
    return asciiHex(tmp, space);                    \
}

DEFN_ASCII_HEX_VECTOR(8)
DEFN_ASCII_HEX_VECTOR(32)
DEFN_ASCII_HEX_VECTOR(64)

#undef DEFN_ASCII_HEX_VECTOR

////////////////////////////////////////////////////////////////////////////////
// serialize hash digests and preimages
//

#define DEFN_ARRAY_OUT(UINT)                                    \
template <std::size_t N>                                        \
std::ostream& operator<< (                                      \
    std::ostream& os,                                           \
    const std::array<UINT, N>& a)                               \
{                                                               \
    const char *ptr = reinterpret_cast<const char*>(a.data());  \
    if (snarklib::is_big_endian<int>()) {                       \
        for (std::size_t i = 0; i < N; ++i) {                   \
            for (int j = sizeof(UINT) - 1; j >= 0; --j) {       \
                os.put(ptr[i * sizeof(UINT) + j]);              \
            }                                                   \
        }                                                       \
    } else {                                                    \
        os.write(ptr, sizeof(a));                               \
    }                                                           \
    return os;                                                  \
}

DEFN_ARRAY_OUT(std::uint8_t)
DEFN_ARRAY_OUT(std::uint32_t)
DEFN_ARRAY_OUT(std::uint64_t)

#undef DEFN_ARRAY_OUT

#define DEFN_VECTOR_ARRAY_OUT(UINT)                     \
template <std::size_t N>                                \
std::ostream& operator<< (                              \
    std::ostream& os,                                   \
    const std::vector<std::array<UINT, N>>& a)          \
{                                                       \
    os << a.size() << ' ';                              \
    for (const auto& r : a)                             \
        os << r;                                        \
    return os;                                          \
}

DEFN_VECTOR_ARRAY_OUT(std::uint8_t)
DEFN_VECTOR_ARRAY_OUT(std::uint32_t)
DEFN_VECTOR_ARRAY_OUT(std::uint64_t)

#undef DEFN_VECTOR_ARRAY_OUT

#define DEFN_ARRAY_IN(UINT)                                     \
template <std::size_t N>                                        \
std::istream& operator>> (                                      \
    std::istream& is,                                           \
    std::array<UINT, N>& a)                                     \
{                                                               \
    char *ptr = reinterpret_cast<char*>(a.data());              \
    if (snarklib::is_big_endian<int>()) {                       \
        for (std::size_t i = 0; i < N; ++i) {                   \
            for (int j = sizeof(UINT) - 1; j >= 0; --j) {       \
                if (! is.get(ptr[i * sizeof(UINT) + j]))        \
                    return is;                                  \
            }                                                   \
        }                                                       \
    } else {                                                    \
        is.read(ptr, sizeof(a));                                \
    }                                                           \
    return is;                                                  \
}

DEFN_ARRAY_IN(std::uint8_t)
DEFN_ARRAY_IN(std::uint32_t)
DEFN_ARRAY_IN(std::uint64_t)

#undef DEFN_ARRAY_IN

#define DEFN_VECTOR_ARRAY_IN(UINT)              \
template <std::size_t N>                        \
std::istream& operator>> (                      \
    std::istream& is,                           \
    std::vector<std::array<UINT, N>>& a)        \
{                                               \
    std::size_t len = -1;                       \
    if (!(is >> len) || (-1 == len)) return is; \
    char c;                                     \
    if (!is.get(c) || (' ' != c)) return is;    \
    a.resize(len);                              \
    for (auto& r : a)                           \
        if (!(is >> r)) break;                  \
    return is;                                  \
}

DEFN_VECTOR_ARRAY_IN(std::uint8_t)
DEFN_VECTOR_ARRAY_IN(std::uint32_t)
DEFN_VECTOR_ARRAY_IN(std::uint64_t)

#undef DEFN_VECTOR_ARRAY_IN

////////////////////////////////////////////////////////////////////////////////
// lookup table for unsigned integer types
//

template <typename T, typename U, typename VAL, typename BITWISE>
class BitwiseLUT
{
public:
    template <std::size_t N>
    BitwiseLUT(const std::array<VAL, N>& table_elements)
        : m_value(table_elements.begin(),
                  table_elements.end())
    {}

    std::size_t size() const { return m_value.size(); }

    U operator[] (const T& x) const
    {
        const auto N = m_value.size();

        auto sum = BITWISE::_AND(BITWISE::_constant(m_value[0]),
                                 BITWISE::_CMPLMNT(BITWISE::_bitmask(0 != x)));

        for (std::size_t i = 1; i < N - 1; ++i) {
            sum = BITWISE::_ADDMOD(sum,
                                   BITWISE::_AND(
                                       BITWISE::_constant(m_value[i]),
                                       BITWISE::_CMPLMNT(BITWISE::_bitmask(i != x))));
        }

        return BITWISE::ADDMOD(sum,
                               BITWISE::_AND(
                                   BITWISE::_constant(m_value[N - 1]),
                                   BITWISE::_CMPLMNT(BITWISE::_bitmask((N-1) != x))));
    }

private:
    const std::vector<VAL> m_value;
};

template <typename FR> using
array_uint8 = BitwiseLUT<AST_Node<Alg_uint8<FR>>,
                         AST_Op<Alg_uint8<FR>>,
                         std::uint8_t,
                         BitwiseAST<Alg_uint8<FR>>>;

template <typename FR> using
array_uint32 = BitwiseLUT<AST_Node<Alg_uint32<FR>>,
                          AST_Op<Alg_uint32<FR>>,
                          std::uint32_t,
                          BitwiseAST<Alg_uint32<FR>>>;

template <typename FR> using
array_uint64 = BitwiseLUT<AST_Node<Alg_uint64<FR>>,
                          AST_Op<Alg_uint64<FR>>,
                          std::uint64_t,
                          BitwiseAST<Alg_uint64<FR>>>;

} // namespace snarkfront

#endif
<|endoftext|>


<commit_before>// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.

#include "fieldupdate.h"
#include <vespa/document/base/exceptions.h>
#include <vespa/document/fieldvalue/document.h>
#include <vespa/document/datatype/documenttype.h>
#include <vespa/vespalib/objects/nbostream.h>
#include <ostream>

namespace document {

using vespalib::nbostream;

FieldUpdate::FieldUpdate(const Field& field)
    : _field(field),
      _updates()
{
}

namespace {

int readInt(nbostream & stream) {
    int tmp;
    stream >> tmp;
    return tmp;
}

}

FieldUpdate::FieldUpdate(const DocumentTypeRepo& repo, const DataType & type, nbostream & stream)
    : _field(type.getField(readInt(stream))),
      _updates()
{
    int numUpdates = readInt(stream);
    _updates.reserve(numUpdates);
    const DataType& dataType = _field.getDataType();
    for(int i(0); i < numUpdates; i++) {
        _updates.emplace_back(ValueUpdate::createInstance(repo, dataType, stream));
    }
}

FieldUpdate::~FieldUpdate() = default;

bool
FieldUpdate::operator==(const FieldUpdate& other) const
{
    if (_field != other._field) return false;
    if (_updates.size() != other._updates.size()) return false;
    for (uint32_t i=0, n=_updates.size(); i<n; ++i) {
        if (*_updates[i] != *other._updates[i]) return false;
    }
    return true;
}

FieldUpdate&
FieldUpdate::addUpdate(std::unique_ptr<ValueUpdate> update) & {
    update->checkCompatibility(_field); // May throw exception.
    _updates.push_back(std::move(update));
    return *this;
}

FieldUpdate&&
FieldUpdate::addUpdate(std::unique_ptr<ValueUpdate> update) && {
    update->checkCompatibility(_field); // May throw exception.
    _updates.push_back(std::move(update));
    return std::move(*this);
}

void
FieldUpdate::printXml(XmlOutputStream& xos) const
{
    for(const auto & update : _updates) {
        update->printXml(xos);
    }
}

// Apply this field update to the given document.
void
FieldUpdate::applyTo(Document& doc) const
{
    const DataType& datatype = _field.getDataType();
    FieldValue::UP value = doc.getValue(_field);

    for (const auto & update : _updates) {
        if ( ! value) {
            // Avoid passing a null pointer to a value update.
            value = datatype.createFieldValue();
        }
        if (!update->applyTo(*value)) {
            value.reset();
        }
    }

    if (value) {
        doc.setFieldValue(_field, std::move(value));
    } else {
        doc.remove(_field);
    }
}

// Print this field update as a human readable string.
void
FieldUpdate::print(std::ostream& out, bool verbose, const std::string& indent) const
{
    out << "FieldUpdate(" << _field.toString(verbose);
    for(const auto & update : _updates) {
        out << "\n" << indent << "  ";
        update->print(out, verbose, indent + "  ");
    }
    if (_updates.size() > 0) {
        out << "\n" << indent;
    }
    out << ")";
}

// Deserialize this field update from the given buffer.
void
FieldUpdate::deserialize(const DocumentTypeRepo& repo, const DocumentType& docType, nbostream& stream)
{
    int fieldId = readInt(stream);
    _field = docType.getField(fieldId);
    const DataType& dataType = _field.getDataType();

    int numUpdates = readInt(stream);
    _updates.clear();
    _updates.resize(numUpdates);
    for(int i = 0; i < numUpdates; i++) {
        _updates[i].reset(ValueUpdate::createInstance(repo, dataType, stream).release());
    }
}

}  // namespace document
<commit_msg>Avoid code duplication.<commit_after>// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.

#include "fieldupdate.h"
#include <vespa/document/base/exceptions.h>
#include <vespa/document/fieldvalue/document.h>
#include <vespa/document/datatype/documenttype.h>
#include <vespa/vespalib/objects/nbostream.h>
#include <ostream>

namespace document {

using vespalib::nbostream;

FieldUpdate::FieldUpdate(const Field& field)
    : _field(field),
      _updates()
{
}

namespace {

int readInt(nbostream & stream) {
    int tmp;
    stream >> tmp;
    return tmp;
}

}

FieldUpdate::FieldUpdate(const DocumentTypeRepo& repo, const DataType & type, nbostream & stream)
    : _field(type.getField(readInt(stream))),
      _updates()
{
    int numUpdates = readInt(stream);
    _updates.reserve(numUpdates);
    const DataType& dataType = _field.getDataType();
    for(int i(0); i < numUpdates; i++) {
        _updates.emplace_back(ValueUpdate::createInstance(repo, dataType, stream));
    }
}

FieldUpdate::~FieldUpdate() = default;

bool
FieldUpdate::operator==(const FieldUpdate& other) const
{
    if (_field != other._field) return false;
    if (_updates.size() != other._updates.size()) return false;
    for (uint32_t i=0, n=_updates.size(); i<n; ++i) {
        if (*_updates[i] != *other._updates[i]) return false;
    }
    return true;
}

FieldUpdate&
FieldUpdate::addUpdate(std::unique_ptr<ValueUpdate> update) & {
    update->checkCompatibility(_field); // May throw exception.
    _updates.push_back(std::move(update));
    return *this;
}

FieldUpdate&&
FieldUpdate::addUpdate(std::unique_ptr<ValueUpdate> update) && {
    addUpdate(std::move(update));
    return std::move(*this);
}

void
FieldUpdate::printXml(XmlOutputStream& xos) const
{
    for(const auto & update : _updates) {
        update->printXml(xos);
    }
}

// Apply this field update to the given document.
void
FieldUpdate::applyTo(Document& doc) const
{
    const DataType& datatype = _field.getDataType();
    FieldValue::UP value = doc.getValue(_field);

    for (const auto & update : _updates) {
        if ( ! value) {
            // Avoid passing a null pointer to a value update.
            value = datatype.createFieldValue();
        }
        if (!update->applyTo(*value)) {
            value.reset();
        }
    }

    if (value) {
        doc.setFieldValue(_field, std::move(value));
    } else {
        doc.remove(_field);
    }
}

// Print this field update as a human readable string.
void
FieldUpdate::print(std::ostream& out, bool verbose, const std::string& indent) const
{
    out << "FieldUpdate(" << _field.toString(verbose);
    for(const auto & update : _updates) {
        out << "\n" << indent << "  ";
        update->print(out, verbose, indent + "  ");
    }
    if (_updates.size() > 0) {
        out << "\n" << indent;
    }
    out << ")";
}

// Deserialize this field update from the given buffer.
void
FieldUpdate::deserialize(const DocumentTypeRepo& repo, const DocumentType& docType, nbostream& stream)
{
    int fieldId = readInt(stream);
    _field = docType.getField(fieldId);
    const DataType& dataType = _field.getDataType();

    int numUpdates = readInt(stream);
    _updates.clear();
    _updates.resize(numUpdates);
    for(int i = 0; i < numUpdates; i++) {
        _updates[i].reset(ValueUpdate::createInstance(repo, dataType, stream).release());
    }
}

}  // namespace document
<|endoftext|>