<commit_before>#include "client.h"
#include "server.h"
#include "bdPlatformLog.h"
#include "command.h"
#include "qframe.h"

using namespace CMD;

/********************
 *    CONSTRUCTOR   *
 ********************/
Client::Client(QTcpSocket *socket, QObject *parent) : QObject(parent)
{
    m_socket = socket;
    m_state = 0;
    QObject::connect(m_socket, SIGNAL(disconnected()), this, SLOT(onDisconnection()));
    QObject::connect(m_socket, SIGNAL(disconnected()), this, SLOT(deleteLater()));
    QObject::connect(m_socket, SIGNAL(readyRead()), this, SLOT(onDataReady()));
}

/********************
 *    DESTRUCTOR    *
 ********************/
Client::~Client()
{
    delete m_socket;
    bdPlatformLog::bdLogMessage(_DEBUG, "debug/", "client", __FILE__, __PRETTY_FUNCTION__, __LINE__, "Client has been destroyed !");
}

/********************
 *      SLOTS       *
 ********************/
void Client::onDisconnection()
{
    Server* s = Server::Instance();
    s->delClient(this);
}

void Client::onDataReady()
{
    QString data = QString::fromUtf8(this->getSocket()->readAll());
    quint8 codeCmd = QFrame::getCmdCode(data), ret_val;

    bdPlatformLog::bdLogMessage(_DEBUG, "debug/", "client", __FILE__, __PRETTY_FUNCTION__, __LINE__, "Frame size : %u ", QFrame::getFrameSize(data));
    bdPlatformLog::bdLogMessage(_DEBUG, "debug/", "client", __FILE__, __PRETTY_FUNCTION__, __LINE__, "Command ID : %u", QFrame::getCmdId(data));
    bdPlatformLog::bdLogMessage(_DEBUG, "debug/", "client", __FILE__, __PRETTY_FUNCTION__, __LINE__, "Command code : %u", QFrame::getCmdCode(data));

    switch(codeCmd){
    case NICK_CMD:
        nickCommand cmd(this, QFrame::getArg(data, 0, 0));
        quint8 ret_val = cmd.execute();
        if(ret_val == 0 )
            bdPlatformLog::bdLogMessage(_DEBUG, "debug/", "client", __FILE__, __PRETTY_FUNCTION__, __LINE__, "Nickname has been changed successfully !!! ");
        break;
    }

  // This part has been commented to compile and run properly
/*
    switch(codeCmd)
    {
        case NICK_CMD:
        {
            nickCommand cmd(this, QFrame::getArg(data, 0, 0));
            ret_val = cmd.execute();
            if(ret_val == 0)
                bdPlatformLog::bdLogMessage(_DEBUG, "debug/", "client", __FILE__, __PRETTY_FUNCTION__, __LINE__, "Nickname has been changed successfully !!! ");
            break;
        }
        case CLMSGCL_CMD:
        {
            pmCommand cmd(this, QFrame::getArg(data, 0, 0), QFrame::getArg(data, 1));
            ret_val = cmd.execute();
            if(ret_val == 0)
                bdPlatformLog::bdLogMessage(_DEBUG, "debug/", "client", __FILE__, __PRETTY_FUNCTION__, __LINE__, "Successfully sent private message!");
            break;
        }
        case CLMSGCH_CMD:
        {
            chCommand cmd(this, QFrame::getArg(data, 0, 0), QFrame::getArg(data, 1));
            ret_val = cmd.execute();
            if(ret_val == 0)
                bdPlatformLog::bdLogMessage(_DEBUG, "debug/", "client", __FILE__, __PRETTY_FUNCTION__, __LINE__, "Successfully sent message to the channel!");
            break;
        }
        case JOIN_CMD:
        {
            joinCommand cmd(this, QFrame::getArg(data, 0, 0));
            ret_val = cmd.execute();
            if(ret_val == 0)
                bdPlatformLog::bdLogMessage(_DEBUG, "debug/", "client", __FILE__, __PRETTY_FUNCTION__, __LINE__, "Successfully joined channel!");
            if(ret_val == 1)
                bdPlatformLog::bdLogMessage(_DEBUG, "debug/", "client", __FILE__, __PRETTY_FUNCTION__, __LINE__, "Successfully created channel!");
            break;
        }
        case LEAVE_CMD:
        {
            leaveCommand cmd(this, QFrame::getArg(data, 0, 0));
            ret_val = cmd.execute();
            if(ret_val == 0)
                bdPlatformLog::bdLogMessage(_DEBUG, "debug/", "client", __FILE__, __PRETTY_FUNCTION__, __LINE__, "Successfully left channel!");
            break;
        }
        case LIST_CMD:
        {
            listCommand cmd(this, QFrame::getArg(data, 0, 0));
            ret_val = cmd.execute(); //This operation never fails
            break;
        }
        case TOPIC_CMD:
        {
            topicCommand cmd(this, QFrame::getArg(data, 0, 0), QFrame::getArg(data, 1));
            ret_val = cmd.execute();
            if (ret_val == 0)
                bdPlatformLog::bdLogMessage(_DEBUG, "debug/", "client", __FILE__, __PRETTY_FUNCTION__, __LINE__, "Successfully modified topic!");
               break;
        }
        case WHOG_CMD:
        {
            whoGCommand cmd(this, QFrame::getArg(data, 0, 0));
            ret_val = cmd.execute(); //This command should never fail
            break;
        }
        case WHOC_CMD:
        {
            whoCCommand cmd(this, QFrame::getArg(data, 0, 0));
            ret_val = cmd.execute(); //This command should never fail
            break;
        }
        default:
        {
            bdPlatformLog::bdLogMessage(_WARNING, "warn/", "client", __FILE__, __PRETTY_FUNCTION__, __LINE__, "Received unknown command ident %u.", codeCmd);
            break;
        }
    }
 */
}

/********************
 *      GETTERS     *
 ********************/
QTcpSocket* Client::getSocket(void) const
{
    return m_socket;
}

QString Client::getNickname(void) const
{
    return m_nickname;
}

bool Client::getState(void) const
{
    return m_state;
}

/********************
 *      SETTERS     *
 ********************/
void Client::setNickname( QString& nickname )
{
    m_nickname = nickname;
}

void Client::setSocket(QTcpSocket *socket)
{
     m_socket = socket;
}

void Client::setState(bool state)
{
    m_state = state;
}
<commit_msg>In the client the modifications have mostly focused on onDataReady() slot.<commit_after>#include "client.h"
#include "server.h"
#include "bdPlatformLog.h"
#include "command.h"
#include "frame.h"
#include <iostream>

//using namespace CMD;

/********************
 *    CONSTRUCTOR   *
 ********************/
Client::Client(QTcpSocket *socket, QObject *parent) : QObject(parent)
{
    m_socket = socket;
    m_state = 0;
    QObject::connect(m_socket, SIGNAL(disconnected()), this, SLOT(onDisconnection()));
    QObject::connect(m_socket, SIGNAL(disconnected()), this, SLOT(deleteLater()));
    QObject::connect(m_socket, SIGNAL(readyRead()), this, SLOT(onDataReady()));
}

/********************
 *    DESTRUCTOR    *
 ********************/
Client::~Client()
{
    delete m_socket;
    bdPlatformLog::bdLogMessage(_DEBUG, "debug/", "client", __FILE__, __PRETTY_FUNCTION__, __LINE__, "Client has been destroyed !");
}

/********************
 *      SLOTS       *
 ********************/
void Client::onDisconnection()
{
    Server* s = Server::Instance();
    s->delClient(this);
}

void Client::onDataReady()
{

    QByteArray data = this->getSocket()->readAll();

    Frame frame = (data);

    frame.debug();

    quint8 ret_val = 0;

    Command* command = Command::getCommand(this, frame);

    if(command == NULL)
        return;

    ret_val = command->verify();

    if(ret_val == ERROR::esuccess)
        ret_val = command->execute();

    QByteArray response = Frame::getReadyToSendFrame("", frame.getId(), ret_val);
    this->getSocket()->write(response);

}

/********************
 *      GETTERS     *
 ********************/
QTcpSocket* Client::getSocket(void) const
{
    return m_socket;
}

QString Client::getNickname(void) const
{
    return m_nickname;
}

bool Client::getState(void) const
{
    return m_state;
}

/********************
 *      SETTERS     *
 ********************/
void Client::setNickname( QString& nickname )
{
    m_nickname = nickname;
}

void Client::setSocket(QTcpSocket *socket)
{
     m_socket = socket;
}

void Client::setState(bool state)
{
    m_state = state;
}
<|endoftext|>


<commit_before>#include "plot_settings_view2.hpp"
#include "../plot/line_plot.hpp"
#include "../plot/heat_map.hpp"
#include "../plot/scatter_plot_1d.hpp"
#include "../plot/scatter_plot_2d.hpp"

#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QFormLayout>
#include <QListWidgetItem>
#include <QLabel>

