<commit_before>/*
 * Copyright © 2010 Intel Corporation
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice (including the next
 * paragraph) shall be included in all copies or substantial portions of the
 * Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 */

/**
 * \file opt_constant_variable.cpp
 *
 * Marks variables assigned a single constant value over the course
 * of the program as constant.
 *
 * The goal here is to trigger further constant folding and then dead
 * code elimination.  This is common with vector/matrix constructors
 * and calls to builtin functions.
 */

#include "ir.h"
#include "ir_visitor.h"
#include "ir_optimization.h"
#include "glsl_types.h"

namespace {

struct assignment_entry {
   exec_node link;
   int assignment_count;
   ir_variable *var;
   ir_constant *constval;
   bool our_scope;
};

class ir_constant_variable_visitor : public ir_hierarchical_visitor {
public:
   virtual ir_visitor_status visit_enter(ir_dereference_variable *);
   virtual ir_visitor_status visit(ir_variable *);
   virtual ir_visitor_status visit_enter(ir_assignment *);
   virtual ir_visitor_status visit_enter(ir_call *);

   exec_list list;
};

} /* unnamed namespace */

static struct assignment_entry *
get_assignment_entry(ir_variable *var, exec_list *list)
{
   struct assignment_entry *entry;

   foreach_list_typed(struct assignment_entry, entry, link, list) {
      if (entry->var == var)
	 return entry;
   }

   entry = (struct assignment_entry *)calloc(1, sizeof(*entry));
   entry->var = var;
   list->push_head(&entry->link);
   return entry;
}

ir_visitor_status
ir_constant_variable_visitor::visit(ir_variable *ir)
{
   struct assignment_entry *entry = get_assignment_entry(ir, &this->list);
   entry->our_scope = true;
   return visit_continue;
}

/* Skip derefs of variables so that we can detect declarations. */
ir_visitor_status
ir_constant_variable_visitor::visit_enter(ir_dereference_variable *ir)
{
   (void)ir;
   return visit_continue_with_parent;
}

ir_visitor_status
ir_constant_variable_visitor::visit_enter(ir_assignment *ir)
{
   ir_constant *constval;
   struct assignment_entry *entry;

   entry = get_assignment_entry(ir->lhs->variable_referenced(), &this->list);
   assert(entry);
   entry->assignment_count++;

   /* If it's already constant, don't do the work. */
   if (entry->var->constant_value)
      return visit_continue;

   /* OK, now find if we actually have all the right conditions for
    * this to be a constant value assigned to the var.
    */
   if (ir->condition)
      return visit_continue;

   ir_variable *var = ir->whole_variable_written();
   if (!var)
      return visit_continue;

   constval = ir->rhs->constant_expression_value();
   if (!constval)
      return visit_continue;

   /* Mark this entry as having a constant assignment (if the
    * assignment count doesn't go >1).  do_constant_variable will fix
    * up the variable with the constant value later.
    */
   entry->constval = constval;

   return visit_continue;
}

ir_visitor_status
ir_constant_variable_visitor::visit_enter(ir_call *ir)
{
   /* Mark any out parameters as assigned to */
   exec_list_iterator sig_iter = ir->callee->parameters.iterator();
   foreach_iter(exec_list_iterator, iter, *ir) {
      ir_rvalue *param_rval = (ir_rvalue *)iter.get();
      ir_variable *param = (ir_variable *)sig_iter.get();

      if (param->mode == ir_var_out ||
	  param->mode == ir_var_inout) {
	 ir_variable *var = param_rval->variable_referenced();
	 struct assignment_entry *entry;

	 assert(var);
	 entry = get_assignment_entry(var, &this->list);
	 entry->assignment_count++;
      }
      sig_iter.next();
   }

   /* Mark the return storage as having been assigned to */
   if (ir->return_deref != NULL) {
      ir_variable *var = ir->return_deref->variable_referenced();
      struct assignment_entry *entry;

      assert(var);
      entry = get_assignment_entry(var, &this->list);
      entry->assignment_count++;
   }

   return visit_continue;
}

/**
 * Does a copy propagation pass on the code present in the instruction stream.
 */
bool
do_constant_variable(exec_list *instructions)
{
   bool progress = false;
   ir_constant_variable_visitor v;

   v.run(instructions);

   while (!v.list.is_empty()) {

      struct assignment_entry *entry;
      entry = exec_node_data(struct assignment_entry, v.list.head, link);

      if (entry->assignment_count == 1 && entry->constval && entry->our_scope) {
	 entry->var->constant_value = entry->constval;
	 progress = true;
      }
      entry->link.remove();
      free(entry);
   }

   return progress;
}

bool
do_constant_variable_unlinked(exec_list *instructions)
{
   bool progress = false;

   foreach_iter(exec_list_iterator, iter, *instructions) {
      ir_instruction *ir = (ir_instruction *)iter.get();
      ir_function *f = ir->as_function();
      if (f) {
	 foreach_iter(exec_list_iterator, sigiter, *f) {
	    ir_function_signature *sig =
	       (ir_function_signature *) sigiter.get();
	    if (do_constant_variable(&sig->body))
	       progress = true;
	 }
      }
   }

   return progress;
}
<commit_msg>fix too eager constant variable optimization v2; mark function input parameters as being assigned to<commit_after>/*
 * Copyright © 2010 Intel Corporation
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice (including the next
 * paragraph) shall be included in all copies or substantial portions of the
 * Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 */

/**
 * \file opt_constant_variable.cpp
 *
 * Marks variables assigned a single constant value over the course
 * of the program as constant.
 *
 * The goal here is to trigger further constant folding and then dead
 * code elimination.  This is common with vector/matrix constructors
 * and calls to builtin functions.
 */

#include "ir.h"
#include "ir_visitor.h"
#include "ir_optimization.h"
#include "glsl_types.h"

namespace {

struct assignment_entry {
   exec_node link;
   int assignment_count;
   ir_variable *var;
   ir_constant *constval;
   bool our_scope;
};

class ir_constant_variable_visitor : public ir_hierarchical_visitor {
public:
   virtual ir_visitor_status visit_enter(ir_dereference_variable *);
   virtual ir_visitor_status visit(ir_variable *);
   virtual ir_visitor_status visit_enter(ir_assignment *);
   virtual ir_visitor_status visit_enter(ir_call *);
   virtual ir_visitor_status visit_enter(ir_function_signature *);

   exec_list list;
};

} /* unnamed namespace */

static struct assignment_entry *
get_assignment_entry(ir_variable *var, exec_list *list)
{
   struct assignment_entry *entry;

   foreach_list_typed(struct assignment_entry, entry, link, list) {
      if (entry->var == var)
	 return entry;
   }

   entry = (struct assignment_entry *)calloc(1, sizeof(*entry));
   entry->var = var;
   list->push_head(&entry->link);
   return entry;
}

ir_visitor_status
ir_constant_variable_visitor::visit(ir_variable *ir)
{
   struct assignment_entry *entry = get_assignment_entry(ir, &this->list);
   entry->our_scope = true;
   return visit_continue;
}

/* Skip derefs of variables so that we can detect declarations. */
ir_visitor_status
ir_constant_variable_visitor::visit_enter(ir_dereference_variable *ir)
{
   (void)ir;
   return visit_continue_with_parent;
}

ir_visitor_status
ir_constant_variable_visitor::visit_enter(ir_assignment *ir)
{
   ir_constant *constval;
   struct assignment_entry *entry;

   entry = get_assignment_entry(ir->lhs->variable_referenced(), &this->list);
   assert(entry);
   entry->assignment_count++;

   /* If it's already constant, don't do the work. */
   if (entry->var->constant_value)
      return visit_continue;

   /* OK, now find if we actually have all the right conditions for
    * this to be a constant value assigned to the var.
    */
   if (ir->condition)
      return visit_continue;

   ir_variable *var = ir->whole_variable_written();
   if (!var)
      return visit_continue;

   constval = ir->rhs->constant_expression_value();
   if (!constval)
      return visit_continue;

   /* Mark this entry as having a constant assignment (if the
    * assignment count doesn't go >1).  do_constant_variable will fix
    * up the variable with the constant value later.
    */
   entry->constval = constval;

   return visit_continue;
}

ir_visitor_status
ir_constant_variable_visitor::visit_enter(ir_call *ir)
{
   /* Mark any out parameters as assigned to */
   exec_list_iterator sig_iter = ir->callee->parameters.iterator();
   foreach_iter(exec_list_iterator, iter, *ir) {
      ir_rvalue *param_rval = (ir_rvalue *)iter.get();
      ir_variable *param = (ir_variable *)sig_iter.get();

      if (param->mode == ir_var_out ||
	  param->mode == ir_var_inout) {
	 ir_variable *var = param_rval->variable_referenced();
	 struct assignment_entry *entry;

	 assert(var);
	 entry = get_assignment_entry(var, &this->list);
	 entry->assignment_count++;
      }
      sig_iter.next();
   }

   /* Mark the return storage as having been assigned to */
   if (ir->return_deref != NULL) {
      ir_variable *var = ir->return_deref->variable_referenced();
      struct assignment_entry *entry;

      assert(var);
      entry = get_assignment_entry(var, &this->list);
      entry->assignment_count++;
   }

   return visit_continue;
}

ir_visitor_status
ir_constant_variable_visitor::visit_enter(ir_function_signature *ir)
{
   /* Mark any in parameters as assigned to */
   foreach_iter(exec_list_iterator, iter, ir->parameters) {
      ir_variable *var = (ir_variable *)iter.get();
      if (var->mode == ir_var_in || var->mode == ir_var_const_in || var->mode == ir_var_inout) {
         struct assignment_entry *entry;
         entry = get_assignment_entry(var, &this->list);
         entry->assignment_count++;
      }
   }
   visit_list_elements(this, &ir->body);
   return visit_continue_with_parent;
}

/**
 * Does a copy propagation pass on the code present in the instruction stream.
 */
bool
do_constant_variable(exec_list *instructions)
{
   bool progress = false;
   ir_constant_variable_visitor v;

   v.run(instructions);

   while (!v.list.is_empty()) {

      struct assignment_entry *entry;
      entry = exec_node_data(struct assignment_entry, v.list.head, link);

      if (entry->assignment_count == 1 && entry->constval && entry->our_scope) {
	 entry->var->constant_value = entry->constval;
	 progress = true;
      }
      entry->link.remove();
      free(entry);
   }

   return progress;
}

bool
do_constant_variable_unlinked(exec_list *instructions)
{
   bool progress = false;

   foreach_iter(exec_list_iterator, iter, *instructions) {
      ir_instruction *ir = (ir_instruction *)iter.get();
      ir_function *f = ir->as_function();
      if (f) {
	 foreach_iter(exec_list_iterator, sigiter, *f) {
	    ir_function_signature *sig =
	       (ir_function_signature *) sigiter.get();
	    if (do_constant_variable(&sig->body))
	       progress = true;
	 }
      }
   }

   return progress;
}
<|endoftext|>