namespace datavis {

PlotSettingsView::PlotSettingsView(const DataSetInfo & info, QWidget *parent):
    QWidget(parent)
{
    auto layout = new QVBoxLayout(this);

    m_type = new QComboBox(this);
    m_type->addItem("Line");
    m_type->addItem("Heat Map");
    m_type->addItem("Scatter 1D");
    m_type->addItem("Scatter 2D");
    layout->addWidget(m_type);

    m_settings.push_back(new LinePlotSettings(info));
    m_settings.push_back(new HeatMapPlotSettings(info));
    m_settings.push_back(new ScatterPlot1dSettings(info));
    m_settings.push_back(new ScatterPlot2dSettings(info));

    m_settings_stack = new QStackedLayout;
    for (auto widget : m_settings)
    {
        m_settings_stack->addWidget(widget);
    }
    layout->addLayout(m_settings_stack);

    connect(m_type, SIGNAL(currentIndexChanged(int)),
            m_settings_stack, SLOT(setCurrentIndex(int)));
}

Plot * PlotSettingsView::makePlot(const DataSetPtr & dataset)
{
    auto settings = m_settings[m_type->currentIndex()];
    return settings->makePlot(dataset);
}

PlotSettings::PlotSettings(const DataSetInfo & info, QWidget * parent):
    QWidget(parent),
    m_info(info)
{
}

void PlotSettings::fillDimensionsAndAttributes(QComboBox * box)
{
    fillDimensions(box);
    fillAttributes(box);
}

void PlotSettings::fillDimensions(QComboBox * box)
{
    for(int i = 0; i < m_info.dimensions.size(); ++i)
    {
        string name = m_info.dimensions[i].name;
        if (name.empty())
            name = "Dimension " + to_string(i);
        cerr << "Adding dim " << name << endl;
        box->addItem(QString::fromStdString(name));
    }
}

void PlotSettings::fillAttributes(QComboBox * box)
{
    for (int i = 0; i < m_info.attributes.size(); ++i)
    {
        string name = m_info.attributes[i].name;
        if (name.empty())
            name = "Attribute " + to_string(i);
        cerr << "Adding att " << name << endl;
        box->addItem(QString::fromStdString(name));
    }
}

LinePlotSettings::LinePlotSettings(const DataSetInfo & info, QWidget * parent):
    PlotSettings(info, parent)
{
    auto form = new QFormLayout(this);

    m_dimension = new QComboBox;
    fillDimensions(m_dimension);

    form->addRow("Dimension:", m_dimension);
}

Plot * LinePlotSettings::makePlot(const DataSetPtr & dataset)
{
    auto plot = new LinePlot;
    plot->setDataSet(dataset, m_dimension->currentIndex());
    return plot;
}

HeatMapPlotSettings::HeatMapPlotSettings(const DataSetInfo & info, QWidget * parent):
    PlotSettings(info, parent)
{
    auto form = new QFormLayout(this);

    m_x_dim = new QComboBox;
    m_y_dim = new QComboBox;

    m_y_dim->setModel(m_x_dim->model());

    fillDimensions(m_x_dim);

    form->addRow(new QLabel("X:"), m_x_dim);
    form->addRow(new QLabel("Y:"), m_y_dim);

    m_x_dim->setCurrentIndex(0);
    m_y_dim->setCurrentIndex(1);
}

Plot * HeatMapPlotSettings::makePlot(const DataSetPtr & dataset)
{
    int x = m_x_dim->currentIndex();
    int y = m_y_dim->currentIndex();
    if (x < 0 || y < 0)
        return nullptr;

    auto plot = new HeatMap;
    plot->setDataSet(dataset, { x, y });
    return plot;
}

ScatterPlot1dSettings::ScatterPlot1dSettings(const DataSetInfo & info, QWidget * parent):
    PlotSettings(info, parent)
{
    auto form = new QFormLayout(this);

    m_orientation = new QComboBox;
    m_orientation->addItem("Horizontal");
    m_orientation->addItem("Vertical");

    m_attribute = new QComboBox;
    fillAttributes(m_attribute);

    form->addRow("Orientation:", m_orientation);
    form->addRow("Attribute:", m_attribute);
}

Plot * ScatterPlot1dSettings::makePlot(const DataSetPtr & dataset)
{
    auto plot = new ScatterPlot1d;
    auto orientation = m_orientation->currentIndex() == 0 ? ScatterPlot1d::Horizontal : ScatterPlot1d::Vertical;
    plot->setData(dataset, m_attribute->currentIndex(), orientation);
    return plot;
}

ScatterPlot2dSettings::ScatterPlot2dSettings(const DataSetInfo & info, QWidget * parent):
    PlotSettings(info, parent)
{
    auto form = new QFormLayout(this);

    m_x_source = new QComboBox;
    m_y_source = new QComboBox;
    m_y_source->setModel(m_x_source->model());
    m_dots = new QCheckBox;
    m_line = new QCheckBox;

    fillAttributes(m_x_source);

    form->addRow(new QLabel("X:"), m_x_source);
    form->addRow(new QLabel("Y:"), m_y_source);
    form->addRow(new QLabel("Dots:"), m_dots);
    form->addRow(new QLabel("Line:"), m_line);

    m_x_source->setCurrentIndex(0);
    m_y_source->setCurrentIndex(1);
    m_dots->setChecked(true);
}

Plot * ScatterPlot2dSettings::makePlot(const DataSetPtr & dataset)
{
    auto plot = new ScatterPlot2d();
    int x = m_x_source->currentIndex() + dataset->dimensionCount();
    int y = m_y_source->currentIndex() + dataset->dimensionCount();
    plot->setData(dataset, x, y);
    plot->setShowDot(m_dots->isChecked());
    plot->setShowLine(m_line->isChecked());
    return plot;
}

}
<commit_msg>Fix plot settings view<commit_after>#include "plot_settings_view2.hpp"
#include "../plot/line_plot.hpp"
#include "../plot/heat_map.hpp"
#include "../plot/scatter_plot_1d.hpp"
#include "../plot/scatter_plot_2d.hpp"

#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QFormLayout>
#include <QListWidgetItem>
#include <QLabel>

namespace datavis {

PlotSettingsView::PlotSettingsView(const DataSetInfo & info, QWidget *parent):
    QWidget(parent)
{
    auto layout = new QVBoxLayout(this);

    m_type = new QComboBox(this);
    m_type->addItem("Line");
    m_type->addItem("Heat Map");
    m_type->addItem("Scatter 1D");
    m_type->addItem("Scatter 2D");
    layout->addWidget(m_type);

    m_settings.push_back(new LinePlotSettings(info));
    m_settings.push_back(new HeatMapPlotSettings(info));
    m_settings.push_back(new ScatterPlot1dSettings(info));
    m_settings.push_back(new ScatterPlot2dSettings(info));

    m_settings_stack = new QStackedLayout;
    for (auto widget : m_settings)
    {
        m_settings_stack->addWidget(widget);
    }
    layout->addLayout(m_settings_stack);

    connect(m_type, SIGNAL(currentIndexChanged(int)),
            m_settings_stack, SLOT(setCurrentIndex(int)));
}

Plot * PlotSettingsView::makePlot(const DataSetPtr & dataset)
{
    auto settings = m_settings[m_type->currentIndex()];
    return settings->makePlot(dataset);
}

PlotSettings::PlotSettings(const DataSetInfo & info, QWidget * parent):
    QWidget(parent),
    m_info(info)
{
}

void PlotSettings::fillDimensionsAndAttributes(QComboBox * box)
{
    fillDimensions(box);
    fillAttributes(box);
}

void PlotSettings::fillDimensions(QComboBox * box)
{
    for(int i = 0; i < m_info.dimensions.size(); ++i)
    {
        string name = m_info.dimensions[i].name;
        if (name.empty())
            name = "Dimension " + to_string(i);
        cerr << "Adding dim " << name << endl;
        box->addItem(QString::fromStdString(name));
    }
}

void PlotSettings::fillAttributes(QComboBox * box)
{
    for (int i = 0; i < m_info.attributes.size(); ++i)
    {
        string name = m_info.attributes[i].name;
        if (name.empty())
            name = "Attribute " + to_string(i);
        cerr << "Adding att " << name << endl;
        box->addItem(QString::fromStdString(name));
    }
}

LinePlotSettings::LinePlotSettings(const DataSetInfo & info, QWidget * parent):
    PlotSettings(info, parent)
{
    auto form = new QFormLayout(this);

    m_dimension = new QComboBox;
    fillDimensions(m_dimension);

    form->addRow("Dimension:", m_dimension);
}

Plot * LinePlotSettings::makePlot(const DataSetPtr & dataset)
{
    int dim = m_dimension->currentIndex();
    if (dim < 0)
        return nullptr;

    auto plot = new LinePlot;
    plot->setDataSet(dataset, m_dimension->currentIndex());
    return plot;
}

HeatMapPlotSettings::HeatMapPlotSettings(const DataSetInfo & info, QWidget * parent):
    PlotSettings(info, parent)
{
    auto form = new QFormLayout(this);

    m_x_dim = new QComboBox;
    m_y_dim = new QComboBox;

    m_y_dim->setModel(m_x_dim->model());

    fillDimensions(m_x_dim);

    form->addRow(new QLabel("X:"), m_x_dim);
    form->addRow(new QLabel("Y:"), m_y_dim);

    m_x_dim->setCurrentIndex(0);
    m_y_dim->setCurrentIndex(1);
}

Plot * HeatMapPlotSettings::makePlot(const DataSetPtr & dataset)
{
    int x = m_x_dim->currentIndex();
    int y = m_y_dim->currentIndex();
    if (x < 0 || y < 0)
        return nullptr;

    auto plot = new HeatMap;
    plot->setDataSet(dataset, { x, y });
    return plot;
}

ScatterPlot1dSettings::ScatterPlot1dSettings(const DataSetInfo & info, QWidget * parent):
    PlotSettings(info, parent)
{
    auto form = new QFormLayout(this);

    m_orientation = new QComboBox;
    m_orientation->addItem("Horizontal");
    m_orientation->addItem("Vertical");

    m_attribute = new QComboBox;
    fillAttributes(m_attribute);

    form->addRow("Orientation:", m_orientation);
    form->addRow("Attribute:", m_attribute);
}

Plot * ScatterPlot1dSettings::makePlot(const DataSetPtr & dataset)
{
    auto orientation = m_orientation->currentIndex() == 0 ? ScatterPlot1d::Horizontal : ScatterPlot1d::Vertical;
    int attribute = m_attribute->currentIndex();
    if (attribute < 0)
        return nullptr;

    auto plot = new ScatterPlot1d;
    plot->setData(dataset, attribute, orientation);
    return plot;
}

ScatterPlot2dSettings::ScatterPlot2dSettings(const DataSetInfo & info, QWidget * parent):
    PlotSettings(info, parent)
{
    auto form = new QFormLayout(this);

    m_x_source = new QComboBox;
    m_y_source = new QComboBox;
    m_y_source->setModel(m_x_source->model());
    m_dots = new QCheckBox;
    m_line = new QCheckBox;

    fillDimensionsAndAttributes(m_x_source);

    form->addRow(new QLabel("X:"), m_x_source);
    form->addRow(new QLabel("Y:"), m_y_source);
    form->addRow(new QLabel("Dots:"), m_dots);
    form->addRow(new QLabel("Line:"), m_line);

    int first_attribute = info.dimensionCount();

    if (info.attributes.size() >= 2)
    {
        m_x_source->setCurrentIndex(first_attribute);
        m_y_source->setCurrentIndex(first_attribute+1);
    }
    else
    {
        m_x_source->setCurrentIndex(0);
        m_y_source->setCurrentIndex(first_attribute);
    }

    m_dots->setChecked(true);
}

Plot * ScatterPlot2dSettings::makePlot(const DataSetPtr & dataset)
{
    int x = m_x_source->currentIndex();
    int y = m_y_source->currentIndex();
    if (x < 0 || y < 0)
        return nullptr;

    auto plot = new ScatterPlot2d();
    plot->setData(dataset, x, y);
    plot->setShowDot(m_dots->isChecked());
    plot->setShowLine(m_line->isChecked());
    return plot;
}

}
<|endoftext|>


<commit_before>/***************************Copyright-DO-NOT-REMOVE-THIS-LINE**
 * CONDOR Copyright Notice
 *
 * See LICENSE.TXT for additional notices and disclaimers.
 *
 * Copyright (c)1990-1998 CONDOR Team, Computer Sciences Department,
 * University of Wisconsin-Madison, Madison, WI.  All Rights Reserved.
 * No use of the CONDOR Software Program Source Code is authorized
 * without the express consent of the CONDOR Team.  For more information
 * contact: CONDOR Team, Attention: Professor Miron Livny,
 * 7367 Computer Sciences, 1210 W. Dayton St., Madison, WI 53706-1685,
 * (608) 262-0856 or miron@cs.wisc.edu.
 *
 * U.S. Government Rights Restrictions: Use, duplication, or disclosure
 * by the U.S. Government is subject to restrictions as set forth in
 * subparagraph (c)(1)(ii) of The Rights in Technical Data and Computer
 * Software clause at DFARS 252.227-7013 or subparagraphs (c)(1) and
 * (2) of Commercial Computer Software-Restricted Rights at 48 CFR
 * 52.227-19, as applicable, CONDOR Team, Attention: Professor Miron
 * Livny, 7367 Computer Sciences, 1210 W. Dayton St., Madison,
 * WI 53706-1685, (608) 262-0856 or miron@cs.wisc.edu.
****************************Copyright-DO-NOT-REMOVE-THIS-LINE**/
#include  <stdio.h>
#include "debug.h"
#include "condor_updown.h"
#include "condor_disk.h"

// these are C callable functions
extern	UpDown	upDown;

extern "C"
{
	void upDown_ClearUserInfo(void);
	void upDown_UpdateUserInfo(const char* , const int);
	int upDown_GetNoOfActiveUsers(void);
	int upDown_GetUserPriority(const char* , int* );
	void upDown_UpdatePriority(void);
	void upDown_SetParameters(const int , const int);
	void upDown_ReadFromFile(const char* );
	void upDown_WriteToFile(const char*);
	void upDown_Display(void);
	void dprintf(int, char*, char*, char*, char*, char*);
}

void upDown_ClearUserInfo(void)
{
	upDown.ClearUserInfo();
}
void upDown_UpdateUserInfo(const char* userName, const int status)
{
	upDown.UpdateUserInfo(userName, status) ;
}

int upDown_GetNoOfActiveUsers(void)
{
	return(upDown.GetNoOfActiveUsers());
}
int upDown_GetUserPriority(const char*  userName, int* status)
{
	int prio;
	prio = upDown.GetUserPriority(userName, status);
	return ( prio );
}
void upDown_UpdatePriority(void)	// updown algorithm
{
	upDown.UpdatePriority();	// updown algorithm
}
void upDown_SetParameters(const int stepSize, const int heavyUserPrio)
{
	upDown.SetParameters(stepSize, heavyUserPrio);
}

void upDown_ReadFromFile(const char* filename)
{
	File	ff(filename);   // create a File object
	ff >> upDown;		// read from filename
}

void upDown_WriteToFile(const char* filename)
{
	File	ff(filename);   // create a File object
	ff << upDown;		// read from filename
}

void upDown_Display(void)
{
	upDown.Display();
}

void UpDown::Display(void)
{
	int i;
	dprintf(D_UPDOWN,"---------timeout-------------\n",
						"","","","");
	dprintf(D_UPDOWN,"MaxUsers=%d ActiveUsers=%d Step=%d \n",
		(char *)maxUsers,(char *)activeUsers, (char *)step,"");
	for ( i=0; i < activeUsers; i++)
	{
		dprintf(D_UPDOWN,"Name:%s\tRun:%d Pend:%d Prio:%d\n",
			table[i].name,
			(char *)(table[i].jobRunning),
			(char *)(table[i].jobPending),
			(char *)(table[i].priority)
			);
	}
}
<commit_msg>Use condor_common.h<commit_after>/***************************Copyright-DO-NOT-REMOVE-THIS-LINE**
 * CONDOR Copyright Notice
 *
 * See LICENSE.TXT for additional notices and disclaimers.
 *
 * Copyright (c)1990-1998 CONDOR Team, Computer Sciences Department,
 * University of Wisconsin-Madison, Madison, WI.  All Rights Reserved.
 * No use of the CONDOR Software Program Source Code is authorized
 * without the express consent of the CONDOR Team.  For more information
 * contact: CONDOR Team, Attention: Professor Miron Livny,
 * 7367 Computer Sciences, 1210 W. Dayton St., Madison, WI 53706-1685,
 * (608) 262-0856 or miron@cs.wisc.edu.
 *
 * U.S. Government Rights Restrictions: Use, duplication, or disclosure
 * by the U.S. Government is subject to restrictions as set forth in
 * subparagraph (c)(1)(ii) of The Rights in Technical Data and Computer
 * Software clause at DFARS 252.227-7013 or subparagraphs (c)(1) and
 * (2) of Commercial Computer Software-Restricted Rights at 48 CFR
 * 52.227-19, as applicable, CONDOR Team, Attention: Professor Miron
 * Livny, 7367 Computer Sciences, 1210 W. Dayton St., Madison,
 * WI 53706-1685, (608) 262-0856 or miron@cs.wisc.edu.
****************************Copyright-DO-NOT-REMOVE-THIS-LINE**/

#include "condor_common.h"
#include "debug.h"
#include "condor_updown.h"
#include "condor_disk.h"

// these are C callable functions
extern	UpDown	upDown;

extern "C"
{
	void upDown_ClearUserInfo(void);
	void upDown_UpdateUserInfo(const char* , const int);
	int upDown_GetNoOfActiveUsers(void);
	int upDown_GetUserPriority(const char* , int* );
	void upDown_UpdatePriority(void);
	void upDown_SetParameters(const int , const int);
	void upDown_ReadFromFile(const char* );
	void upDown_WriteToFile(const char*);
	void upDown_Display(void);
	void dprintf(int, char*, char*, char*, char*, char*);
}

void upDown_ClearUserInfo(void)
{
	upDown.ClearUserInfo();
}
void upDown_UpdateUserInfo(const char* userName, const int status)
{
	upDown.UpdateUserInfo(userName, status) ;
}

int upDown_GetNoOfActiveUsers(void)
{
	return(upDown.GetNoOfActiveUsers());
}
int upDown_GetUserPriority(const char*  userName, int* status)
{
	int prio;
	prio = upDown.GetUserPriority(userName, status);
	return ( prio );
}
void upDown_UpdatePriority(void)	// updown algorithm
{
	upDown.UpdatePriority();	// updown algorithm
}
void upDown_SetParameters(const int stepSize, const int heavyUserPrio)
{
	upDown.SetParameters(stepSize, heavyUserPrio);
}

void upDown_ReadFromFile(const char* filename)
{
	File	ff(filename);   // create a File object
	ff >> upDown;		// read from filename
}

void upDown_WriteToFile(const char* filename)
{
	File	ff(filename);   // create a File object
	ff << upDown;		// read from filename
}

void upDown_Display(void)
{
	upDown.Display();
}

void UpDown::Display(void)
{
	int i;
	dprintf(D_UPDOWN,"---------timeout-------------\n",
						"","","","");
	dprintf(D_UPDOWN,"MaxUsers=%d ActiveUsers=%d Step=%d \n",
		(char *)maxUsers,(char *)activeUsers, (char *)step,"");
	for ( i=0; i < activeUsers; i++)
	{
		dprintf(D_UPDOWN,"Name:%s\tRun:%d Pend:%d Prio:%d\n",
			table[i].name,
			(char *)(table[i].jobRunning),
			(char *)(table[i].jobPending),
			(char *)(table[i].priority)
			);
	}
}
<|endoftext|>


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

#ifndef __SGI_STL_VECTOR
#include <vector>
#endif

enum SchXMLCellType
{
    SCH_CELL_TYPE_UNKNOWN,
    SCH_CELL_TYPE_FLOAT,
    SCH_CELL_TYPE_STRING
};

struct SchXMLCell
{
    rtl::OUString aString;
    double fValue;
    SchXMLCellType eType;

    SchXMLCell() : fValue( 0.0 ), eType( SCH_CELL_TYPE_UNKNOWN ) {}
};

struct SchXMLTable
{
    std::vector< std::vector< SchXMLCell > > aData;     /// an array of rows containing the table contents

    sal_Int32 nRowIndex;                                /// reflects the index of the row currently parsed
    sal_Int32 nColumnIndex;                             /// reflects the index of the column currently parsed
    sal_Int32 nMaxColumnIndex;                          /// the greatest number of columns detected

    sal_Int32 nNumberOfColsEstimate;                    /// parsing column-elements may yield an estimate

    SchXMLTable() : nRowIndex( -1 ),
                    nColumnIndex( -1 ),
                    nMaxColumnIndex( -1 ),
                    nNumberOfColsEstimate( 0 ) {}
};

// ----------------------------------------

struct SchNumericCellRangeAddress
{
    sal_Int32 nRow1, nRow2;
    sal_Int32 nCol1, nCol2;