<commit_before>/* conduitConfigDialog.cc                KPilot
**
** Copyright (C) 2004 by Dan Pilone
** Written 2004 by Reinhold Kainhofer
**
** This file defines a .ui-based configuration dialog for conduits.
*/

/*
** This program is free software; you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation; either version 2 of the License, or
** (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with this program in a file called COPYING; if not, write to
** the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
** MA 02111-1307, USA.
*/

/*
** Bug reports and questions can be sent to kde-pim@kde.org
*/

static const char *conduitconfigdialog_id =
	"$Id$";

//#include "options.h"

#include <qpushbutton.h>
#include <qbuttongroup.h>
#include <qcheckbox.h>
#include <qlineedit.h>

#include <kmessagebox.h>
#include <kglobal.h>
#include <klocale.h>
#include <kconfigskeleton.h>

#include "kpilotConfig.h"
#include "options.h"

#include "kpilotConfigWizard_base1.h"
#include "kpilotConfigWizard_base2.h"
#include "kpilotConfigWizard_base3.h"

#include "kpilotConfigWizard.moc"
#include "kpilotProbeDialog.h"

ConfigWizard::ConfigWizard(QWidget *parent, const char *n) :
	KWizard(parent, n)
{
	page1=new ConfigWizard_base1(this);
	addPage( page1, i18n("Select connection type") );
	page2=new ConfigWizard_base2(this);
	addPage( page2, i18n("Pilot info") );
	page3=new ConfigWizard_base3(this);
	addPage( page3, i18n("Application to sync with") );
	setFinishEnabled( page3, true );

	connect( page2->fProbeButton, SIGNAL( pressed() ),
		this, SLOT( probeHandheld() ) );

	KPilotSettings::self()->readConfig();
	page2->fUserName->setText( KPilotSettings::userName() );
	page2->fDeviceName->setText( KPilotSettings::pilotDevice() );
	page2->fPilotRunningPermanently->setChecked( KPilotSettings::startDaemonAtLogin() );
}

ConfigWizard::~ConfigWizard()
{
}

void ConfigWizard::accept()
{
	FUNCTIONSETUP;
	QString username( page2->fUserName->text() );
	QString devicename( page2->fDeviceName->text() );
//	int devicetype( page1->fConnectionType->selectedId() );
	enum eSyncApp {
		eAppKDE=0,
		eAppKontact,
		eAppEvolution
	} app;
	app=(eSyncApp)( page3->fAppType->selectedId() );
	bool keepPermanently( page2->fPilotRunningPermanently->isChecked() );
#ifdef DEBUG
	DEBUGCONDUIT<<fname<<"Keep permanently: "<<keepPermanently<<endl;
#endif

	KPilotSettings::setPilotDevice( devicename );
	KPilotSettings::setUserName(username);
	KPilotSettings::setEncoding("iso 8859-15");
	KPilotSettings::setDockDaemon( true );
	KPilotSettings::setKillDaemonAtExit( !keepPermanently);
	KPilotSettings::setQuitAfterSync( !keepPermanently );
	KPilotSettings::setStartDaemonAtLogin( keepPermanently );
	KPilotSettings::setSyncType(0);
	KPilotSettings::setFullSyncOnPCChange( true );
	KPilotSettings::setConflictResolution(0);

	QStringList conduits = KPilotSettings::installedConduits();
	// TODO: enable the right conduits
#define APPEND_CONDUIT(a) if (!conduits.contains(a)) conduits.append(a)
	QString applicationName(i18n("general KDE-PIM"));
	APPEND_CONDUIT("internal_fileinstall");
	APPEND_CONDUIT("todo-conduit");
	APPEND_CONDUIT("vcal-conduit");
	switch (app) {
		case eAppEvolution:
			applicationName=i18n("Gnome's PIM suite", "Evolution");
			conduits.remove("knotes-conduit");
			// TODO: Once the Evolution abook resource is finished, enable it...
			conduits.remove("abbrowser_conduit");
			// TODO: settings for conduits
			KMessageBox::information(this, i18n("KPilot cannot yet synchronize the addressbook with Evolution, so the addressbook conduit was disabled.\nWhen syncing the calendar or todo list using KPilot, please quit Evolution before the sync, otherwise you will loose data."), i18n("Restrictions with Evolution"));
			break;
		case eAppKontact:
			applicationName=i18n("KDE's PIM suite", "Kontact");
		case eAppKDE:
		default:
			APPEND_CONDUIT("knotes-conduit");
			APPEND_CONDUIT("abbrowser_conduit");
			// TODO: settings for conduits
			break;
	}
	KPilotSettings::setInstalledConduits( conduits );
#undef APPEND_CONDUIT

	KMessageBox::information(this, i18n("KPilot is now configured to sync with %1.\n"
		"The remaining options in the config dialog are advanced options and can "
		"be used to fine-tune KPilot.").arg(applicationName), i18n("Automatic configuration finished"));
	KPilotSettings::self()->writeConfig();
	QDialog::accept();
}

// Devices to probe:
// Linux: /dev/pilot (symlink), /dev/ttyS* (serial + irda), /dev/tts/[012345...] (with devfs),
//        /dev/ttyUSB*, /dev/usb/tts/[012345...]
// *BSD: /dev/pilot, /dev/cuaa[01]   (serial), /dev/ucom* (usb)

void ConfigWizard::probeHandheld()
{
	ProbeDialog *probeDialog = new ProbeDialog( this );
	if ( probeDialog->exec() && probeDialog->detected() ) {
		page2->fUserName->setText( probeDialog->userName() );
		page2->fDeviceName->setText( probeDialog->device() );
	}
	KPILOT_DELETE(probeDialog);
}

<commit_msg><commit_after>/* conduitConfigDialog.cc                KPilot
**
** Copyright (C) 2004 by Dan Pilone
** Written 2004 by Reinhold Kainhofer
**
** This file defines a .ui-based configuration dialog for conduits.
*/

/*
** This program is free software; you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation; either version 2 of the License, or
** (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with this program in a file called COPYING; if not, write to
** the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
** MA 02111-1307, USA.
*/

/*
** Bug reports and questions can be sent to kde-pim@kde.org
*/

static const char *conduitconfigdialog_id =
	"$Id$";

//#include "options.h"

#include <qpushbutton.h>
#include <qbuttongroup.h>
#include <qcheckbox.h>
#include <qlineedit.h>

#include <kmessagebox.h>
#include <kglobal.h>
#include <klocale.h>
#include <kconfigskeleton.h>

#include "kpilotConfig.h"
#include "options.h"

#include "kpilotConfigWizard_base1.h"
#include "kpilotConfigWizard_base2.h"
#include "kpilotConfigWizard_base3.h"

#include "kpilotConfigWizard.moc"
#include "kpilotProbeDialog.h"

ConfigWizard::ConfigWizard(QWidget *parent, const char *n) :
	KWizard(parent, n)
{
	page1=new ConfigWizard_base1(this);
	addPage( page1, i18n("Select connection type") );
	page2=new ConfigWizard_base2(this);
	addPage( page2, i18n("Pilot info") );
	page3=new ConfigWizard_base3(this);
	addPage( page3, i18n("Application to sync with") );
	setFinishEnabled( page3, true );

	connect( page2->fProbeButton, SIGNAL( pressed() ),
		this, SLOT( probeHandheld() ) );

	KPilotSettings::self()->readConfig();
	page2->fUserName->setText( KPilotSettings::userName() );
	page2->fDeviceName->setText( KPilotSettings::pilotDevice() );
	page2->fPilotRunningPermanently->setChecked( KPilotSettings::startDaemonAtLogin() );
}

ConfigWizard::~ConfigWizard()
{
}

void ConfigWizard::accept()
{
	FUNCTIONSETUP;
	QString username( page2->fUserName->text() );
	QString devicename( page2->fDeviceName->text() );
//	int devicetype( page1->fConnectionType->selectedId() );
	enum eSyncApp {
		eAppKDE=0,
		eAppKontact,
		eAppEvolution
	} app;
	app=(eSyncApp)( page3->fAppType->selectedId() );
	bool keepPermanently( page2->fPilotRunningPermanently->isChecked() );
#ifdef DEBUG
	DEBUGCONDUIT<<fname<<"Keep permanently: "<<keepPermanently<<endl;
#endif

	KPilotSettings::setPilotDevice( devicename );
	KPilotSettings::setUserName(username);
	KPilotSettings::setEncoding("iso 8859-15");
	KPilotSettings::setDockDaemon( true );
	KPilotSettings::setKillDaemonAtExit( !keepPermanently);
	KPilotSettings::setQuitAfterSync( !keepPermanently );
	KPilotSettings::setStartDaemonAtLogin( keepPermanently );
	KPilotSettings::setSyncType(0);
	KPilotSettings::setFullSyncOnPCChange( true );
	KPilotSettings::setConflictResolution(0);

	QStringList conduits = KPilotSettings::installedConduits();
	// TODO: enable the right conduits
#define APPEND_CONDUIT(a) if (!conduits.contains(a)) conduits.append(a)
	QString applicationName(i18n("general KDE-PIM"));
	APPEND_CONDUIT("internal_fileinstall");
	APPEND_CONDUIT("todo-conduit");
	APPEND_CONDUIT("vcal-conduit");
	switch (app) {
		case eAppEvolution:
			applicationName=i18n("Gnome's PIM suite", "Evolution");
			conduits.remove("knotes-conduit");
			// TODO: Once the Evolution abook resource is finished, enable it...
			conduits.remove("abbrowser_conduit");
			// TODO: settings for conduits
			KMessageBox::information(this, i18n("KPilot cannot yet synchronize the addressbook with Evolution, so the addressbook conduit was disabled.\nWhen syncing the calendar or todo list using KPilot please quit Evolution before the sync, otherwise you will lose data."), i18n("Restrictions with Evolution"));
			break;
		case eAppKontact:
			applicationName=i18n("KDE's PIM suite", "Kontact");
		case eAppKDE:
		default:
			APPEND_CONDUIT("knotes-conduit");
			APPEND_CONDUIT("abbrowser_conduit");
			// TODO: settings for conduits
			break;
	}
	KPilotSettings::setInstalledConduits( conduits );
#undef APPEND_CONDUIT

	KMessageBox::information(this, i18n("KPilot is now configured to sync with %1.\n"
		"The remaining options in the config dialog are advanced options and can "
		"be used to fine-tune KPilot.").arg(applicationName), i18n("Automatic configuration finished"));
	KPilotSettings::self()->writeConfig();
	QDialog::accept();
}