    SchNumericCellRangeAddress() :
            nRow1( -1 ), nRow2( -1 ),
            nCol1( -1 ), nCol2( -1 )
        {}

    SchNumericCellRangeAddress( const SchNumericCellRangeAddress& aOther )
        {
            nRow1 = aOther.nRow1; nRow2 = aOther.nRow2;
            nCol1 = aOther.nCol1; nCol2 = aOther.nCol2;
        }
};

// ----------------------------------------

enum SchXMLAxisClass
{
    SCH_XML_AXIS_CATEGORY,
    SCH_XML_AXIS_DOMAIN,
    SCH_XML_AXIS_VALUE,
    SCH_XML_AXIS_SERIES,
    SCH_XML_AXIS_UNDEF
};

struct SchXMLAxis
{
    enum SchXMLAxisClass eClass;
    sal_Int8 nIndexInCategory;
    rtl::OUString aName;
    rtl::OUString aTitle;
    com::sun::star::awt::Point aPosition;

    SchXMLAxis() : eClass( SCH_XML_AXIS_UNDEF ), nIndexInCategory( 0 ) {}
};

#endif  // SCH_XML_TRANSPORTTYPES_HXX_
<commit_msg>INTEGRATION: CWS schoasis02 (1.3.432); FILE MERGED 2004/11/03 17:12:23 bm 1.3.432.1: #i36581# chart axis class -> dimension<commit_after>/*************************************************************************
 *
 *  $RCSfile: transporttypes.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: obo $ $Date: 2004-11-15 12:35:32 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/
#ifndef SCH_XML_TRANSPORTTYPES_HXX_
#define SCH_XML_TRANSPORTTYPES_HXX_

#ifndef __SGI_STL_VECTOR
#include <vector>
#endif

enum SchXMLCellType
{
    SCH_CELL_TYPE_UNKNOWN,
    SCH_CELL_TYPE_FLOAT,
    SCH_CELL_TYPE_STRING
};

struct SchXMLCell
{
    rtl::OUString aString;
    double fValue;
    SchXMLCellType eType;

    SchXMLCell() : fValue( 0.0 ), eType( SCH_CELL_TYPE_UNKNOWN ) {}
};

struct SchXMLTable
{
    std::vector< std::vector< SchXMLCell > > aData;     /// an array of rows containing the table contents

    sal_Int32 nRowIndex;                                /// reflects the index of the row currently parsed
    sal_Int32 nColumnIndex;                             /// reflects the index of the column currently parsed
    sal_Int32 nMaxColumnIndex;                          /// the greatest number of columns detected

    sal_Int32 nNumberOfColsEstimate;                    /// parsing column-elements may yield an estimate

    SchXMLTable() : nRowIndex( -1 ),
                    nColumnIndex( -1 ),
                    nMaxColumnIndex( -1 ),
                    nNumberOfColsEstimate( 0 ) {}
};

// ----------------------------------------

struct SchNumericCellRangeAddress
{
    sal_Int32 nRow1, nRow2;
    sal_Int32 nCol1, nCol2;

    SchNumericCellRangeAddress() :
            nRow1( -1 ), nRow2( -1 ),
            nCol1( -1 ), nCol2( -1 )
        {}

    SchNumericCellRangeAddress( const SchNumericCellRangeAddress& aOther )
        {
            nRow1 = aOther.nRow1; nRow2 = aOther.nRow2;
            nCol1 = aOther.nCol1; nCol2 = aOther.nCol2;
        }
};

// ----------------------------------------

enum SchXMLAxisClass
{
    SCH_XML_AXIS_X,
    SCH_XML_AXIS_Y,
    SCH_XML_AXIS_Z,
    SCH_XML_AXIS_UNDEF
};

struct SchXMLAxis
{
    enum SchXMLAxisClass eClass;
    sal_Int8 nIndexInCategory;
    rtl::OUString aName;
    rtl::OUString aTitle;
    com::sun::star::awt::Point aPosition;

    SchXMLAxis() : eClass( SCH_XML_AXIS_UNDEF ), nIndexInCategory( 0 ) {}
};

#endif  // SCH_XML_TRANSPORTTYPES_HXX_
<|endoftext|>


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

#ifndef __SGI_STL_VECTOR
#include <vector>
#endif

enum SchXMLCellType
{
    SCH_CELL_TYPE_UNKNOWN,
    SCH_CELL_TYPE_FLOAT,
    SCH_CELL_TYPE_STRING
};

struct SchXMLCell
{
    rtl::OUString aString;
    double fValue;
    SchXMLCellType eType;

    SchXMLCell() : fValue( 0.0 ), eType( SCH_CELL_TYPE_UNKNOWN ) {}
};

struct SchXMLTable
{
    std::vector< std::vector< SchXMLCell > > aData;     /// an array of rows containing the table contents

    sal_Int32 nRowIndex;                                /// reflects the index of the row currently parsed
    sal_Int32 nColumnIndex;                             /// reflects the index of the column currently parsed
    sal_Int32 nMaxColumnIndex;                          /// the greatest number of columns detected

    sal_Int32 nNumberOfColsEstimate;                    /// parsing column-elements may yield an estimate

    SchXMLTable() : nRowIndex( -1 ),
                    nColumnIndex( -1 ),
                    nMaxColumnIndex( -1 ),
                    nNumberOfColsEstimate( 0 ) {}
};

// ----------------------------------------

struct SchNumericCellRangeAddress
{
    sal_Int32 nRow1, nRow2;
    sal_Int32 nCol1, nCol2;

    SchNumericCellRangeAddress() :
            nRow1( -1 ), nRow2( -1 ),
            nCol1( -1 ), nCol2( -1 )
        {}

    SchNumericCellRangeAddress( const SchNumericCellRangeAddress& aOther )
        {
            nRow1 = aOther.nRow1; nRow2 = aOther.nRow2;
            nCol1 = aOther.nCol1; nCol2 = aOther.nCol2;
        }
};

// ----------------------------------------

enum SchXMLAxisClass
{
    SCH_XML_AXIS_X,
    SCH_XML_AXIS_Y,
    SCH_XML_AXIS_Z,
    SCH_XML_AXIS_UNDEF
};

struct SchXMLAxis
{
    enum SchXMLAxisClass eClass;
    sal_Int8 nIndexInCategory;
    rtl::OUString aName;
    rtl::OUString aTitle;
    com::sun::star::awt::Point aPosition;

    SchXMLAxis() : eClass( SCH_XML_AXIS_UNDEF ), nIndexInCategory( 0 ) {}
};

#endif  // SCH_XML_TRANSPORTTYPES_HXX_
<commit_msg>INTEGRATION: CWS sch10 (1.4.178); FILE MERGED 2005/06/30 09:50:18 bm 1.4.178.1: #i51307# set size/position and 3d scene properties only if necessary, i.e. when respective attributes have been read<commit_after>/*************************************************************************
 *
 *  $RCSfile: transporttypes.hxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: obo $ $Date: 2005-07-05 10:56:28 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/
#ifndef SCH_XML_TRANSPORTTYPES_HXX_
#define SCH_XML_TRANSPORTTYPES_HXX_

#ifndef __SGI_STL_VECTOR
#include <vector>
#endif

enum SchXMLCellType
{
    SCH_CELL_TYPE_UNKNOWN,
    SCH_CELL_TYPE_FLOAT,
    SCH_CELL_TYPE_STRING
};

struct SchXMLCell
{
    rtl::OUString aString;
    double fValue;
    SchXMLCellType eType;

    SchXMLCell() : fValue( 0.0 ), eType( SCH_CELL_TYPE_UNKNOWN ) {}
};

struct SchXMLTable
{
    std::vector< std::vector< SchXMLCell > > aData;     /// an array of rows containing the table contents

    sal_Int32 nRowIndex;                                /// reflects the index of the row currently parsed
    sal_Int32 nColumnIndex;                             /// reflects the index of the column currently parsed
    sal_Int32 nMaxColumnIndex;                          /// the greatest number of columns detected

    sal_Int32 nNumberOfColsEstimate;                    /// parsing column-elements may yield an estimate

    SchXMLTable() : nRowIndex( -1 ),
                    nColumnIndex( -1 ),
                    nMaxColumnIndex( -1 ),
                    nNumberOfColsEstimate( 0 ) {}
};

// ----------------------------------------

struct SchNumericCellRangeAddress
{
    sal_Int32 nRow1, nRow2;
    sal_Int32 nCol1, nCol2;

    SchNumericCellRangeAddress() :
            nRow1( -1 ), nRow2( -1 ),
            nCol1( -1 ), nCol2( -1 )
        {}

    SchNumericCellRangeAddress( const SchNumericCellRangeAddress& aOther )
        {
            nRow1 = aOther.nRow1; nRow2 = aOther.nRow2;
            nCol1 = aOther.nCol1; nCol2 = aOther.nCol2;
        }
};

// ----------------------------------------

enum SchXMLAxisClass
{
    SCH_XML_AXIS_X,
    SCH_XML_AXIS_Y,
    SCH_XML_AXIS_Z,
    SCH_XML_AXIS_UNDEF
};

struct SchXMLAxis
{
    enum SchXMLAxisClass eClass;
    sal_Int8 nIndexInCategory;
    rtl::OUString aName;
    rtl::OUString aTitle;
    com::sun::star::awt::Point aPosition;
    bool bTitleHasMoved;

    SchXMLAxis() : eClass( SCH_XML_AXIS_UNDEF ), nIndexInCategory( 0 ), bTitleHasMoved( false ) {}
};

#endif  // SCH_XML_TRANSPORTTYPES_HXX_
<|endoftext|>


<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2000, 2010 Oracle and/or its affiliates.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#define UNICODE
#define _UNICODE

#include <cstddef>

#define WIN32_LEAN_AND_MEAN
#if defined _MSC_VER
#pragma warning(push, 1)
#endif
#include <windows.h>
#include <shellapi.h>
#if defined _MSC_VER
#pragma warning(pop)
#endif

#include <tchar.h>

#include <malloc.h>
#include <string.h>
#include <stdlib.h>
#include <systools/win32/uwinapi.h>