// Devices to probe:
// Linux: /dev/pilot (symlink), /dev/ttyS* (serial + irda), /dev/tts/[012345...] (with devfs),
//        /dev/ttyUSB*, /dev/usb/tts/[012345...]
// *BSD: /dev/pilot, /dev/cuaa[01]   (serial), /dev/ucom* (usb)

void ConfigWizard::probeHandheld()
{
	ProbeDialog *probeDialog = new ProbeDialog( this );
	if ( probeDialog->exec() && probeDialog->detected() ) {
		page2->fUserName->setText( probeDialog->userName() );
		page2->fDeviceName->setText( probeDialog->device() );
	}
	KPILOT_DELETE(probeDialog);
}

<|endoftext|>


<commit_before>/* libwpd
 * Copyright (C) 2004 Marc Maurer (uwog@uwog.net)
 * Copyright (C) 2004-2006 Fridrich Strba (fridrich.strba@bluewin.ch)
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * 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
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
 *
 * For further information visit http://libwpd.sourceforge.net
 */

/* "This product is not manufactured, approved, or supported by
 * Corel Corporation or Corel Corporation Limited."
 */

#include "WP3FileStructure.h"
#include "WP3VariableLengthGroup.h"
#include "WP3UnsupportedVariableLengthGroup.h"
#include "WP3EndOfLinePageGroup.h"
#include "WP3MiscellaneousGroup.h"
#include "WP3PageFormatGroup.h"
#include "WP3FontGroup.h"
#include "WP3DefinitionGroup.h"
#include "WP3DisplayGroup.h"
#include "WP3HeaderFooterGroup.h"
#include "WP3FootnoteEndnoteGroup.h"
#include "WP3TablesGroup.h"
#include "libwpd_internal.h"

WP3VariableLengthGroup::WP3VariableLengthGroup()
{
}

WP3VariableLengthGroup * WP3VariableLengthGroup::constructVariableLengthGroup(WPXInputStream *input, uint8_t group)
{
	switch (group)
	{
		case WP3_PAGE_FORMAT_GROUP:
			return new WP3PageFormatGroup(input);
		case WP3_END_OF_LINE_PAGE_GROUP:
			return new WP3EndOfLinePageGroup(input);
		case WP3_MISCELLANEOUS_GROUP:
			return new WP3MiscellaneousGroup(input);
		case WP3_TABLES_GROUP:
			return new WP3TablesGroup(input);
		case WP3_FONT_GROUP:
			return new WP3FontGroup(input);
		case WP3_DEFINITION_GROUP:
			return new WP3DefinitionGroup(input);
		case WP3_HEADER_FOOTER_GROUP:
			return new WP3HeaderFooterGroup(input);
		case WP3_FOOTNOTE_ENDNOTE_GROUP:
			return new WP3FootnoteEndnoteGroup(input);
		case WP3_DISPLAY_GROUP:
			return new WP3DisplayGroup(input);
		default:
			// this is an unhandled group, just skip it
			return new WP3UnsupportedVariableLengthGroup(input);
	}
}

bool WP3VariableLengthGroup::isGroupConsistent(WPXInputStream *input, const uint8_t group)
{
	uint32_t startPosition = input->tell();

	try
	{
		uint8_t subGroup = readU8(input);
		uint16_t size = readU16(input, true);

		if (input->seek((startPosition + size - 1 - input->tell()), WPX_SEEK_CUR) || input->atEOS())
		{
			input->seek(startPosition, WPX_SEEK_SET);
			return false;
		}
		if (size != readU16(input, true))
		{
			input->seek(startPosition, WPX_SEEK_SET);
			return false;
		}
		if (subGroup != readU8(input))
		{
			input->seek(startPosition, WPX_SEEK_SET);
			return false;
		}
		if (group != readU8(input))
		{
			input->seek(startPosition, WPX_SEEK_SET);
			return false;
		}

		input->seek(startPosition, WPX_SEEK_SET);
		return true;
	}
	catch(...)
	{
		input->seek(startPosition, WPX_SEEK_SET);
		return false;
	}
}

void WP3VariableLengthGroup::_read(WPXInputStream *input)
{
	uint32_t startPosition = input->tell();

	WPD_DEBUG_MSG(("WordPerfect: handling a variable length group\n"));

	m_subGroup = readU8(input);
	m_size = readU16(input, true) + 4; // the length is the number of data bytes minus 4 (ie. the function codes)

	WPD_DEBUG_MSG(("WordPerfect: Read variable group header (start_position: %i, sub_group: 0x%x, size: %i)\n", startPosition, m_subGroup, m_size));

	_readContents(input);

	input->seek((startPosition + m_size - 5 - input->tell()), WPX_SEEK_CUR);

	if (m_size != (readU16(input, true) + 4))
	{
		WPD_DEBUG_MSG(("WordPerfect: Possible corruption detected. Bailing out!\n"));
		throw FileException();
	}
	if (m_subGroup != readU8(input))
	{
		WPD_DEBUG_MSG(("WordPerfect: Possible corruption detected. Bailing out!\n"));
		throw FileException();
	}

	input->seek((startPosition + m_size - 1 - input->tell()), WPX_SEEK_CUR);

}
<commit_msg>Adding a missing const<commit_after>/* libwpd
 * Copyright (C) 2004 Marc Maurer (uwog@uwog.net)
 * Copyright (C) 2004-2006 Fridrich Strba (fridrich.strba@bluewin.ch)
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * 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
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
 *
 * For further information visit http://libwpd.sourceforge.net
 */

/* "This product is not manufactured, approved, or supported by
 * Corel Corporation or Corel Corporation Limited."
 */

#include "WP3FileStructure.h"
#include "WP3VariableLengthGroup.h"
#include "WP3UnsupportedVariableLengthGroup.h"
#include "WP3EndOfLinePageGroup.h"
#include "WP3MiscellaneousGroup.h"
#include "WP3PageFormatGroup.h"
#include "WP3FontGroup.h"
#include "WP3DefinitionGroup.h"
#include "WP3DisplayGroup.h"
#include "WP3HeaderFooterGroup.h"
#include "WP3FootnoteEndnoteGroup.h"
#include "WP3TablesGroup.h"
#include "libwpd_internal.h"

WP3VariableLengthGroup::WP3VariableLengthGroup()
{
}

WP3VariableLengthGroup * WP3VariableLengthGroup::constructVariableLengthGroup(WPXInputStream *input, const uint8_t group)
{
	switch (group)
	{
		case WP3_PAGE_FORMAT_GROUP:
			return new WP3PageFormatGroup(input);
		case WP3_END_OF_LINE_PAGE_GROUP:
			return new WP3EndOfLinePageGroup(input);
		case WP3_MISCELLANEOUS_GROUP:
			return new WP3MiscellaneousGroup(input);
		case WP3_TABLES_GROUP:
			return new WP3TablesGroup(input);
		case WP3_FONT_GROUP:
			return new WP3FontGroup(input);
		case WP3_DEFINITION_GROUP:
			return new WP3DefinitionGroup(input);
		case WP3_HEADER_FOOTER_GROUP:
			return new WP3HeaderFooterGroup(input);
		case WP3_FOOTNOTE_ENDNOTE_GROUP:
			return new WP3FootnoteEndnoteGroup(input);
		case WP3_DISPLAY_GROUP:
			return new WP3DisplayGroup(input);
		default:
			// this is an unhandled group, just skip it
			return new WP3UnsupportedVariableLengthGroup(input);
	}
}

bool WP3VariableLengthGroup::isGroupConsistent(WPXInputStream *input, const uint8_t group)
{
	uint32_t startPosition = input->tell();

	try
	{
		uint8_t subGroup = readU8(input);
		uint16_t size = readU16(input, true);

		if (input->seek((startPosition + size - 1 - input->tell()), WPX_SEEK_CUR) || input->atEOS())
		{
			input->seek(startPosition, WPX_SEEK_SET);
			return false;
		}
		if (size != readU16(input, true))
		{
			input->seek(startPosition, WPX_SEEK_SET);
			return false;
		}
		if (subGroup != readU8(input))
		{
			input->seek(startPosition, WPX_SEEK_SET);
			return false;
		}
		if (group != readU8(input))
		{
			input->seek(startPosition, WPX_SEEK_SET);
			return false;
		}

		input->seek(startPosition, WPX_SEEK_SET);
		return true;
	}
	catch(...)
	{
		input->seek(startPosition, WPX_SEEK_SET);
		return false;
	}
}

void WP3VariableLengthGroup::_read(WPXInputStream *input)
{
	uint32_t startPosition = input->tell();

	WPD_DEBUG_MSG(("WordPerfect: handling a variable length group\n"));

	m_subGroup = readU8(input);
	m_size = readU16(input, true) + 4; // the length is the number of data bytes minus 4 (ie. the function codes)

	WPD_DEBUG_MSG(("WordPerfect: Read variable group header (start_position: %i, sub_group: 0x%x, size: %i)\n", startPosition, m_subGroup, m_size));

	_readContents(input);

	input->seek((startPosition + m_size - 5 - input->tell()), WPX_SEEK_CUR);

	if (m_size != (readU16(input, true) + 4))
	{
		WPD_DEBUG_MSG(("WordPerfect: Possible corruption detected. Bailing out!\n"));
		throw FileException();
	}
	if (m_subGroup != readU8(input))
	{
		WPD_DEBUG_MSG(("WordPerfect: Possible corruption detected. Bailing out!\n"));
		throw FileException();
	}

	input->seek((startPosition + m_size - 1 - input->tell()), WPX_SEEK_CUR);

}
<|endoftext|>


<commit_before>/*
 * Copyright 2009-2013 The VOTCA Development Team (http://www.votca.org)
 *
 * 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 <vector>
#include <boost/lexical_cast.hpp>
#include <boost/algorithm/string.hpp>
#include <votca/tools/getline.h>
#include "pdbreader.h"

namespace votca { namespace csg {
    using namespace boost;
using namespace std;

bool PDBReader::ReadTopology(string file,  Topology &top)
{
   _topology = true;
   top.Cleanup();

   _fl.open(file.c_str());
    if(!_fl.is_open())
        throw std::ios_base::failure("Error on open topology file: " + file);

   NextFrame(top);

    _fl.close();

    return true;
}

bool PDBReader::Open(const string &file)
{
    _fl.open(file.c_str());
    if(!_fl.is_open())
        throw std::ios_base::failure("Error on open trajectory file: " + file);
    return true;
}

void PDBReader::Close()
{
    _fl.close();
}

bool PDBReader::FirstFrame(Topology &top)
{
    _topology = false;
    NextFrame(top);
    return true;
}

bool PDBReader::NextFrame(Topology &top)
{
    string line;
    int i = 0 ;
    while ( std::getline(_fl, line) ){
        if( wildcmp("CRYST1*",line.c_str())){
	     string a, b, c, alpha, beta, gamma;
	     try {
               //1 -  6       Record name    "CRYST1"
	       a=string(line,(7-1),9); //7 - 15       Real(9.3)      a (Angstroms)
	       b=string(line,(16-1),9); //16 - 24       Real(9.3)      b (Angstroms)
	       c=string(line,(25-1),9); //25 - 33       Real(9.3)      c (Angstroms)
	       alpha=string(line,(34-1),7); //34 - 40       Real(7.2)      alpha (degrees)
               beta=string(line,(41-1),7); //41 - 47       Real(7.2)      beta (degrees)
	       gamma=string(line,(48-1),7); //48 - 54       Real(7.2)      gamma (degrees)
               //56 - 66       LString        Space group
	       //67 - 70       Integer        Z value
	    } catch (std::out_of_range& err) {
	      throw std::runtime_error("Misformated pdb file in CRYST1 line");
	    }
	    boost::algorithm::trim(a);
	    boost::algorithm::trim(b);
	    boost::algorithm::trim(c);
	    boost::algorithm::trim(alpha);
	    boost::algorithm::trim(beta);
	    boost::algorithm::trim(gamma);
	    if ((!wildcmp("90*",alpha.c_str()))||(!wildcmp("90*",alpha.c_str()))||(!wildcmp("90*",alpha.c_str()))){
	         throw std::runtime_error("Non cubical box in pdb file not implemented, yet!");
            }
	    top.setBox(matrix(vec(boost::lexical_cast<double>(a), 0, 0),
	                      vec(0, boost::lexical_cast<double>(b), 0),
			      vec(0, 0, boost::lexical_cast<double>(c))));

	}
        if( wildcmp("ATOM*",line.c_str()) || wildcmp("HETATM*",line.c_str())){

            //      according to PDB format
	    string x,y,z, resNum, resName, atName;
            try {
	      /* Some pdb don't include all this, read only what we realy need*/
	      /* leave this here in case we need more later*/
              //string recType    (line,( 1-1),6); // str,  "ATOM", "HETATM"
              //string atNum      (line,( 7-1),6); // int,  Atom serial number
              atName=string(line,(13-1),4); // str,  Atom name
              //string atAltLoc   (line,(17-1),1); // char, Alternate location indicator
              resName=string(line,(18-1),3); // str,  Residue name
              //string chainID    (line,(22-1),1); // char, Chain identifier
              resNum=string(line,(23-1),4); // int,  Residue sequence number
              //string atICode    (line,(27-1),1); // char, Code for insertion of res
              x=string(line,(31-1),8); // float 8.3 ,x
              y=string(line,(39-1),8); // float 8.3 ,y
              z=string(line,(47-1),8); // float 8.3 ,z
              //string atOccup    (line,(55-1),6); // float  6.2, Occupancy
              //string atTFactor  (line,(61-1),6); // float  6.2, Temperature factor
              //string segID      (line,(73-1),4); // str, Segment identifier
              //string atElement  (line,(77-1),2); // str, Element symbol
              //string atCharge   (line,(79-1),2); // str, Charge on the atom

	    } catch (std::out_of_range& err) {
	      throw std::runtime_error("Misformated pdb file in atom line # "+ boost::lexical_cast<string>(i));
	    }
            boost::algorithm::trim(atName);
            boost::algorithm::trim(resName);
            boost::algorithm::trim(resNum);
            boost::algorithm::trim(x);
            boost::algorithm::trim(y);
            boost::algorithm::trim(z);

	    i++;
            if(!_topology && i > top.BeadCount())
              throw std::runtime_error("number of beads in topology and trajectory differ");

            Bead *b;
            if(_topology){
	      int resnr;
	      try {
		resnr = boost::lexical_cast<int>(resNum);
	      } catch(bad_lexical_cast &) {
	        throw std::runtime_error("Cannot convert resNum='"+ resNum+"' to int, that usallly means: misformated pdb file");
	      }
              if (resnr < 1)
                throw std::runtime_error("Misformated pdb file, resnr has to be > 0");
	      //TODO: fix the case that resnr is not in ascending order
              if(resnr > top.ResidueCount()) {
                while ((resnr-1)>top.ResidueCount()){ //pdb resnr should start with 1 but accept sloppy files
	          top.CreateResidue("DUMMY"); // create dummy residue, hopefully it will never show
	          cout << "Warning: residue numbers not continous, create DUMMY residue with nr " << top.ResidueCount() << endl;
		}
                top.CreateResidue(resName);
	      }
              //this is not correct, but still better than no type at all!
	      BeadType *type = top.GetOrCreateBeadType(atName);

	      // res -1 as internal number starts with 0
	      b = top.CreateBead(1, atName, type, resnr-1, 1., 0.);
	    } else {
                b = top.getBead(i-1);
	    }
            // convert to nm from A
            b->setPos(vec(
                    boost::lexical_cast<double>(x)/10.0,
                    boost::lexical_cast<double>(y)/10.0,
                    boost::lexical_cast<double>(z)/10.0
                ));

	}

        if (( line == "ENDMDL" ) || ( line == "END" ) || ( _fl.eof())){
          break;
	}
    }

    if(!_topology && (i>0) && i != top.BeadCount())
      throw std::runtime_error("number of beads in topology and trajectory differ");

    if (_topology)
      cout << "WARNING: topology created from .pdb file, charges and masses are wrong!\n";

    return !_fl.eof();
}

}}

<commit_msg>pdbreader: box needs to be scaled as well (A -> nm)<commit_after>/*
 * Copyright 2009-2013 The VOTCA Development Team (http://www.votca.org)
 *
 * 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 <vector>
#include <boost/lexical_cast.hpp>
#include <boost/algorithm/string.hpp>
#include <votca/tools/getline.h>
#include "pdbreader.h"

namespace votca { namespace csg {
    using namespace boost;
using namespace std;

bool PDBReader::ReadTopology(string file,  Topology &top)
{
   _topology = true;
   top.Cleanup();

   _fl.open(file.c_str());
    if(!_fl.is_open())
        throw std::ios_base::failure("Error on open topology file: " + file);

   NextFrame(top);

    _fl.close();

    return true;
}

bool PDBReader::Open(const string &file)
{
    _fl.open(file.c_str());
    if(!_fl.is_open())
        throw std::ios_base::failure("Error on open trajectory file: " + file);
    return true;
}

void PDBReader::Close()
{
    _fl.close();
}

bool PDBReader::FirstFrame(Topology &top)
{
    _topology = false;
    NextFrame(top);
    return true;
}

bool PDBReader::NextFrame(Topology &top)
{
    string line;
    int i = 0 ;
    while ( std::getline(_fl, line) ){
        if( wildcmp("CRYST1*",line.c_str())){
	     string a, b, c, alpha, beta, gamma;
	     try {
               //1 -  6       Record name    "CRYST1"
	       a=string(line,(7-1),9); //7 - 15       Real(9.3)      a (Angstroms)
	       b=string(line,(16-1),9); //16 - 24       Real(9.3)      b (Angstroms)
	       c=string(line,(25-1),9); //25 - 33       Real(9.3)      c (Angstroms)
	       alpha=string(line,(34-1),7); //34 - 40       Real(7.2)      alpha (degrees)
               beta=string(line,(41-1),7); //41 - 47       Real(7.2)      beta (degrees)
	       gamma=string(line,(48-1),7); //48 - 54       Real(7.2)      gamma (degrees)
               //56 - 66       LString        Space group
	       //67 - 70       Integer        Z value
	    } catch (std::out_of_range& err) {
	      throw std::runtime_error("Misformated pdb file in CRYST1 line");
	    }
	    boost::algorithm::trim(a);
	    boost::algorithm::trim(b);
	    boost::algorithm::trim(c);
	    boost::algorithm::trim(alpha);
	    boost::algorithm::trim(beta);
	    boost::algorithm::trim(gamma);
	    if ((!wildcmp("90*",alpha.c_str()))||(!wildcmp("90*",alpha.c_str()))||(!wildcmp("90*",alpha.c_str()))){
	         throw std::runtime_error("Non cubical box in pdb file not implemented, yet!");
            }
	    top.setBox(matrix(vec(boost::lexical_cast<double>(a)/10.0, 0, 0),
	                      vec(0, boost::lexical_cast<double>(b)/10.0, 0),
			      vec(0, 0, boost::lexical_cast<double>(c)/10.0)));

	}
        if( wildcmp("ATOM*",line.c_str()) || wildcmp("HETATM*",line.c_str())){

            //      according to PDB format
	    string x,y,z, resNum, resName, atName;
            try {
	      /* Some pdb don't include all this, read only what we realy need*/
	      /* leave this here in case we need more later*/
              //string recType    (line,( 1-1),6); // str,  "ATOM", "HETATM"
              //string atNum      (line,( 7-1),6); // int,  Atom serial number
              atName=string(line,(13-1),4); // str,  Atom name
              //string atAltLoc   (line,(17-1),1); // char, Alternate location indicator
              resName=string(line,(18-1),3); // str,  Residue name
              //string chainID    (line,(22-1),1); // char, Chain identifier
              resNum=string(line,(23-1),4); // int,  Residue sequence number
              //string atICode    (line,(27-1),1); // char, Code for insertion of res
              x=string(line,(31-1),8); // float 8.3 ,x
              y=string(line,(39-1),8); // float 8.3 ,y
              z=string(line,(47-1),8); // float 8.3 ,z
              //string atOccup    (line,(55-1),6); // float  6.2, Occupancy
              //string atTFactor  (line,(61-1),6); // float  6.2, Temperature factor
              //string segID      (line,(73-1),4); // str, Segment identifier
              //string atElement  (line,(77-1),2); // str, Element symbol
              //string atCharge   (line,(79-1),2); // str, Charge on the atom

	    } catch (std::out_of_range& err) {
	      throw std::runtime_error("Misformated pdb file in atom line # "+ boost::lexical_cast<string>(i));
	    }
            boost::algorithm::trim(atName);
            boost::algorithm::trim(resName);
            boost::algorithm::trim(resNum);
            boost::algorithm::trim(x);
            boost::algorithm::trim(y);
            boost::algorithm::trim(z);

	    i++;
            if(!_topology && i > top.BeadCount())
              throw std::runtime_error("number of beads in topology and trajectory differ");

            Bead *b;
            if(_topology){
	      int resnr;
	      try {
		resnr = boost::lexical_cast<int>(resNum);
	      } catch(bad_lexical_cast &) {
	        throw std::runtime_error("Cannot convert resNum='"+ resNum+"' to int, that usallly means: misformated pdb file");
	      }
              if (resnr < 1)
                throw std::runtime_error("Misformated pdb file, resnr has to be > 0");
	      //TODO: fix the case that resnr is not in ascending order
              if(resnr > top.ResidueCount()) {
                while ((resnr-1)>top.ResidueCount()){ //pdb resnr should start with 1 but accept sloppy files
	          top.CreateResidue("DUMMY"); // create dummy residue, hopefully it will never show
	          cout << "Warning: residue numbers not continous, create DUMMY residue with nr " << top.ResidueCount() << endl;
		}
                top.CreateResidue(resName);
	      }
              //this is not correct, but still better than no type at all!
	      BeadType *type = top.GetOrCreateBeadType(atName);

	      // res -1 as internal number starts with 0
	      b = top.CreateBead(1, atName, type, resnr-1, 1., 0.);
	    } else {
                b = top.getBead(i-1);
	    }
            // convert to nm from A
            b->setPos(vec(
                    boost::lexical_cast<double>(x)/10.0,
                    boost::lexical_cast<double>(y)/10.0,
                    boost::lexical_cast<double>(z)/10.0
                ));

	}

        if (( line == "ENDMDL" ) || ( line == "END" ) || ( _fl.eof())){
          break;
	}
    }

    if(!_topology && (i>0) && i != top.BeadCount())
      throw std::runtime_error("number of beads in topology and trajectory differ");

    if (_topology)
      cout << "WARNING: topology created from .pdb file, charges and masses are wrong!\n";

    return !_fl.eof();
}

}}