#include "rtl/string.h"
#include <sal/macros.h>

#include "../../../source/inc/exithelper.hxx"
#include "../extendloaderenvironment.hxx"

#define PIPE_PREFIX                 TEXT("\\\\.\\pipe\\OSL_PIPE_")
#define PIPE_POSTFIX                TEXT("_SingleOfficeIPC_")
#define PIPE_TERMINATION_SEQUENCE   "InternalIPC::ProcessingDone"

BOOL WINAPI ConvertSidToStringSid( PSID pSid, LPTSTR* StringSid )
{
    PSID_IDENTIFIER_AUTHORITY psia;
    DWORD dwSubAuthorities;
    DWORD dwSidRev=SID_REVISION;
    DWORD dwCounter;
    DWORD dwSidSize;

    // Validate the binary SID.

    if(!IsValidSid(pSid)) return FALSE;

    // Get the identifier authority value from the SID.

    psia = GetSidIdentifierAuthority(pSid);

    // Get the number of subauthorities in the SID.

    dwSubAuthorities = *GetSidSubAuthorityCount(pSid);

    // Compute the buffer length.
    // S-SID_REVISION- + IdentifierAuthority- + subauthorities- + NULL

    dwSidSize=(15 + 12 + (12 * dwSubAuthorities) + 1) * sizeof(TCHAR);

    *StringSid = (LPTSTR)LocalAlloc( LMEM_FIXED, dwSidSize );

    // Add 'S' prefix and revision number to the string.

    dwSidSize=wsprintf(*StringSid, TEXT("S-%lu-"), dwSidRev );

    // Add a SID identifier authority to the string.

    if ( (psia->Value[0] != 0) || (psia->Value[1] != 0) )
    {
        dwSidSize+=wsprintf(*StringSid + lstrlen(*StringSid),
                    TEXT("0x%02hx%02hx%02hx%02hx%02hx%02hx"),
                    (USHORT)psia->Value[0],
                    (USHORT)psia->Value[1],
                    (USHORT)psia->Value[2],
                    (USHORT)psia->Value[3],
                    (USHORT)psia->Value[4],
                    (USHORT)psia->Value[5]);
    }
    else
    {
        dwSidSize+=wsprintf(*StringSid + lstrlen(*StringSid),
                    TEXT("%lu"),
                    (ULONG)(psia->Value[5]      )   +
                    (ULONG)(psia->Value[4] <<  8)   +
                    (ULONG)(psia->Value[3] << 16)   +
                    (ULONG)(psia->Value[2] << 24)   );
    }

    // Add SID subauthorities to the string.
    for (dwCounter=0 ; dwCounter < dwSubAuthorities ; dwCounter++)
    {
        dwSidSize+=wsprintf(*StringSid + dwSidSize, TEXT("-%lu"),
                    *GetSidSubAuthority(pSid, dwCounter) );
    }

    return TRUE;
}

//---------------------------------------------------------------------------

static LPTSTR   *GetCommandArgs( int *pArgc )
{
#ifdef UNICODE
    return CommandLineToArgvW( GetCommandLineW(), pArgc );
#else
    *pArgc = __argc;
    return __argv;
#endif
}

//---------------------------------------------------------------------------

namespace {

bool writeArgument(HANDLE pipe, char prefix, WCHAR const * argument) {
    CHAR szBuffer[4096];
    int n = WideCharToMultiByte(
        CP_UTF8, 0, argument, -1, szBuffer, sizeof (szBuffer), NULL, NULL);
    char b[1 + 2 * ((sizeof szBuffer) - 1)]; // hopefully does not overflow
    b[0] = prefix;
    char * p = b + 1;
    for (int i = 0; i < n - 1; ++i) { // cannot underflow (n >= 0)
        char c = szBuffer[i];
        switch (c) {
        case '\0':
            *p++ = '\\';
            *p++ = '0';
            break;
        case ',':
            *p++ = '\\';
            *p++ = ',';
            break;
        case '\\':
            *p++ = '\\';
            *p++ = '\\';
            break;
        default:
            *p++ = c;
            break;
        }
    }
    DWORD w;
    return WriteFile(pipe, b, p - b, &w, NULL);
}

}