<|endoftext|>


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

#include "strings.hrc"
#include "sdresid.hxx"
#include "sdmod.hxx"
#include "sdiocmpt.hxx"
#include "morphdlg.hxx"
#include "morphdlg.hrc"

#ifndef _SV_CONFIG_HXX //autogen
#include <vcl/config.hxx>
#endif
#ifndef SVX_XFILLIT0_HXX //autogen
#include <svx/xfillit0.hxx>
#endif
#ifndef _SVX_XLINEIT0_HXX //autogen
#include <svx/xlineit0.hxx>
#endif
#ifndef _XENUM_HXX //autogen
#include <svx/xenum.hxx>
#endif
#ifndef _SVDOBJ_HXX //autogen
#include <svx/svdobj.hxx>
#endif
#ifndef _SFXITEMSET_HXX //autogen
#include <svtools/itemset.hxx>
#endif
#ifndef _SFXITEMPOOL_HXX //autogen
#include <svtools/itempool.hxx>
#endif

/******************************************************************************/

#define FADE_STEP   "FadeSteps"
#define FADE_ATTRIB "FadeAttributes"
#define FADE_ORIENT "FadeOrientation"
#define FADE_TRUE   "true"
#define FADE_FALSE  "false"

/******************************************************************************/

/******************************************************************************
|*
|*
|*
\******************************************************************************/

SdMorphDlg::SdMorphDlg( Window* pParent, const SdrObject* pObj1, const SdrObject* pObj2 ) :
            ModalDialog     ( pParent, SdResId( DLG_MORPH ) ),
            aBtnOK          ( this, SdResId( BTN_OK ) ),
            aBtnCancel      ( this, SdResId( BTN_CANCEL ) ),
            aBtnHelp        ( this, SdResId( BTN_HELP ) ),
            aGrpPreset      ( this, SdResId( GRP_PRESET ) ),
            aFtSteps        ( this, SdResId( FT_STEPS ) ),
            aMtfSteps       ( this, SdResId( MTF_STEPS ) ),
            aCbxAttributes  ( this, SdResId( CBX_ATTRIBUTES ) ),
            aCbxOrientation ( this, SdResId( CBX_ORIENTATION ) )
{
    FreeResource();
    LoadSettings();

    SfxItemPool*    pPool = (SfxItemPool*) pObj1->GetItemPool();
    SfxItemSet      aSet1( *pPool );
    SfxItemSet      aSet2( *pPool );

    aSet1.Put(pObj1->GetMergedItemSet());
    aSet2.Put(pObj2->GetMergedItemSet());

    const XLineStyle    eLineStyle1 = ( (const XLineStyleItem&) aSet1.Get( XATTR_LINESTYLE ) ).GetValue();
    const XLineStyle    eLineStyle2 = ( (const XLineStyleItem&) aSet2.Get( XATTR_LINESTYLE ) ).GetValue();
    const XFillStyle    eFillStyle1 = ( (const XFillStyleItem&) aSet1.Get( XATTR_FILLSTYLE ) ).GetValue();
    const XFillStyle    eFillStyle2 = ( (const XFillStyleItem&) aSet2.Get( XATTR_FILLSTYLE ) ).GetValue();

    if ( ( ( eLineStyle1 == XLINE_NONE ) || ( eLineStyle2 == XLINE_NONE ) ) &&
         ( ( eFillStyle1 != XFILL_SOLID ) || ( eFillStyle2 != XFILL_SOLID ) ) )
    {
        aCbxAttributes.Disable();
    }
}

/******************************************************************************
|*
|*
|*
\******************************************************************************/

SdMorphDlg::~SdMorphDlg()
{
}

/******************************************************************************
|*
|*
|*
\******************************************************************************/

void SdMorphDlg::LoadSettings()
{
    SvStorageStreamRef  xIStm( SD_MOD()->GetOptionStream( UniString::CreateFromAscii(
                               RTL_CONSTASCII_STRINGPARAM( SD_OPTION_MORPHING ) ),
                               SD_OPTION_LOAD ) );
    UINT16              nSteps;
    BOOL                bOrient, bAttrib;

    if( xIStm.Is() )
    {
        SdIOCompat aCompat( *xIStm, STREAM_READ );

        *xIStm >> nSteps >> bOrient >> bAttrib;
    }
    else
    {
        nSteps = 16;
        bOrient = bAttrib = TRUE;
    }

    aMtfSteps.SetValue( nSteps );
    aCbxOrientation.Check( bOrient );
    aCbxAttributes.Check( bAttrib );
}

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

void SdMorphDlg::SaveSettings() const
{
    SvStorageStreamRef xOStm( SD_MOD()->GetOptionStream( UniString::CreateFromAscii(
                               RTL_CONSTASCII_STRINGPARAM( SD_OPTION_MORPHING ) ),
                               SD_OPTION_STORE ) );

    if( xOStm.Is() )
    {
        SdIOCompat aCompat( *xOStm, STREAM_WRITE, 1 );

        *xOStm << (UINT16) aMtfSteps.GetValue()
               << aCbxOrientation.IsChecked()
               << aCbxAttributes.IsChecked();
    }
}

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

#include "strings.hrc"
#include "sdresid.hxx"
#include "sdmod.hxx"
#include "sdiocmpt.hxx"
#include "morphdlg.hxx"
#include "morphdlg.hrc"

#ifndef _CONFIG_HXX
#include <tools/config.hxx>
#endif
#ifndef SVX_XFILLIT0_HXX //autogen
#include <svx/xfillit0.hxx>
#endif
#ifndef _SVX_XLINEIT0_HXX //autogen
#include <svx/xlineit0.hxx>
#endif
#ifndef _XENUM_HXX //autogen
#include <svx/xenum.hxx>
#endif
#ifndef _SVDOBJ_HXX //autogen
#include <svx/svdobj.hxx>
#endif
#ifndef _SFXITEMSET_HXX //autogen
#include <svtools/itemset.hxx>
#endif
#ifndef _SFXITEMPOOL_HXX //autogen
#include <svtools/itempool.hxx>
#endif

/******************************************************************************/

#define FADE_STEP   "FadeSteps"
#define FADE_ATTRIB "FadeAttributes"
#define FADE_ORIENT "FadeOrientation"
#define FADE_TRUE   "true"
#define FADE_FALSE  "false"

/******************************************************************************/

/******************************************************************************
|*
|*
|*
\******************************************************************************/

SdMorphDlg::SdMorphDlg( Window* pParent, const SdrObject* pObj1, const SdrObject* pObj2 ) :
            ModalDialog     ( pParent, SdResId( DLG_MORPH ) ),
            aBtnOK          ( this, SdResId( BTN_OK ) ),
            aBtnCancel      ( this, SdResId( BTN_CANCEL ) ),
            aBtnHelp        ( this, SdResId( BTN_HELP ) ),
            aGrpPreset      ( this, SdResId( GRP_PRESET ) ),
            aFtSteps        ( this, SdResId( FT_STEPS ) ),
            aMtfSteps       ( this, SdResId( MTF_STEPS ) ),
            aCbxAttributes  ( this, SdResId( CBX_ATTRIBUTES ) ),
            aCbxOrientation ( this, SdResId( CBX_ORIENTATION ) )
{
    FreeResource();
    LoadSettings();

    SfxItemPool*    pPool = (SfxItemPool*) pObj1->GetItemPool();
    SfxItemSet      aSet1( *pPool );
    SfxItemSet      aSet2( *pPool );

    aSet1.Put(pObj1->GetMergedItemSet());
    aSet2.Put(pObj2->GetMergedItemSet());

    const XLineStyle    eLineStyle1 = ( (const XLineStyleItem&) aSet1.Get( XATTR_LINESTYLE ) ).GetValue();
    const XLineStyle    eLineStyle2 = ( (const XLineStyleItem&) aSet2.Get( XATTR_LINESTYLE ) ).GetValue();
    const XFillStyle    eFillStyle1 = ( (const XFillStyleItem&) aSet1.Get( XATTR_FILLSTYLE ) ).GetValue();
    const XFillStyle    eFillStyle2 = ( (const XFillStyleItem&) aSet2.Get( XATTR_FILLSTYLE ) ).GetValue();

    if ( ( ( eLineStyle1 == XLINE_NONE ) || ( eLineStyle2 == XLINE_NONE ) ) &&
         ( ( eFillStyle1 != XFILL_SOLID ) || ( eFillStyle2 != XFILL_SOLID ) ) )
    {
        aCbxAttributes.Disable();
    }
}

/******************************************************************************
|*
|*
|*
\******************************************************************************/

SdMorphDlg::~SdMorphDlg()
{
}

/******************************************************************************
|*
|*
|*
\******************************************************************************/

void SdMorphDlg::LoadSettings()
{
    SvStorageStreamRef  xIStm( SD_MOD()->GetOptionStream( UniString::CreateFromAscii(
                               RTL_CONSTASCII_STRINGPARAM( SD_OPTION_MORPHING ) ),
                               SD_OPTION_LOAD ) );
    UINT16              nSteps;
    BOOL                bOrient, bAttrib;

    if( xIStm.Is() )
    {
        SdIOCompat aCompat( *xIStm, STREAM_READ );

        *xIStm >> nSteps >> bOrient >> bAttrib;
    }
    else
    {
        nSteps = 16;
        bOrient = bAttrib = TRUE;
    }

    aMtfSteps.SetValue( nSteps );
    aCbxOrientation.Check( bOrient );
    aCbxAttributes.Check( bAttrib );
}

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

void SdMorphDlg::SaveSettings() const
{
    SvStorageStreamRef xOStm( SD_MOD()->GetOptionStream( UniString::CreateFromAscii(
                               RTL_CONSTASCII_STRINGPARAM( SD_OPTION_MORPHING ) ),
                               SD_OPTION_STORE ) );

    if( xOStm.Is() )
    {
        SdIOCompat aCompat( *xOStm, STREAM_WRITE, 1 );

        *xOStm << (UINT16) aMtfSteps.GetValue()
               << aCbxOrientation.IsChecked()
               << aCbxAttributes.IsChecked();
    }
}

<|endoftext|>


<commit_before>#include "archive.hh"
#include "binary-cache-store.hh"
#include "compression.hh"
#include "derivations.hh"
#include "fs-accessor.hh"
#include "globals.hh"
#include "nar-info.hh"
#include "sync.hh"
#include "remote-fs-accessor.hh"
#include "nar-info-disk-cache.hh"
#include "nar-accessor.hh"
#include "json.hh"

#include <chrono>

#include <future>

namespace nix {

BinaryCacheStore::BinaryCacheStore(const Params & params)
    : Store(params)
{
    if (secretKeyFile != "")
        secretKey = std::unique_ptr<SecretKey>(new SecretKey(readFile(secretKeyFile)));

    StringSink sink;
    sink << narVersionMagic1;
    narMagic = *sink.s;
}

void BinaryCacheStore::init()
{
    std::string cacheInfoFile = "nix-cache-info";

    auto cacheInfo = getFile(cacheInfoFile);
    if (!cacheInfo) {
        upsertFile(cacheInfoFile, "StoreDir: " + storeDir + "\n", "text/x-nix-cache-info");
    } else {
        for (auto & line : tokenizeString<Strings>(*cacheInfo, "\n")) {
            size_t colon = line.find(':');
            if (colon == std::string::npos) continue;
            auto name = line.substr(0, colon);
            auto value = trim(line.substr(colon + 1, std::string::npos));
            if (name == "StoreDir") {
                if (value != storeDir)
                    throw Error(format("binary cache '%s' is for Nix stores with prefix '%s', not '%s'")
                        % getUri() % value % storeDir);
            } else if (name == "WantMassQuery") {
                wantMassQuery_ = value == "1";
            } else if (name == "Priority") {
                string2Int(value, priority);
            }
        }
    }
}

void BinaryCacheStore::getFile(const std::string & path,
    Callback<std::shared_ptr<std::string>> callback)
{
    try {
        callback(getFile(path));
    } catch (...) { callback.rethrow(); }
}

void BinaryCacheStore::getFile(const std::string & path, Sink & sink)
{
    std::promise<std::shared_ptr<std::string>> promise;
    getFile(path,
        {[&](std::future<std::shared_ptr<std::string>> result) {
            try {
                promise.set_value(result.get());
            } catch (...) {
                promise.set_exception(std::current_exception());
            }
        }});
    auto data = promise.get_future().get();
    sink((unsigned char *) data->data(), data->size());
}

std::shared_ptr<std::string> BinaryCacheStore::getFile(const std::string & path)
{
    StringSink sink;
    try {
        getFile(path, sink);
    } catch (NoSuchBinaryCacheFile &) {
        return nullptr;
    }
    return sink.s;
}

Path BinaryCacheStore::narInfoFileFor(const Path & storePath)
{
    assertStorePath(storePath);
    return storePathToHash(storePath) + ".narinfo";
}

void BinaryCacheStore::writeNarInfo(ref<NarInfo> narInfo)
{
    auto narInfoFile = narInfoFileFor(narInfo->path);

    upsertFile(narInfoFile, narInfo->to_string(), "text/x-nix-narinfo");

    auto hashPart = storePathToHash(narInfo->path);

    {
        auto state_(state.lock());
        state_->pathInfoCache.upsert(hashPart, std::shared_ptr<NarInfo>(narInfo));
    }

    if (diskCache)
        diskCache->upsertNarInfo(getUri(), hashPart, std::shared_ptr<NarInfo>(narInfo));
}

void BinaryCacheStore::addToStore(const ValidPathInfo & info, const ref<std::string> & nar,
    RepairFlag repair, CheckSigsFlag checkSigs, std::shared_ptr<FSAccessor> accessor)
{
    if (!repair && isValidPath(info.path)) return;

    /* Verify that all references are valid. This may do some .narinfo
       reads, but typically they'll already be cached. */
    for (auto & ref : info.references)
        try {
            if (ref != info.path)
                queryPathInfo(ref);
        } catch (InvalidPath &) {
            throw Error(format("cannot add '%s' to the binary cache because the reference '%s' is not valid")
                % info.path % ref);
        }

    assert(nar->compare(0, narMagic.size(), narMagic) == 0);

    auto narInfo = make_ref<NarInfo>(info);

    narInfo->narSize = nar->size();
    narInfo->narHash = hashString(htSHA256, *nar);

    if (info.narHash && info.narHash != narInfo->narHash)
        throw Error(format("refusing to copy corrupted path '%1%' to binary cache") % info.path);

    auto accessor_ = std::dynamic_pointer_cast<RemoteFSAccessor>(accessor);

    /* Optionally write a JSON file containing a listing of the
       contents of the NAR. */
    if (writeNARListing) {
        std::ostringstream jsonOut;

        {
            JSONObject jsonRoot(jsonOut);
            jsonRoot.attr("version", 1);

            auto narAccessor = makeNarAccessor(nar);

            if (accessor_)
                accessor_->addToCache(info.path, *nar, narAccessor);

            {
                auto res = jsonRoot.placeholder("root");
                listNar(res, narAccessor, "", true);
            }
        }

        upsertFile(storePathToHash(info.path) + ".ls", jsonOut.str(), "application/json");
    }

    else {
        if (accessor_)
            accessor_->addToCache(info.path, *nar, makeNarAccessor(nar));
    }

    /* Compress the NAR. */
    narInfo->compression = compression;
    auto now1 = std::chrono::steady_clock::now();
    auto narCompressed = compress(compression, *nar, parallelCompression);
    auto now2 = std::chrono::steady_clock::now();
    narInfo->fileHash = hashString(htSHA256, *narCompressed);
    narInfo->fileSize = narCompressed->size();

    auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(now2 - now1).count();
    printMsg(lvlTalkative, format("copying path '%1%' (%2% bytes, compressed %3$.1f%% in %4% ms) to binary cache")
        % narInfo->path % narInfo->narSize
        % ((1.0 - (double) narCompressed->size() / nar->size()) * 100.0)
        % duration);

    /* Atomically write the NAR file. */
    narInfo->url = "nar/" + narInfo->fileHash.to_string(Base32, false) + ".nar"
        + (compression == "xz" ? ".xz" :
           compression == "bzip2" ? ".bz2" :
           compression == "br" ? ".br" :
           "");
    if (repair || !fileExists(narInfo->url)) {
        stats.narWrite++;
        upsertFile(narInfo->url, *narCompressed, "application/x-nix-nar");
    } else
        stats.narWriteAverted++;

    stats.narWriteBytes += nar->size();
    stats.narWriteCompressedBytes += narCompressed->size();
    stats.narWriteCompressionTimeMs += duration;

    /* Atomically write the NAR info file.*/
    if (secretKey) narInfo->sign(*secretKey);

    writeNarInfo(narInfo);

    stats.narInfoWrite++;
}

bool BinaryCacheStore::isValidPathUncached(const Path & storePath)
{
    // FIXME: this only checks whether a .narinfo with a matching hash
    // part exists. So ‘f4kb...-foo’ matches ‘f4kb...-bar’, even
    // though they shouldn't. Not easily fixed.
    return fileExists(narInfoFileFor(storePath));
}

void BinaryCacheStore::narFromPath(const Path & storePath, Sink & sink)
{
    auto info = queryPathInfo(storePath).cast<const NarInfo>();

    uint64_t narSize = 0;

    LambdaSink wrapperSink([&](const unsigned char * data, size_t len) {
        sink(data, len);
        narSize += len;
    });

    auto decompressor = makeDecompressionSink(info->compression, wrapperSink);

    try {
        getFile(info->url, *decompressor);
    } catch (NoSuchBinaryCacheFile & e) {
        throw SubstituteGone(e.what());
    }

    decompressor->flush();

    stats.narRead++;
    //stats.narReadCompressedBytes += nar->size(); // FIXME
    stats.narReadBytes += narSize;
}

void BinaryCacheStore::queryPathInfoUncached(const Path & storePath,
    Callback<std::shared_ptr<ValidPathInfo>> callback)
{
    auto uri = getUri();
    auto act = std::make_shared<Activity>(*logger, lvlTalkative, actQueryPathInfo,
        fmt("querying info about '%s' on '%s'", storePath, uri), Logger::Fields{storePath, uri});
    PushActivity pact(act->id);

    auto narInfoFile = narInfoFileFor(storePath);

    getFile(narInfoFile,
        {[=](std::future<std::shared_ptr<std::string>> fut) {
            try {
                auto data = fut.get();

                if (!data) return callback(nullptr);

                stats.narInfoRead++;

                callback((std::shared_ptr<ValidPathInfo>)
                    std::make_shared<NarInfo>(*this, *data, narInfoFile));

                (void) act; // force Activity into this lambda to ensure it stays alive
            } catch (...) {
                callback.rethrow();
            }
        }});
}

Path BinaryCacheStore::addToStore(const string & name, const Path & srcPath,
    bool recursive, HashType hashAlgo, PathFilter & filter, RepairFlag repair)
{
    // FIXME: some cut&paste from LocalStore::addToStore().

    /* Read the whole path into memory. This is not a very scalable
       method for very large paths, but `copyPath' is mainly used for
       small files. */
    StringSink sink;
    Hash h;
    if (recursive) {
        dumpPath(srcPath, sink, filter);
        h = hashString(hashAlgo, *sink.s);
    } else {
        auto s = readFile(srcPath);
        dumpString(s, sink);
        h = hashString(hashAlgo, s);
    }

    ValidPathInfo info;
    info.path = makeFixedOutputPath(recursive, h, name);

    addToStore(info, sink.s, repair, CheckSigs, nullptr);

    return info.path;
}

Path BinaryCacheStore::addTextToStore(const string & name, const string & s,
    const PathSet & references, RepairFlag repair)
{
    ValidPathInfo info;
    info.path = computeStorePathForText(name, s, references);
    info.references = references;

    if (repair || !isValidPath(info.path)) {
        StringSink sink;
        dumpString(s, sink);
        addToStore(info, sink.s, repair, CheckSigs, nullptr);
    }

    return info.path;
}

ref<FSAccessor> BinaryCacheStore::getFSAccessor()
{
    return make_ref<RemoteFSAccessor>(ref<Store>(shared_from_this()), localNarCache);
}

void BinaryCacheStore::addSignatures(const Path & storePath, const StringSet & sigs)
{
    /* Note: this is inherently racy since there is no locking on
       binary caches. In particular, with S3 this unreliable, even
       when addSignatures() is called sequentially on a path, because
       S3 might return an outdated cached version. */

    auto narInfo = make_ref<NarInfo>((NarInfo &) *queryPathInfo(storePath));

    narInfo->sigs.insert(sigs.begin(), sigs.end());

    auto narInfoFile = narInfoFileFor(narInfo->path);

    writeNarInfo(narInfo);
}

std::shared_ptr<std::string> BinaryCacheStore::getBuildLog(const Path & path)
{
    Path drvPath;

    if (isDerivation(path))
        drvPath = path;
    else {
        try {
            auto info = queryPathInfo(path);
            // FIXME: add a "Log" field to .narinfo
            if (info->deriver == "") return nullptr;
            drvPath = info->deriver;
        } catch (InvalidPath &) {
            return nullptr;
        }
    }

    auto logPath = "log/" + baseNameOf(drvPath);

    debug("fetching build log from binary cache '%s/%s'", getUri(), logPath);

    return getFile(logPath);
}

}
<commit_msg>Fix another 'coroutine has finished' during decompression<commit_after>#include "archive.hh"
#include "binary-cache-store.hh"
#include "compression.hh"
#include "derivations.hh"
#include "fs-accessor.hh"
#include "globals.hh"
#include "nar-info.hh"
#include "sync.hh"
#include "remote-fs-accessor.hh"
#include "nar-info-disk-cache.hh"
#include "nar-accessor.hh"
#include "json.hh"