#ifdef __MINGW32__
int WINAPI WinMain( HINSTANCE, HINSTANCE, LPSTR, int )
#else
int WINAPI _tWinMain( HINSTANCE, HINSTANCE, LPTSTR, int )
#endif
{
    TCHAR               szTargetFileName[MAX_PATH] = TEXT("");
    TCHAR               szIniDirectory[MAX_PATH];
    TCHAR               szPerfTuneIniFile[MAX_PATH] = TEXT("");
    STARTUPINFO         aStartupInfo;

    desktop_win32::extendLoaderEnvironment(szTargetFileName, szIniDirectory);

    ZeroMemory( &aStartupInfo, sizeof(aStartupInfo) );
    aStartupInfo.cb = sizeof(aStartupInfo);

    GetStartupInfo( &aStartupInfo );
    // Get image path with same name but with .bin extension

    TCHAR               szModuleFileName[MAX_PATH];

    GetModuleFileName( NULL, szModuleFileName, MAX_PATH );
    _TCHAR  *lpLastSlash = _tcsrchr( szModuleFileName, '\\' );
    if ( lpLastSlash )
    {
        size_t len = lpLastSlash - szModuleFileName + 1;
        _tcsncpy( szPerfTuneIniFile, szModuleFileName, len );
        _tcsncpy( szPerfTuneIniFile + len, _T("perftune.ini"), SAL_N_ELEMENTS(szPerfTuneIniFile) - len );
    }

    // Create process with same command line, environment and stdio handles which
    // are directed to the created pipes

    DWORD   dwExitCode = (DWORD)-1;

    BOOL    fSuccess = FALSE;
    LPTSTR  lpCommandLine = NULL;
    int argc = 0;
    LPTSTR * argv = NULL;
    bool bFirst = true;
    WCHAR cwd[MAX_PATH];
    DWORD cwdLen = GetCurrentDirectoryW(MAX_PATH, cwd);
    if (cwdLen >= MAX_PATH) {
        cwdLen = 0;
    }

    do
    {
        TCHAR   szKey[32];

        GetPrivateProfileString(
            TEXT("PerformanceTuning"),
            TEXT("FastPipeCommunication"),
            TEXT("0"),
            szKey,
            SAL_N_ELEMENTS(szKey),
            szPerfTuneIniFile
            );

        if ( 0 == _tcscmp( szKey, TEXT("1") ) )
        {
            HANDLE  hProcessToken;

            if ( OpenProcessToken( GetCurrentProcess(), TOKEN_QUERY, &hProcessToken ) )
            {
                TCHAR   szPipeName[4096];

                DWORD   dwTokenLength = 0;

                fSuccess = GetTokenInformation( hProcessToken, TokenUser, NULL, dwTokenLength, &dwTokenLength );

                PVOID   pTokenInfo = _alloca(dwTokenLength);
                fSuccess = GetTokenInformation( hProcessToken, TokenUser, pTokenInfo, dwTokenLength, &dwTokenLength );
                CloseHandle( hProcessToken );

                PSID pSid = ((PTOKEN_USER)pTokenInfo)->User.Sid;
                LPTSTR  szUserIdent = NULL;
                TCHAR   szSUPD[11] = TEXT("0");

                fSuccess = ConvertSidToStringSid( pSid, &szUserIdent );

                _tcsncpy( szPipeName, PIPE_PREFIX, SAL_N_ELEMENTS(szPipeName) );
                _tcsncat( szPipeName, szUserIdent, SAL_N_ELEMENTS(szPipeName) - _tcslen(szPipeName) - 1 );
                _tcsncat( szPipeName, PIPE_POSTFIX, SAL_N_ELEMENTS(szPipeName) - _tcslen(szPipeName) - 1 );
                _tcsncat( szPipeName, _ultot( SUPD, szSUPD, 10), SAL_N_ELEMENTS(szPipeName) - _tcslen(szPipeName) - 1 );

                LocalFree( szUserIdent );

                HANDLE  hPipe = CreateFile(
                                    szPipeName,
                                    GENERIC_READ|GENERIC_WRITE,
                                    FILE_SHARE_READ | FILE_SHARE_WRITE,
                                    NULL,
                                    OPEN_EXISTING,
                                    FILE_ATTRIBUTE_NORMAL,
                                    NULL);

                if ( INVALID_HANDLE_VALUE != hPipe )
                {
                    DWORD   dwBytesWritten;
                    int argc2 = 0;
                    LPWSTR  *argv2 = CommandLineToArgvW( GetCommandLine(), &argc2 );

                    fSuccess = WriteFile( hPipe, RTL_CONSTASCII_STRINGPARAM("InternalIPC::Arguments"), &dwBytesWritten, NULL );
                    if (fSuccess) {
                        if (cwdLen > 0) {
                            fSuccess = writeArgument(hPipe, '2', cwd);
                        } else {
                            fSuccess = WriteFile(
                                hPipe, RTL_CONSTASCII_STRINGPARAM("0"),
                                &dwBytesWritten, NULL);
                        }
                    }
                    for ( int argn = 1; fSuccess && argn < argc2; argn++ )
                    {
                        fSuccess = writeArgument(hPipe, ',', argv2[argn]);
                    }

                    if ( fSuccess )
                    {
                        fSuccess = WriteFile(  hPipe, "", 1, &dwBytesWritten, NULL );
                        if ( fSuccess )
                        {
                            DWORD   dwBytesRead = 0;
                            char    *pBuffer = (char *)_alloca( sizeof(PIPE_TERMINATION_SEQUENCE) );
                            fSuccess = ReadFile( hPipe, pBuffer, sizeof(PIPE_TERMINATION_SEQUENCE) - 1, &dwBytesRead, NULL );
                            if ( fSuccess )
                            {
                                pBuffer[dwBytesRead] = 0;
                                if ( 0 != strcmp( PIPE_TERMINATION_SEQUENCE, pBuffer ) )
                                    fSuccess = FALSE;
                            }
                        }
                    }

                    CloseHandle( hPipe );

                    return fSuccess ? 0 : -1;
                }

            }
        }

        if ( bFirst ) {
            argv = GetCommandArgs(&argc);
            std::size_t n = wcslen(argv[0]) + 2;
            for (int i = 1; i < argc; ++i) {
                n += wcslen(argv[i]) + 3;
            }
            n += MY_LENGTH(L" \"-env:OOO_CWD=2") + 4 * cwdLen +
                MY_LENGTH(L"\"") + 1;
                // 4 * cwdLen: each char preceded by backslash, each trailing
                // backslash doubled
            lpCommandLine = new WCHAR[n];
        }
        WCHAR * p = desktop_win32::commandLineAppend(
            lpCommandLine, MY_STRING(L"\""));
        p = desktop_win32::commandLineAppend(p, argv[0]);
        for (int i = 1; i < argc; ++i) {
            if (bFirst || ::desktop::ExitHelper::E_NORMAL_RESTART == dwExitCode || wcsncmp(argv[i], MY_STRING(L"-env:")) == 0) {
                p = desktop_win32::commandLineAppend(p, MY_STRING(L"\" \""));
                p = desktop_win32::commandLineAppend(p, argv[i]);
            }
        }

        p = desktop_win32::commandLineAppend(
            p, MY_STRING(L"\" \"-env:OOO_CWD="));
        if (cwdLen == 0) {
            p = desktop_win32::commandLineAppend(p, MY_STRING(L"0"));
        } else {
            p = desktop_win32::commandLineAppend(p, MY_STRING(L"2"));
            p = desktop_win32::commandLineAppendEncoded(p, cwd);
        }
        desktop_win32::commandLineAppend(p, MY_STRING(L"\""));
        bFirst = false;

        TCHAR   szParentProcessId[64]; // This is more than large enough for a 128 bit decimal value
        BOOL    bHeadlessMode( FALSE );

        {
            // Check command line arguments for "--headless" parameter. We only
            // set the environment variable "ATTACHED_PARENT_PROCESSID" for the headless
            // mode as self-destruction of the soffice.bin process can lead to
            // certain side-effects (log-off can result in data-loss, ".lock" is not deleted.
            // See 138244 for more information.
            int     argc2;
            LPTSTR  *argv2 = GetCommandArgs( &argc2 );

            if ( argc2 > 1 )
            {
                int n;

                for ( n = 1; n < argc2; n++ )
                {
                    if ( 0 == _tcsnicmp( argv2[n], _T("-headless"), 9 ) ||
                         0 == _tcsnicmp( argv2[n], _T("--headless"), 9 ) )
                    {
                        bHeadlessMode = TRUE;
                    }
                }
            }
        }

        if ( _ltot( (long)GetCurrentProcessId(),szParentProcessId, 10 ) && bHeadlessMode )
            SetEnvironmentVariable( TEXT("ATTACHED_PARENT_PROCESSID"), szParentProcessId );

        PROCESS_INFORMATION aProcessInfo;

        fSuccess = CreateProcess(
            szTargetFileName,
            lpCommandLine,
            NULL,
            NULL,
            TRUE,
            0,
            NULL,
            szIniDirectory,
            &aStartupInfo,
            &aProcessInfo );

        if ( fSuccess )
        {
            DWORD   dwWaitResult;

            do
            {
                // On Windows XP it seems as the desktop calls WaitForInputIdle after "OpenWidth" so we have to do so
                // as if we where processing any messages

                dwWaitResult = MsgWaitForMultipleObjects( 1, &aProcessInfo.hProcess, FALSE, INFINITE, QS_ALLEVENTS );

                if (  WAIT_OBJECT_0 + 1 == dwWaitResult )
                {
                    MSG msg;

                    PeekMessage( &msg, NULL, 0, 0, PM_REMOVE );
                }
            } while ( WAIT_OBJECT_0 + 1 == dwWaitResult );

            dwExitCode = 0;
            GetExitCodeProcess( aProcessInfo.hProcess, &dwExitCode );

            CloseHandle( aProcessInfo.hProcess );
            CloseHandle( aProcessInfo.hThread );
        }
    } while ( false );
    delete[] lpCommandLine;

    return fSuccess ? dwExitCode : -1;
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>fdo#43989: Revert "win32-dont-attempt-restart.diff: Don't attempt to restart OOo after crash"<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2000, 2010 Oracle and/or its affiliates.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#define UNICODE
#define _UNICODE

#include <cstddef>

#define WIN32_LEAN_AND_MEAN
#if defined _MSC_VER
#pragma warning(push, 1)
#endif
#include <windows.h>
#include <shellapi.h>
#if defined _MSC_VER
#pragma warning(pop)
#endif

#include <tchar.h>

#include <malloc.h>
#include <string.h>
#include <stdlib.h>
#include <systools/win32/uwinapi.h>

#include "rtl/string.h"
#include <sal/macros.h>

#include "../../../source/inc/exithelper.hxx"
#include "../extendloaderenvironment.hxx"

#define PIPE_PREFIX                 TEXT("\\\\.\\pipe\\OSL_PIPE_")
#define PIPE_POSTFIX                TEXT("_SingleOfficeIPC_")
#define PIPE_TERMINATION_SEQUENCE   "InternalIPC::ProcessingDone"

BOOL WINAPI ConvertSidToStringSid( PSID pSid, LPTSTR* StringSid )
{
    PSID_IDENTIFIER_AUTHORITY psia;
    DWORD dwSubAuthorities;
    DWORD dwSidRev=SID_REVISION;
    DWORD dwCounter;
    DWORD dwSidSize;

    // Validate the binary SID.

    if(!IsValidSid(pSid)) return FALSE;

    // Get the identifier authority value from the SID.

    psia = GetSidIdentifierAuthority(pSid);

    // Get the number of subauthorities in the SID.

    dwSubAuthorities = *GetSidSubAuthorityCount(pSid);

    // Compute the buffer length.
    // S-SID_REVISION- + IdentifierAuthority- + subauthorities- + NULL

    dwSidSize=(15 + 12 + (12 * dwSubAuthorities) + 1) * sizeof(TCHAR);

    *StringSid = (LPTSTR)LocalAlloc( LMEM_FIXED, dwSidSize );

    // Add 'S' prefix and revision number to the string.

    dwSidSize=wsprintf(*StringSid, TEXT("S-%lu-"), dwSidRev );

    // Add a SID identifier authority to the string.

    if ( (psia->Value[0] != 0) || (psia->Value[1] != 0) )
    {
        dwSidSize+=wsprintf(*StringSid + lstrlen(*StringSid),
                    TEXT("0x%02hx%02hx%02hx%02hx%02hx%02hx"),
                    (USHORT)psia->Value[0],
                    (USHORT)psia->Value[1],
                    (USHORT)psia->Value[2],
                    (USHORT)psia->Value[3],
                    (USHORT)psia->Value[4],
                    (USHORT)psia->Value[5]);
    }
    else
    {
        dwSidSize+=wsprintf(*StringSid + lstrlen(*StringSid),
                    TEXT("%lu"),
                    (ULONG)(psia->Value[5]      )   +
                    (ULONG)(psia->Value[4] <<  8)   +
                    (ULONG)(psia->Value[3] << 16)   +
                    (ULONG)(psia->Value[2] << 24)   );
    }

    // Add SID subauthorities to the string.
    for (dwCounter=0 ; dwCounter < dwSubAuthorities ; dwCounter++)
    {
        dwSidSize+=wsprintf(*StringSid + dwSidSize, TEXT("-%lu"),
                    *GetSidSubAuthority(pSid, dwCounter) );
    }

    return TRUE;
}

//---------------------------------------------------------------------------

static LPTSTR   *GetCommandArgs( int *pArgc )
{
#ifdef UNICODE
    return CommandLineToArgvW( GetCommandLineW(), pArgc );
#else
    *pArgc = __argc;
    return __argv;
#endif
}

//---------------------------------------------------------------------------

namespace {

bool writeArgument(HANDLE pipe, char prefix, WCHAR const * argument) {
    CHAR szBuffer[4096];
    int n = WideCharToMultiByte(
        CP_UTF8, 0, argument, -1, szBuffer, sizeof (szBuffer), NULL, NULL);
    char b[1 + 2 * ((sizeof szBuffer) - 1)]; // hopefully does not overflow
    b[0] = prefix;
    char * p = b + 1;
    for (int i = 0; i < n - 1; ++i) { // cannot underflow (n >= 0)
        char c = szBuffer[i];
        switch (c) {
        case '\0':
            *p++ = '\\';
            *p++ = '0';
            break;
        case ',':
            *p++ = '\\';
            *p++ = ',';
            break;
        case '\\':
            *p++ = '\\';
            *p++ = '\\';
            break;
        default:
            *p++ = c;
            break;
        }
    }
    DWORD w;
    return WriteFile(pipe, b, p - b, &w, NULL);
}

}

#ifdef __MINGW32__
int WINAPI WinMain( HINSTANCE, HINSTANCE, LPSTR, int )
#else
int WINAPI _tWinMain( HINSTANCE, HINSTANCE, LPTSTR, int )
#endif
{
    TCHAR               szTargetFileName[MAX_PATH] = TEXT("");
    TCHAR               szIniDirectory[MAX_PATH];
    TCHAR               szPerfTuneIniFile[MAX_PATH] = TEXT("");
    STARTUPINFO         aStartupInfo;

    desktop_win32::extendLoaderEnvironment(szTargetFileName, szIniDirectory);

    ZeroMemory( &aStartupInfo, sizeof(aStartupInfo) );
    aStartupInfo.cb = sizeof(aStartupInfo);

    GetStartupInfo( &aStartupInfo );
    // Get image path with same name but with .bin extension

    TCHAR               szModuleFileName[MAX_PATH];

    GetModuleFileName( NULL, szModuleFileName, MAX_PATH );
    _TCHAR  *lpLastSlash = _tcsrchr( szModuleFileName, '\\' );
    if ( lpLastSlash )
    {
        size_t len = lpLastSlash - szModuleFileName + 1;
        _tcsncpy( szPerfTuneIniFile, szModuleFileName, len );
        _tcsncpy( szPerfTuneIniFile + len, _T("perftune.ini"), SAL_N_ELEMENTS(szPerfTuneIniFile) - len );
    }

    // Create process with same command line, environment and stdio handles which
    // are directed to the created pipes

    DWORD   dwExitCode = (DWORD)-1;

    BOOL    fSuccess = FALSE;
    LPTSTR  lpCommandLine = NULL;
    int argc = 0;
    LPTSTR * argv = NULL;
    bool bFirst = true;
    WCHAR cwd[MAX_PATH];
    DWORD cwdLen = GetCurrentDirectoryW(MAX_PATH, cwd);
    if (cwdLen >= MAX_PATH) {
        cwdLen = 0;
    }

    do
    {
        TCHAR   szKey[32];

        GetPrivateProfileString(
            TEXT("PerformanceTuning"),
            TEXT("FastPipeCommunication"),
            TEXT("0"),
            szKey,
            SAL_N_ELEMENTS(szKey),
            szPerfTuneIniFile
            );

        if ( 0 == _tcscmp( szKey, TEXT("1") ) )
        {
            HANDLE  hProcessToken;

            if ( OpenProcessToken( GetCurrentProcess(), TOKEN_QUERY, &hProcessToken ) )
            {
                TCHAR   szPipeName[4096];

                DWORD   dwTokenLength = 0;

                fSuccess = GetTokenInformation( hProcessToken, TokenUser, NULL, dwTokenLength, &dwTokenLength );

                PVOID   pTokenInfo = _alloca(dwTokenLength);
                fSuccess = GetTokenInformation( hProcessToken, TokenUser, pTokenInfo, dwTokenLength, &dwTokenLength );
                CloseHandle( hProcessToken );

                PSID pSid = ((PTOKEN_USER)pTokenInfo)->User.Sid;
                LPTSTR  szUserIdent = NULL;
                TCHAR   szSUPD[11] = TEXT("0");

                fSuccess = ConvertSidToStringSid( pSid, &szUserIdent );

                _tcsncpy( szPipeName, PIPE_PREFIX, SAL_N_ELEMENTS(szPipeName) );
                _tcsncat( szPipeName, szUserIdent, SAL_N_ELEMENTS(szPipeName) - _tcslen(szPipeName) - 1 );
                _tcsncat( szPipeName, PIPE_POSTFIX, SAL_N_ELEMENTS(szPipeName) - _tcslen(szPipeName) - 1 );
                _tcsncat( szPipeName, _ultot( SUPD, szSUPD, 10), SAL_N_ELEMENTS(szPipeName) - _tcslen(szPipeName) - 1 );

                LocalFree( szUserIdent );

                HANDLE  hPipe = CreateFile(
                                    szPipeName,
                                    GENERIC_READ|GENERIC_WRITE,
                                    FILE_SHARE_READ | FILE_SHARE_WRITE,
                                    NULL,
                                    OPEN_EXISTING,
                                    FILE_ATTRIBUTE_NORMAL,
                                    NULL);

                if ( INVALID_HANDLE_VALUE != hPipe )
                {
                    DWORD   dwBytesWritten;
                    int argc2 = 0;
                    LPWSTR  *argv2 = CommandLineToArgvW( GetCommandLine(), &argc2 );

                    fSuccess = WriteFile( hPipe, RTL_CONSTASCII_STRINGPARAM("InternalIPC::Arguments"), &dwBytesWritten, NULL );
                    if (fSuccess) {
                        if (cwdLen > 0) {
                            fSuccess = writeArgument(hPipe, '2', cwd);
                        } else {
                            fSuccess = WriteFile(
                                hPipe, RTL_CONSTASCII_STRINGPARAM("0"),
                                &dwBytesWritten, NULL);
                        }
                    }
                    for ( int argn = 1; fSuccess && argn < argc2; argn++ )
                    {
                        fSuccess = writeArgument(hPipe, ',', argv2[argn]);
                    }

                    if ( fSuccess )
                    {
                        fSuccess = WriteFile(  hPipe, "", 1, &dwBytesWritten, NULL );
                        if ( fSuccess )
                        {
                            DWORD   dwBytesRead = 0;
                            char    *pBuffer = (char *)_alloca( sizeof(PIPE_TERMINATION_SEQUENCE) );
                            fSuccess = ReadFile( hPipe, pBuffer, sizeof(PIPE_TERMINATION_SEQUENCE) - 1, &dwBytesRead, NULL );
                            if ( fSuccess )
                            {
                                pBuffer[dwBytesRead] = 0;
                                if ( 0 != strcmp( PIPE_TERMINATION_SEQUENCE, pBuffer ) )
                                    fSuccess = FALSE;
                            }
                        }
                    }

                    CloseHandle( hPipe );

                    return fSuccess ? 0 : -1;
                }

            }
        }

        if ( bFirst ) {
            argv = GetCommandArgs(&argc);
            std::size_t n = wcslen(argv[0]) + 2;
            for (int i = 1; i < argc; ++i) {
                n += wcslen(argv[i]) + 3;
            }
            n += MY_LENGTH(L" \"-env:OOO_CWD=2") + 4 * cwdLen +
                MY_LENGTH(L"\"") + 1;
                // 4 * cwdLen: each char preceded by backslash, each trailing
                // backslash doubled
            lpCommandLine = new WCHAR[n];
        }
        WCHAR * p = desktop_win32::commandLineAppend(
            lpCommandLine, MY_STRING(L"\""));
        p = desktop_win32::commandLineAppend(p, argv[0]);
        for (int i = 1; i < argc; ++i) {
            if (bFirst || ::desktop::ExitHelper::E_NORMAL_RESTART == dwExitCode || wcsncmp(argv[i], MY_STRING(L"-env:")) == 0) {
                p = desktop_win32::commandLineAppend(p, MY_STRING(L"\" \""));
                p = desktop_win32::commandLineAppend(p, argv[i]);
            }
        }

        p = desktop_win32::commandLineAppend(
            p, MY_STRING(L"\" \"-env:OOO_CWD="));
        if (cwdLen == 0) {
            p = desktop_win32::commandLineAppend(p, MY_STRING(L"0"));
        } else {
            p = desktop_win32::commandLineAppend(p, MY_STRING(L"2"));
            p = desktop_win32::commandLineAppendEncoded(p, cwd);
        }
        desktop_win32::commandLineAppend(p, MY_STRING(L"\""));
        bFirst = false;

        TCHAR   szParentProcessId[64]; // This is more than large enough for a 128 bit decimal value
        BOOL    bHeadlessMode( FALSE );

        {
            // Check command line arguments for "--headless" parameter. We only
            // set the environment variable "ATTACHED_PARENT_PROCESSID" for the headless
            // mode as self-destruction of the soffice.bin process can lead to
            // certain side-effects (log-off can result in data-loss, ".lock" is not deleted.
            // See 138244 for more information.
            int     argc2;
            LPTSTR  *argv2 = GetCommandArgs( &argc2 );

            if ( argc2 > 1 )
            {
                int n;

                for ( n = 1; n < argc2; n++ )
                {
                    if ( 0 == _tcsnicmp( argv2[n], _T("-headless"), 9 ) ||
                         0 == _tcsnicmp( argv2[n], _T("--headless"), 9 ) )
                    {
                        bHeadlessMode = TRUE;
                    }
                }
            }
        }

        if ( _ltot( (long)GetCurrentProcessId(),szParentProcessId, 10 ) && bHeadlessMode )
            SetEnvironmentVariable( TEXT("ATTACHED_PARENT_PROCESSID"), szParentProcessId );

        PROCESS_INFORMATION aProcessInfo;

        fSuccess = CreateProcess(
            szTargetFileName,
            lpCommandLine,
            NULL,
            NULL,
            TRUE,
            0,
            NULL,
            szIniDirectory,
            &aStartupInfo,
            &aProcessInfo );

        if ( fSuccess )
        {
            DWORD   dwWaitResult;

            do
            {
                // On Windows XP it seems as the desktop calls WaitForInputIdle after "OpenWidth" so we have to do so
                // as if we where processing any messages

                dwWaitResult = MsgWaitForMultipleObjects( 1, &aProcessInfo.hProcess, FALSE, INFINITE, QS_ALLEVENTS );

                if (  WAIT_OBJECT_0 + 1 == dwWaitResult )
                {
                    MSG msg;

                    PeekMessage( &msg, NULL, 0, 0, PM_REMOVE );
                }
            } while ( WAIT_OBJECT_0 + 1 == dwWaitResult );

            dwExitCode = 0;
            GetExitCodeProcess( aProcessInfo.hProcess, &dwExitCode );

            CloseHandle( aProcessInfo.hProcess );
            CloseHandle( aProcessInfo.hThread );
        }
    } while ( fSuccess
              && ( ::desktop::ExitHelper::E_CRASH_WITH_RESTART == dwExitCode || ::desktop::ExitHelper::E_NORMAL_RESTART == dwExitCode ));
    delete[] lpCommandLine;

    return fSuccess ? dwExitCode : -1;
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>


<commit_before>#ifndef resplunk_util_Tuples_HeaderPlusPlus
#define resplunk_util_Tuples_HeaderPlusPlus

#include <cstdint>
#include <tuple>
#include <functional>
#include <type_traits>

namespace resplunk
{
	namespace util
	{
		namespace tuple_unpack
		{
			template<std::uintmax_t...>
			struct seq final
			{
			};
			template<std::uintmax_t N, std::uintmax_t... S>
			struct gens final
			: gens<N-1, N-1, S...>
			{
			};
			template<std::uintmax_t... S>
			struct gens<0, S...> final
			{
				using type = seq<S...>;
			};
		};

		template<template<typename...> typename To, typename Tuple>
		struct tuple_template_forward;
		template<template<typename...> typename To, typename... Args>
		struct tuple_template_forward<To, std::tuple<Args...>> final
		{
			using type = To<Args...>;
		};

		template<typename... Tuples>
		struct tuple_type_cat
		{
			using type = typename std::function<decltype(std::tuple_cat<Tuples...>)>::result_type;
		};

		namespace impl
		{
			template<typename Type, typename... Args>
			struct tuple_contains;
			template<typename Type, typename First, typename... Rest>
			struct tuple_contains<Type, First, Rest...> final
			{
				static constexpr bool value = (std::is_same<Type, First>::value || tuple_contains<Type, Rest...>::value);
			};
			template<typename Type>
			struct tuple_contains<Type> final
			: std::false_type
			{
			};
		}

		template<typename Tuple, typename Type>
		struct tuple_contains final
		{
			static constexpr bool value = tuple_template_forward<impl::tuple_contains, typename tuple_type_cat<std::tuple<Type>, Tuple>::type>::type::value;
		};

		namespace impl
		{
			template<typename Current, typename... Args>
			struct tuple_prune;
			template<typename Current, typename First, typename... Rest>
			struct tuple_prune<Current, First, Rest...> final
			{
				using type = typename std::conditional
				<
					util::tuple_contains<Current, First>::value,
					tuple_prune<Current, Rest...>,
					tuple_prune<typename tuple_type_cat<Current, std::tuple<First>>::type, Rest...>
				>::type::type;
			};
			template<typename Current>
			struct tuple_prune<Current> final
			{
				using type = Current;
			};
		}

		template<typename Tuple>
		struct tuple_prune final
		{
			using type = typename tuple_template_forward<impl::tuple_prune, typename tuple_type_cat<std::tuple<std::tuple<>>, Tuple>::type>::type::type;
		};
	}
}

#endif
<commit_msg>SpecificTo was a bad idea<commit_after>#ifndef resplunk_util_Tuples_HeaderPlusPlus
#define resplunk_util_Tuples_HeaderPlusPlus

#include <cstdint>
#include <tuple>
#include <functional>
#include <type_traits>

namespace resplunk
{
	namespace util
	{
		namespace tuple_unpack
		{
			template<std::uintmax_t...>
			struct seq final
			{
			};
			template<std::uintmax_t N, std::uintmax_t... S>
			struct gens final
			: gens<N-1, N-1, S...>
			{
			};
			template<std::uintmax_t... S>
			struct gens<0, S...> final
			{
				using type = seq<S...>;
			};
		};

		template<template<typename...> typename To, typename Tuple>
		struct tuple_template_forward;
		template<template<typename...> typename To, typename... Args>
		struct tuple_template_forward<To, std::tuple<Args...>> final
		{
			using type = To<Args...>;
		};

		template<typename... Tuples>
		struct tuple_type_cat
		{
			using type = typename std::function<decltype(std::tuple_cat<Tuples...>)>::result_type;
		};

		namespace impl
		{
			template<typename Type, typename... Args>
			struct tuple_contains;
			template<typename Type, typename First, typename... Rest>
			struct tuple_contains<Type, First, Rest...> final
			{
				static constexpr bool value = (std::is_same<Type, First>::value || tuple_contains<Type, Rest...>::value);
			};
			template<typename Type>
			struct tuple_contains<Type> final
			: std::false_type
			{
			};
		}

		template<typename Tuple, typename Type>
		struct tuple_contains final
		{
			static constexpr bool value = tuple_template_forward<impl::tuple_contains, typename tuple_type_cat<std::tuple<Type>, Tuple>::type>::type::value;
		};

		namespace impl
		{
			template<typename Current, typename... Args>
			struct tuple_prune;
			template<typename Current, typename First, typename... Rest>
			struct tuple_prune<Current, First, Rest...> final
			{
				using type = typename std::conditional
				<
					util::tuple_contains<Current, First>::value,
					tuple_prune<Current, Rest...>,
					tuple_prune<typename tuple_type_cat<Current, std::tuple<First>>::type, Rest...>
				>::type::type;
			};
			template<typename Current>
			struct tuple_prune<Current> final
			{
				using type = Current;
			};
		}

		template<typename Tuple>
		struct tuple_prune final
		{
			using type = typename tuple_template_forward<impl::tuple_prune, typename tuple_type_cat<std::tuple<std::tuple<>>, Tuple>::type>::type::type;
		};

		template<template<typename...> typename Check, typename... Tuple>
		struct multi_assert;
		template<template<typename...> typename Check, typename First, typename... Rest>
		struct multi_assert<Check, First, Rest...> final
		{
			static constexpr bool value = (tuple_template_forward<Check, First>::type::value && multi_assert<Check, Rest...>::value);
		};
		template<template<typename...> typename Check>
		struct multi_assert<Check> final
		: std::true_type
		{
		};
	}
}

#endif
<|endoftext|>


<commit_before>#include <log4cpp/AppendersFactory.hh>
#include <stdexcept>

namespace log4cpp
{
   static AppendersFactory* appenders_factory_ = 0;

   std::auto_ptr<Appender> create_file_appender(const FactoryParams&);
   std::auto_ptr<Appender> create_roll_file_appender(const FactoryParams&);
   std::auto_ptr<Appender> create_idsa_appender(const FactoryParams&);
   std::auto_ptr<Appender> create_nt_event_log_appender(const FactoryParams&);
   std::auto_ptr<Appender> create_remote_syslog_appender(const FactoryParams&);
   std::auto_ptr<Appender> create_syslog_appender(const FactoryParams&);
   std::auto_ptr<Appender> create_win32_debug_appender(const FactoryParams&);
   std::auto_ptr<Appender> create_abort_appender(const FactoryParams&);
   std::auto_ptr<Appender> create_smtp_appender(const FactoryParams&);

   AppendersFactory& AppendersFactory::getInstance()
   {
      if (!appenders_factory_)
      {
         std::auto_ptr<AppendersFactory> af(new AppendersFactory);

         af->registerCreator("file", &create_file_appender);
         af->registerCreator("roll file", &create_roll_file_appender);
         af->registerCreator("remote syslog", &create_remote_syslog_appender);
         af->registerCreator("abort", &create_abort_appender);

#if defined(LOG4CPP_HAVE_LIBIDSA)
         af->registerCreator("idsa", &create_idsa_appender);
#endif

#if defined(LOG4CPP_HAVE_SYSLOG)
         af->registerCreator("syslog", &create_syslog_appender);
#endif

#if defined(WIN32)
         af->registerCreator("win32 debug", &create_win32_debug_appender);
         af->registerCreator("nt event log", &create_nt_event_log_appender);
#endif
         af->registerCreator("smtp", &create_smtp_appender);

         appenders_factory_ = af.release();
      }

      return *appenders_factory_;
   }

   void AppendersFactory::registerCreator(const std::string& class_name, create_function_t create_function)
   {
      const_iterator i = creators_.find(class_name);
      if (i != creators_.end())
         throw std::invalid_argument("Appender creator for type name '" + class_name + "' allready registered");

      creators_[class_name] = create_function;
   }

   std::auto_ptr<Appender> AppendersFactory::create(const std::string& class_name, const params_t& params)
   {
      const_iterator i = creators_.find(class_name);
      if (i == creators_.end())
         throw std::invalid_argument("There is no appender with type name '" + class_name + "'");

      return (*i->second)(params);
   }

   bool AppendersFactory::registered(const std::string& class_name) const
   {
      return creators_.end() != creators_.find(class_name);
   }
}
<commit_msg>Fix: Ifdef SmtpAppender registration code<commit_after>#include <log4cpp/AppendersFactory.hh>
#include <stdexcept>

namespace log4cpp
{
   static AppendersFactory* appenders_factory_ = 0;

   std::auto_ptr<Appender> create_file_appender(const FactoryParams&);
   std::auto_ptr<Appender> create_roll_file_appender(const FactoryParams&);
   std::auto_ptr<Appender> create_idsa_appender(const FactoryParams&);
   std::auto_ptr<Appender> create_nt_event_log_appender(const FactoryParams&);
   std::auto_ptr<Appender> create_remote_syslog_appender(const FactoryParams&);
   std::auto_ptr<Appender> create_syslog_appender(const FactoryParams&);
   std::auto_ptr<Appender> create_win32_debug_appender(const FactoryParams&);
   std::auto_ptr<Appender> create_abort_appender(const FactoryParams&);
   std::auto_ptr<Appender> create_smtp_appender(const FactoryParams&);

   AppendersFactory& AppendersFactory::getInstance()
   {
      if (!appenders_factory_)
      {
         std::auto_ptr<AppendersFactory> af(new AppendersFactory);

         af->registerCreator("file", &create_file_appender);
         af->registerCreator("roll file", &create_roll_file_appender);
         af->registerCreator("remote syslog", &create_remote_syslog_appender);
         af->registerCreator("abort", &create_abort_appender);

#if defined(LOG4CPP_HAVE_LIBIDSA)
         af->registerCreator("idsa", &create_idsa_appender);
#endif

#if defined(LOG4CPP_HAVE_SYSLOG)
         af->registerCreator("syslog", &create_syslog_appender);
#endif

#if defined(WIN32)
         af->registerCreator("win32 debug", &create_win32_debug_appender);
         af->registerCreator("nt event log", &create_nt_event_log_appender);
#endif

#if defined(LOG4CPP_HAVE_BOOST)
#include <boost/version.hpp>
#if BOOST_VERSION >= 103400
         af->registerCreator("smtp", &create_smtp_appender);
#endif // LOG4CPP_HAVE_BOOST
#endif // BOOST_VERSION >= 103400

         appenders_factory_ = af.release();
      }

      return *appenders_factory_;
   }

   void AppendersFactory::registerCreator(const std::string& class_name, create_function_t create_function)
   {
      const_iterator i = creators_.find(class_name);
      if (i != creators_.end())
         throw std::invalid_argument("Appender creator for type name '" + class_name + "' allready registered");

      creators_[class_name] = create_function;
   }

   std::auto_ptr<Appender> AppendersFactory::create(const std::string& class_name, const params_t& params)
   {
      const_iterator i = creators_.find(class_name);
      if (i == creators_.end())
         throw std::invalid_argument("There is no appender with type name '" + class_name + "'");

      return (*i->second)(params);
   }

   bool AppendersFactory::registered(const std::string& class_name) const
   {
      return creators_.end() != creators_.find(class_name);
   }
}
<|endoftext|>