#include <chrono>

#include <future>

namespace nix {

BinaryCacheStore::BinaryCacheStore(const Params & params)
    : Store(params)
{
    if (secretKeyFile != "")
        secretKey = std::unique_ptr<SecretKey>(new SecretKey(readFile(secretKeyFile)));

    StringSink sink;
    sink << narVersionMagic1;
    narMagic = *sink.s;
}

void BinaryCacheStore::init()
{
    std::string cacheInfoFile = "nix-cache-info";

    auto cacheInfo = getFile(cacheInfoFile);
    if (!cacheInfo) {
        upsertFile(cacheInfoFile, "StoreDir: " + storeDir + "\n", "text/x-nix-cache-info");
    } else {
        for (auto & line : tokenizeString<Strings>(*cacheInfo, "\n")) {
            size_t colon = line.find(':');
            if (colon == std::string::npos) continue;
            auto name = line.substr(0, colon);
            auto value = trim(line.substr(colon + 1, std::string::npos));
            if (name == "StoreDir") {
                if (value != storeDir)
                    throw Error(format("binary cache '%s' is for Nix stores with prefix '%s', not '%s'")
                        % getUri() % value % storeDir);
            } else if (name == "WantMassQuery") {
                wantMassQuery_ = value == "1";
            } else if (name == "Priority") {
                string2Int(value, priority);
            }
        }
    }
}

void BinaryCacheStore::getFile(const std::string & path,
    Callback<std::shared_ptr<std::string>> callback)
{
    try {
        callback(getFile(path));
    } catch (...) { callback.rethrow(); }
}

void BinaryCacheStore::getFile(const std::string & path, Sink & sink)
{
    std::promise<std::shared_ptr<std::string>> promise;
    getFile(path,
        {[&](std::future<std::shared_ptr<std::string>> result) {
            try {
                promise.set_value(result.get());
            } catch (...) {
                promise.set_exception(std::current_exception());
            }
        }});
    auto data = promise.get_future().get();
    sink((unsigned char *) data->data(), data->size());
}

std::shared_ptr<std::string> BinaryCacheStore::getFile(const std::string & path)
{
    StringSink sink;
    try {
        getFile(path, sink);
    } catch (NoSuchBinaryCacheFile &) {
        return nullptr;
    }
    return sink.s;
}

Path BinaryCacheStore::narInfoFileFor(const Path & storePath)
{
    assertStorePath(storePath);
    return storePathToHash(storePath) + ".narinfo";
}

void BinaryCacheStore::writeNarInfo(ref<NarInfo> narInfo)
{
    auto narInfoFile = narInfoFileFor(narInfo->path);

    upsertFile(narInfoFile, narInfo->to_string(), "text/x-nix-narinfo");

    auto hashPart = storePathToHash(narInfo->path);

    {
        auto state_(state.lock());
        state_->pathInfoCache.upsert(hashPart, std::shared_ptr<NarInfo>(narInfo));
    }

    if (diskCache)
        diskCache->upsertNarInfo(getUri(), hashPart, std::shared_ptr<NarInfo>(narInfo));
}

void BinaryCacheStore::addToStore(const ValidPathInfo & info, const ref<std::string> & nar,
    RepairFlag repair, CheckSigsFlag checkSigs, std::shared_ptr<FSAccessor> accessor)
{
    if (!repair && isValidPath(info.path)) return;

    /* Verify that all references are valid. This may do some .narinfo
       reads, but typically they'll already be cached. */
    for (auto & ref : info.references)
        try {
            if (ref != info.path)
                queryPathInfo(ref);
        } catch (InvalidPath &) {
            throw Error(format("cannot add '%s' to the binary cache because the reference '%s' is not valid")
                % info.path % ref);
        }

    assert(nar->compare(0, narMagic.size(), narMagic) == 0);

    auto narInfo = make_ref<NarInfo>(info);

    narInfo->narSize = nar->size();
    narInfo->narHash = hashString(htSHA256, *nar);

    if (info.narHash && info.narHash != narInfo->narHash)
        throw Error(format("refusing to copy corrupted path '%1%' to binary cache") % info.path);

    auto accessor_ = std::dynamic_pointer_cast<RemoteFSAccessor>(accessor);

    /* Optionally write a JSON file containing a listing of the
       contents of the NAR. */
    if (writeNARListing) {
        std::ostringstream jsonOut;

        {
            JSONObject jsonRoot(jsonOut);
            jsonRoot.attr("version", 1);

            auto narAccessor = makeNarAccessor(nar);

            if (accessor_)
                accessor_->addToCache(info.path, *nar, narAccessor);

            {
                auto res = jsonRoot.placeholder("root");
                listNar(res, narAccessor, "", true);
            }
        }

        upsertFile(storePathToHash(info.path) + ".ls", jsonOut.str(), "application/json");
    }

    else {
        if (accessor_)
            accessor_->addToCache(info.path, *nar, makeNarAccessor(nar));
    }

    /* Compress the NAR. */
    narInfo->compression = compression;
    auto now1 = std::chrono::steady_clock::now();
    auto narCompressed = compress(compression, *nar, parallelCompression);
    auto now2 = std::chrono::steady_clock::now();
    narInfo->fileHash = hashString(htSHA256, *narCompressed);
    narInfo->fileSize = narCompressed->size();

    auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(now2 - now1).count();
    printMsg(lvlTalkative, format("copying path '%1%' (%2% bytes, compressed %3$.1f%% in %4% ms) to binary cache")
        % narInfo->path % narInfo->narSize
        % ((1.0 - (double) narCompressed->size() / nar->size()) * 100.0)
        % duration);

    /* Atomically write the NAR file. */
    narInfo->url = "nar/" + narInfo->fileHash.to_string(Base32, false) + ".nar"
        + (compression == "xz" ? ".xz" :
           compression == "bzip2" ? ".bz2" :
           compression == "br" ? ".br" :
           "");
    if (repair || !fileExists(narInfo->url)) {
        stats.narWrite++;
        upsertFile(narInfo->url, *narCompressed, "application/x-nix-nar");
    } else
        stats.narWriteAverted++;

    stats.narWriteBytes += nar->size();
    stats.narWriteCompressedBytes += narCompressed->size();
    stats.narWriteCompressionTimeMs += duration;

    /* Atomically write the NAR info file.*/
    if (secretKey) narInfo->sign(*secretKey);

    writeNarInfo(narInfo);

    stats.narInfoWrite++;
}

bool BinaryCacheStore::isValidPathUncached(const Path & storePath)
{
    // FIXME: this only checks whether a .narinfo with a matching hash
    // part exists. So ‘f4kb...-foo’ matches ‘f4kb...-bar’, even
    // though they shouldn't. Not easily fixed.
    return fileExists(narInfoFileFor(storePath));
}

void BinaryCacheStore::narFromPath(const Path & storePath, Sink & sink)
{
    auto info = queryPathInfo(storePath).cast<const NarInfo>();

    uint64_t narSize = 0;

    LambdaSink wrapperSink([&](const unsigned char * data, size_t len) {
        sink(data, len);
        narSize += len;
    });

    auto decompressor = makeDecompressionSink(info->compression, wrapperSink);

    try {
        getFile(info->url, *decompressor);
    } catch (NoSuchBinaryCacheFile & e) {
        throw SubstituteGone(e.what());
    }

    decompressor->finish();

    stats.narRead++;
    //stats.narReadCompressedBytes += nar->size(); // FIXME
    stats.narReadBytes += narSize;
}

void BinaryCacheStore::queryPathInfoUncached(const Path & storePath,
    Callback<std::shared_ptr<ValidPathInfo>> callback)
{
    auto uri = getUri();
    auto act = std::make_shared<Activity>(*logger, lvlTalkative, actQueryPathInfo,
        fmt("querying info about '%s' on '%s'", storePath, uri), Logger::Fields{storePath, uri});
    PushActivity pact(act->id);

    auto narInfoFile = narInfoFileFor(storePath);

    getFile(narInfoFile,
        {[=](std::future<std::shared_ptr<std::string>> fut) {
            try {
                auto data = fut.get();

                if (!data) return callback(nullptr);

                stats.narInfoRead++;

                callback((std::shared_ptr<ValidPathInfo>)
                    std::make_shared<NarInfo>(*this, *data, narInfoFile));

                (void) act; // force Activity into this lambda to ensure it stays alive
            } catch (...) {
                callback.rethrow();
            }
        }});
}

Path BinaryCacheStore::addToStore(const string & name, const Path & srcPath,
    bool recursive, HashType hashAlgo, PathFilter & filter, RepairFlag repair)
{
    // FIXME: some cut&paste from LocalStore::addToStore().

    /* Read the whole path into memory. This is not a very scalable
       method for very large paths, but `copyPath' is mainly used for
       small files. */
    StringSink sink;
    Hash h;
    if (recursive) {
        dumpPath(srcPath, sink, filter);
        h = hashString(hashAlgo, *sink.s);
    } else {
        auto s = readFile(srcPath);
        dumpString(s, sink);
        h = hashString(hashAlgo, s);
    }

    ValidPathInfo info;
    info.path = makeFixedOutputPath(recursive, h, name);

    addToStore(info, sink.s, repair, CheckSigs, nullptr);

    return info.path;
}

Path BinaryCacheStore::addTextToStore(const string & name, const string & s,
    const PathSet & references, RepairFlag repair)
{
    ValidPathInfo info;
    info.path = computeStorePathForText(name, s, references);
    info.references = references;

    if (repair || !isValidPath(info.path)) {
        StringSink sink;
        dumpString(s, sink);
        addToStore(info, sink.s, repair, CheckSigs, nullptr);
    }

    return info.path;
}

ref<FSAccessor> BinaryCacheStore::getFSAccessor()
{
    return make_ref<RemoteFSAccessor>(ref<Store>(shared_from_this()), localNarCache);
}

void BinaryCacheStore::addSignatures(const Path & storePath, const StringSet & sigs)
{
    /* Note: this is inherently racy since there is no locking on
       binary caches. In particular, with S3 this unreliable, even
       when addSignatures() is called sequentially on a path, because
       S3 might return an outdated cached version. */

    auto narInfo = make_ref<NarInfo>((NarInfo &) *queryPathInfo(storePath));

    narInfo->sigs.insert(sigs.begin(), sigs.end());

    auto narInfoFile = narInfoFileFor(narInfo->path);

    writeNarInfo(narInfo);
}

std::shared_ptr<std::string> BinaryCacheStore::getBuildLog(const Path & path)
{
    Path drvPath;

    if (isDerivation(path))
        drvPath = path;
    else {
        try {
            auto info = queryPathInfo(path);
            // FIXME: add a "Log" field to .narinfo
            if (info->deriver == "") return nullptr;
            drvPath = info->deriver;
        } catch (InvalidPath &) {
            return nullptr;
        }
    }

    auto logPath = "log/" + baseNameOf(drvPath);

    debug("fetching build log from binary cache '%s/%s'", getUri(), logPath);

    return getFile(logPath);
}

}
<|endoftext|>


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

#pragma hdrstop

#include "unmovss.hxx"
#include "docshell.hxx"
#include "drawdoc.hxx"
#include "stlsheet.hxx"

TYPEINIT1(SdMoveStyleSheetsUndoAction, SdUndoAction);

/*************************************************************************
|*
|* Konstruktor
|*
\************************************************************************/

SdMoveStyleSheetsUndoAction::SdMoveStyleSheetsUndoAction(
                                SdDrawDocument* pTheDoc,
                                List*           pTheStyles,
                                BOOL            bInserted):
                      SdUndoAction(pTheDoc)
{
    DBG_ASSERT(pTheStyles, "keine Liste gesetzt!");
    pStyles   = pTheStyles;
    bMySheets = !bInserted;

    pListOfChildLists = new List;

    // Liste mit den Listen der StyleSheet-Kinder erstellen
    for (SdStyleSheet* pSheet = (SdStyleSheet*)pStyles->First();
         pSheet;
         pSheet = (SdStyleSheet*)pStyles->Next())
    {
        List* pChildList = pSheet->CreateChildList();
        pListOfChildLists->Insert(pChildList, LIST_APPEND);
    }
}

/*************************************************************************
|*
|* Undo()
|*
\************************************************************************/

void SdMoveStyleSheetsUndoAction::Undo()
{
    SfxStyleSheetBasePool* pPool  = pDoc->GetStyleSheetPool();
    SdStyleSheet*          pSheet = NULL;

    /********************************************************************
    |* die StyleSheets sollen wieder in den Pool eingefuegt werden
    \*******************************************************************/
    if (bMySheets)
    {
        /****************************************************************
        |* erst alle StyleSheets wieder in den Pool einfuegen
        \***************************************************************/
        for (pSheet = (SdStyleSheet*)pStyles->First();
             pSheet;
             pSheet = (SdStyleSheet*)pStyles->Next())
        {
            pPool->Insert(pSheet);
        }

        /****************************************************************
        |* jetzt die ehemaligen Kinder wieder zu Kindern machen
        \***************************************************************/
        List* pChildList = (List*)pListOfChildLists->First();
        for (pSheet = (SdStyleSheet*)pStyles->First();
             pSheet;
             pSheet = (SdStyleSheet*)pStyles->Next())
        {
            String aParent(pSheet->GetName());
            for (SfxStyleSheet* pChild = (SfxStyleSheet*)pChildList->First();
                 pChild;
                 pChild = (SfxStyleSheet*)pChildList->Next())
            {
                pChild->SetParent(aParent);
            }
            pChildList = (List*)pListOfChildLists->Next();
        }
    }
    /********************************************************************
    |* die StyleSheets sollen wieder aus dem, Pool entfernt werden
    \*******************************************************************/
    else
    {
        for (pSheet = (SdStyleSheet*)pStyles->First();
             pSheet;
             pSheet = (SdStyleSheet*)pStyles->Next())
        {
            pPool->Remove(pSheet);
        }
    }
    bMySheets = !bMySheets;
}

/*************************************************************************
|*
|* Redo()
|*
\************************************************************************/

void SdMoveStyleSheetsUndoAction::Redo()
{
    Undo();
}

/*************************************************************************
|*
|* Repeat()
|*
\************************************************************************/

void SdMoveStyleSheetsUndoAction::Repeat()
{
    DBG_ASSERT(FALSE, "SdMoveStyleSheetsUndoAction::Repeat: nicht implementiert");
}

/*************************************************************************
|*
|* Destruktor, Liste loeschen; ggfs. die enthaltenen StyleSheets loeschen
|*
\************************************************************************/

SdMoveStyleSheetsUndoAction::~SdMoveStyleSheetsUndoAction()
{
    if (bMySheets)
    {
        // die Liste rueckwaerts aufdroeseln; wenn Gliederungsvorlagen ent-
        // halten sind gewaehrleistet dies den geringsten Broadcasting-Aufwand
        SfxStyleSheet* pSheet = (SfxStyleSheet*)pStyles->Last();
        while (pSheet)
        {
            delete pSheet;
            pSheet = (SfxStyleSheet*)pStyles->Prev();
        }
    }
    delete pStyles;

    for (List* pChildList = (List*)pListOfChildLists->First();
         pChildList;
         pChildList = (List*)pListOfChildLists->Next())
    {
        delete pChildList;
    }
    delete pListOfChildLists;
}

/*************************************************************************
|*
|* Kommentar liefern
|*
\************************************************************************/

String SdMoveStyleSheetsUndoAction::GetComment() const
{
    return String();
}

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

#pragma hdrstop

#include "unmovss.hxx"
#include "DrawDocShell.hxx"
#include "drawdoc.hxx"
#include "stlsheet.hxx"

TYPEINIT1(SdMoveStyleSheetsUndoAction, SdUndoAction);

/*************************************************************************
|*
|* Konstruktor
|*
\************************************************************************/

SdMoveStyleSheetsUndoAction::SdMoveStyleSheetsUndoAction(
                                SdDrawDocument* pTheDoc,
                                List*           pTheStyles,
                                BOOL            bInserted):
                      SdUndoAction(pTheDoc)
{
    DBG_ASSERT(pTheStyles, "keine Liste gesetzt!");
    pStyles   = pTheStyles;
    bMySheets = !bInserted;

    pListOfChildLists = new List;

    // Liste mit den Listen der StyleSheet-Kinder erstellen
    for (SdStyleSheet* pSheet = (SdStyleSheet*)pStyles->First();
         pSheet;
         pSheet = (SdStyleSheet*)pStyles->Next())
    {
        List* pChildList = pSheet->CreateChildList();
        pListOfChildLists->Insert(pChildList, LIST_APPEND);
    }
}

/*************************************************************************
|*
|* Undo()
|*
\************************************************************************/

void SdMoveStyleSheetsUndoAction::Undo()
{
    SfxStyleSheetBasePool* pPool  = pDoc->GetStyleSheetPool();
    SdStyleSheet*          pSheet = NULL;

    /********************************************************************
    |* die StyleSheets sollen wieder in den Pool eingefuegt werden
    \*******************************************************************/
    if (bMySheets)
    {
        /****************************************************************
        |* erst alle StyleSheets wieder in den Pool einfuegen
        \***************************************************************/
        for (pSheet = (SdStyleSheet*)pStyles->First();
             pSheet;
             pSheet = (SdStyleSheet*)pStyles->Next())
        {
            pPool->Insert(pSheet);
        }

        /****************************************************************
        |* jetzt die ehemaligen Kinder wieder zu Kindern machen
        \***************************************************************/
        List* pChildList = (List*)pListOfChildLists->First();
        for (pSheet = (SdStyleSheet*)pStyles->First();
             pSheet;
             pSheet = (SdStyleSheet*)pStyles->Next())
        {
            String aParent(pSheet->GetName());
            for (SfxStyleSheet* pChild = (SfxStyleSheet*)pChildList->First();
                 pChild;
                 pChild = (SfxStyleSheet*)pChildList->Next())
            {
                pChild->SetParent(aParent);
            }
            pChildList = (List*)pListOfChildLists->Next();
        }
    }
    /********************************************************************
    |* die StyleSheets sollen wieder aus dem, Pool entfernt werden
    \*******************************************************************/
    else
    {
        for (pSheet = (SdStyleSheet*)pStyles->First();
             pSheet;
             pSheet = (SdStyleSheet*)pStyles->Next())
        {
            pPool->Remove(pSheet);
        }
    }
    bMySheets = !bMySheets;
}

/*************************************************************************
|*
|* Redo()
|*
\************************************************************************/

void SdMoveStyleSheetsUndoAction::Redo()
{
    Undo();
}

/*************************************************************************
|*
|* Repeat()
|*
\************************************************************************/

void SdMoveStyleSheetsUndoAction::Repeat()
{
    DBG_ASSERT(FALSE, "SdMoveStyleSheetsUndoAction::Repeat: nicht implementiert");
}

/*************************************************************************
|*
|* Destruktor, Liste loeschen; ggfs. die enthaltenen StyleSheets loeschen
|*
\************************************************************************/

SdMoveStyleSheetsUndoAction::~SdMoveStyleSheetsUndoAction()
{
    if (bMySheets)
    {
        // die Liste rueckwaerts aufdroeseln; wenn Gliederungsvorlagen ent-
        // halten sind gewaehrleistet dies den geringsten Broadcasting-Aufwand
        SfxStyleSheet* pSheet = (SfxStyleSheet*)pStyles->Last();
        while (pSheet)
        {
            delete pSheet;
            pSheet = (SfxStyleSheet*)pStyles->Prev();
        }
    }
    delete pStyles;

    for (List* pChildList = (List*)pListOfChildLists->First();
         pChildList;
         pChildList = (List*)pListOfChildLists->Next())
    {
        delete pChildList;
    }
    delete pListOfChildLists;
}

/*************************************************************************
|*
|* Kommentar liefern
|*
\************************************************************************/

String SdMoveStyleSheetsUndoAction::GetComment() const
{
    return String();
}

<|endoftext|>