<commit_before>/*
 *  CustomVar.cpp
 *  OpenLieroX
 *
 *  Created by Albert Zeyer on 24.02.10.
 *  code under LGPL
 *
 */

#include "CustomVar.h"
#include "CBytestream.h"
#include "Debug.h"
#include "game/Attr.h"
#include "util/macros.h"

CustomVar* CustomVar::copy() const {
	// this copy() relies on the ClassInfo. otherwise it cannot work. provide your own in this case, it's virtual
	assert( thisRef.classId != ClassId(-1) );
	const ClassInfo* classInfo = getClassInfo(thisRef.classId);
	assert( classInfo != NULL );
	BaseObject* obj = classInfo->createInstance();
	assert( obj != NULL );
	CustomVar* v = dynamic_cast<BaseObject*>(obj);
	assert( v != NULL );
	v->copyFrom(*this);
	return v;
}

bool CustomVar::operator==(const CustomVar& v) const {
	if( thisRef.classId != v.thisRef.classId ) return false;
	assert( thisRef.classId != ClassId(-1) );

	std::vector<const AttrDesc*> attribs = getAttrDescs(thisRef.classId, true);
	foreach(a, attribs) {
		ScriptVar_t value = (*a)->get(this);
		if(value != (*a)->get(&v)) return false;
	}

	return true;
}

bool CustomVar::operator<(const CustomVar& v) const {
	if( thisRef.classId != v.thisRef.classId )
		return thisRef.classId < v.thisRef.classId;
	assert( thisRef.classId != ClassId(-1) );

	std::vector<const AttrDesc*> attribs = getAttrDescs(thisRef.classId, true);
	foreach(a, attribs) {
		ScriptVar_t value = (*a)->get(this);
		if(value != (*a)->get(&v))
			return value < (*a)->get(&v);
	}

	return true;
}

void CustomVar::copyFrom(const CustomVar& v) {
	assert( thisRef.classId != ClassId(-1) );
	assert( v.thisRef.classId != ClassId(-1) );
	assert( thisRef.classId == v.thisRef.classId );

	std::vector<const AttrDesc*> attribs = getAttrDescs(thisRef.classId, true);
	foreach(a, attribs) {
		ScriptVar_t value = (*a)->get(&v);
		if(value == (*a)->get(this)) continue;
		(*a)->set(this, value);
	}
}

void CustomVar::fromScriptVar(const ScriptVar_t& v) {
	if(v.isCustomType()
			&& v.customVar()->thisRef.classId != ClassId(-1)
			&& v.customVar()->thisRef.classId == thisRef.classId
	)
		copyFrom(*v.customVar());
	else
		fromString(v.toString());
}

Result CustomVar::ToBytestream( CBytestream* bs ) const {
	assert( thisRef.classId != ClassId(-1) );
	bs->writeInt16(thisRef.classId);
	return toBytestream(bs);
}

Result CustomVar::toBytestream(CBytestream *bs) const {
	assert( thisRef.classId != ClassId(-1) );

	std::vector<const AttrDesc*> attribs = getAttrDescs(thisRef.classId, true);
	foreach(a, attribs) {
		ScriptVar_t value = (*a)->get(this);
		if(value == (*a)->defaultValue) continue;
		bs->writeInt16((*a)->objTypeId);
		bs->writeInt16((*a)->attrId);
		bs->writeVar(value);
	}
	bs->writeInt16(ClassId(-1));

	return true;
}

Result CustomVar::fromBytestream(CBytestream *bs) {
	assert( thisRef.classId != ClassId(-1) );

	Result r = true;
	while(true) {
		AttribRef a;
		a.objTypeId = bs->readInt16();
		if(a.objTypeId == ClassId(-1)) break;
		a.attrId = bs->readInt16();
		const AttrDesc* attrDesc = a.getAttrDesc();
		if(attrDesc == NULL) {
			errors << "CustomVar::fromBytestream: unknown attrib " << a.objTypeId << ":" << a.attrId << " for object " << thisRef.description() << endl;
			// try to continue
			r = "unknown attrib";
			bs->SkipVar();
			continue;
		}

		const ClassInfo* classInfo = getClassInfo(a.objTypeId);
		if(classInfo == NULL) {
			errors << "CustomVar::fromBytestream: unknown class for attrib " << a.description() << " for object " << thisRef.description() << endl;
			// try to continue
			r = "unknown class";
			bs->SkipVar();
			continue;
		}

		if(!classInfo->isTypeOf(a.objTypeId)) {
			errors << "CustomVar::fromBytestream: attrib " << a.description() << " does not belong to class " << classInfo->name << " for object " << thisRef.description() << endl;
			// try to continue
			r = "invalid attrib for class";
			bs->SkipVar();
			continue;
		}

		ScriptVar_t var;
		bs->readVar(var);
		attrDesc->set(this, var);
	}

	return r;
}

CustomVar::Ref CustomVar::FromBytestream( CBytestream* bs ) {
	ClassId classId = bs->readInt16();
	const ClassInfo* classInfo = getClassInfo(classId);
	if(classInfo == NULL) {
		errors << "CustomVar::FromBytestream: class ID " << classId << " unknown" << endl;
		return NULL;
	}

	if(!classInfo->isTypeOf(LuaID<CustomVar>::value)) {
		errors << "CustomVar::FromBytestream: class " << classInfo->name << " is not a CustomVar" << endl;
		return NULL;
	}

	if(classInfo->id == LuaID<CustomVar>::value) {
		errors << "CustomVar::FromBytestream: class " << classInfo->name << " is abstract" << endl;
		return NULL;
	}

	CustomVar::Ref obj = (CustomVar*) classInfo->createInstance();
	if(!obj) {
		errors << "CustomVar::FromBytestream: couldn't create instance of " << classInfo->name << endl;
		return NULL;
	}

	if(NegResult r = obj->fromBytestream(bs)) {
		errors << "CustomVar::FromBytestream: error while reading " << classInfo->name << " instance: " << r.res.humanErrorMsg << endl;
		// continue anyway, maybe we have some useful data
	}

	return obj;
}

// We cannot use the REGISTER_CLASS macro because we cannot instantiate it.
static bool registerClass_CustomVar() {
	ClassInfo i;
	i.id = LuaID<CustomVar>::value;
	i.name = "CustomVar";
	i.memSize = sizeof(CustomVar);
	registerClass(i);
	return true;
}
static bool registerClass_CustomVar_init = registerClass_CustomVar();
<commit_msg>small fix<commit_after>/*
 *  CustomVar.cpp
 *  OpenLieroX
 *
 *  Created by Albert Zeyer on 24.02.10.
 *  code under LGPL
 *
 */

#include "CustomVar.h"
#include "CBytestream.h"
#include "Debug.h"
#include "game/Attr.h"
#include "util/macros.h"

CustomVar* CustomVar::copy() const {
	// this copy() relies on the ClassInfo. otherwise it cannot work. provide your own in this case, it's virtual
	assert( thisRef.classId != ClassId(-1) );
	const ClassInfo* classInfo = getClassInfo(thisRef.classId);
	assert( classInfo != NULL );
	BaseObject* obj = classInfo->createInstance();
	assert( obj != NULL );
	CustomVar* v = dynamic_cast<CustomVar*>(obj);
	assert( v != NULL );
	v->copyFrom(*this);
	return v;
}

bool CustomVar::operator==(const CustomVar& v) const {
	if( thisRef.classId != v.thisRef.classId ) return false;
	assert( thisRef.classId != ClassId(-1) );

	std::vector<const AttrDesc*> attribs = getAttrDescs(thisRef.classId, true);
	foreach(a, attribs) {
		ScriptVar_t value = (*a)->get(this);
		if(value != (*a)->get(&v)) return false;
	}

	return true;
}

bool CustomVar::operator<(const CustomVar& v) const {
	if( thisRef.classId != v.thisRef.classId )
		return thisRef.classId < v.thisRef.classId;
	assert( thisRef.classId != ClassId(-1) );

	std::vector<const AttrDesc*> attribs = getAttrDescs(thisRef.classId, true);
	foreach(a, attribs) {
		ScriptVar_t value = (*a)->get(this);
		if(value != (*a)->get(&v))
			return value < (*a)->get(&v);
	}

	return true;
}

void CustomVar::copyFrom(const CustomVar& v) {
	assert( thisRef.classId != ClassId(-1) );
	assert( v.thisRef.classId != ClassId(-1) );
	assert( thisRef.classId == v.thisRef.classId );

	std::vector<const AttrDesc*> attribs = getAttrDescs(thisRef.classId, true);
	foreach(a, attribs) {
		ScriptVar_t value = (*a)->get(&v);
		if(value == (*a)->get(this)) continue;
		(*a)->set(this, value);
	}
}

void CustomVar::fromScriptVar(const ScriptVar_t& v) {
	if(v.isCustomType()
			&& v.customVar()->thisRef.classId != ClassId(-1)
			&& v.customVar()->thisRef.classId == thisRef.classId
	)
		copyFrom(*v.customVar());
	else
		fromString(v.toString());
}

Result CustomVar::ToBytestream( CBytestream* bs ) const {
	assert( thisRef.classId != ClassId(-1) );
	bs->writeInt16(thisRef.classId);
	return toBytestream(bs);
}

Result CustomVar::toBytestream(CBytestream *bs) const {
	assert( thisRef.classId != ClassId(-1) );

	std::vector<const AttrDesc*> attribs = getAttrDescs(thisRef.classId, true);
	foreach(a, attribs) {
		ScriptVar_t value = (*a)->get(this);
		if(value == (*a)->defaultValue) continue;
		bs->writeInt16((*a)->objTypeId);
		bs->writeInt16((*a)->attrId);
		bs->writeVar(value);
	}
	bs->writeInt16(ClassId(-1));

	return true;
}

Result CustomVar::fromBytestream(CBytestream *bs) {
	assert( thisRef.classId != ClassId(-1) );

	Result r = true;
	while(true) {
		AttribRef a;
		a.objTypeId = bs->readInt16();
		if(a.objTypeId == ClassId(-1)) break;
		a.attrId = bs->readInt16();
		const AttrDesc* attrDesc = a.getAttrDesc();
		if(attrDesc == NULL) {
			errors << "CustomVar::fromBytestream: unknown attrib " << a.objTypeId << ":" << a.attrId << " for object " << thisRef.description() << endl;
			// try to continue
			r = "unknown attrib";
			bs->SkipVar();
			continue;
		}

		const ClassInfo* classInfo = getClassInfo(a.objTypeId);
		if(classInfo == NULL) {
			errors << "CustomVar::fromBytestream: unknown class for attrib " << a.description() << " for object " << thisRef.description() << endl;
			// try to continue
			r = "unknown class";
			bs->SkipVar();
			continue;
		}

		if(!classInfo->isTypeOf(a.objTypeId)) {
			errors << "CustomVar::fromBytestream: attrib " << a.description() << " does not belong to class " << classInfo->name << " for object " << thisRef.description() << endl;
			// try to continue
			r = "invalid attrib for class";
			bs->SkipVar();
			continue;
		}

		ScriptVar_t var;
		bs->readVar(var);
		attrDesc->set(this, var);
	}

	return r;
}

CustomVar::Ref CustomVar::FromBytestream( CBytestream* bs ) {
	ClassId classId = bs->readInt16();
	const ClassInfo* classInfo = getClassInfo(classId);
	if(classInfo == NULL) {
		errors << "CustomVar::FromBytestream: class ID " << classId << " unknown" << endl;
		return NULL;
	}

	if(!classInfo->isTypeOf(LuaID<CustomVar>::value)) {
		errors << "CustomVar::FromBytestream: class " << classInfo->name << " is not a CustomVar" << endl;
		return NULL;
	}

	if(classInfo->id == LuaID<CustomVar>::value) {
		errors << "CustomVar::FromBytestream: class " << classInfo->name << " is abstract" << endl;
		return NULL;
	}

	CustomVar::Ref obj = (CustomVar*) classInfo->createInstance();
	if(!obj) {
		errors << "CustomVar::FromBytestream: couldn't create instance of " << classInfo->name << endl;
		return NULL;
	}

	if(NegResult r = obj->fromBytestream(bs)) {
		errors << "CustomVar::FromBytestream: error while reading " << classInfo->name << " instance: " << r.res.humanErrorMsg << endl;
		// continue anyway, maybe we have some useful data
	}

	return obj;
}

// We cannot use the REGISTER_CLASS macro because we cannot instantiate it.
static bool registerClass_CustomVar() {
	ClassInfo i;
	i.id = LuaID<CustomVar>::value;
	i.name = "CustomVar";
	i.memSize = sizeof(CustomVar);
	registerClass(i);
	return true;
}
static bool registerClass_CustomVar_init = registerClass_CustomVar();
<|endoftext|>


<commit_before>/*!
 * \file util.h
 *
 * \brief Utilities for the IEGen project
 *
 * \date Started: 9/13/2010, but has been completely rewritten
 * # $Revision:: 622                $: last committed revision
 * # $Date:: 2013-01-18 13:11:32 -0#$: date of last committed revision
 * # $Author:: cathie               $: author of last committed revision
 *
 * \authors
 *
 * Copyright (c) 2012, Colorado State University

 * All rights reserved.

 * See ../../COPYING for details.

 */

#include "jsonHelper.h"

//using jsoncons::json;
//using namespace iegenlib;

// Reads a list of UFCs from a json structure and stores them in the environment
void addUFCs(json &ufcs){

  for (size_t j = 0; j < ufcs["UFS"].size(); ++j){

    bool bijective = false;
    if( ufcs["UFS"][j]["Bijective"].as<string>() == string("true") ){
      bijective = true;
    }
    iegenlib::MonotonicType monotonicity = iegenlib::Monotonic_NONE;
    if(ufcs["UFS"][j]["Monotonicity"].as<string>() ==
                            string("Monotonic_Nondecreasing")){
      monotonicity = iegenlib::Monotonic_Nondecreasing;
    } else if(ufcs["UFS"][j]["Monotonicity"].as<string>() ==
                                  string("Monotonic_Increasing")){
      monotonicity = iegenlib::Monotonic_Increasing;
    }

    iegenlib::appendCurrEnv(ufcs["UFS"][j]["Name"].as<string>(),// Name
         new Set(ufcs["UFS"][j]["Domain"].as<string>()),   // Domain
         new Set(ufcs["UFS"][j]["Range"].as<string>()),    // Range
         bijective,                                              // Bijective?
         monotonicity                                            // Monotonicity?
                                );
  }
}

// Reads a list of universially quantified constraints from a json structure
// and stores them in the environment
void addUniQuantRules(json &uqCons){

  UniQuantRule *uqRule;
  for (size_t j = 0; j < uqCons.size(); ++j){

    // forall e1, e2, ... : p => q
    uqRule = new UniQuantRule(uqCons[j]["Type"].as<string>(),
                uqCons[j]["UniQuantVar"].as<string>(),
                uqCons[j]["p"].as<string>(), uqCons[j]["q"].as<string>());
    currentEnv.addUniQuantRule( uqRule );
  }
}

// Reads iterators that we should not project from a json sructure
void notProjectIters(Relation* rel, std::set<int> &parallelTvs, json &np){

  iegenlib::TupleDecl td = rel->getTupleDecl();
  for (size_t j = 0; j < np.size(); ++j){
    string tvS = np[j].as<string>();
    int tvN = -1;
    for (unsigned int c = 0 ; c < td.getSize() ; c++){
      if( tvS == td.elemToString(c) ){
        tvN = c;
        break;
      }
    }
    parallelTvs.insert( tvN );
  }
}
<commit_msg>Adding notProjectIters for iegen::Set<commit_after>/*!
 * \file util.h
 *
 * \brief Utilities for the IEGen project
 *
 * \date Started: 9/13/2010, but has been completely rewritten
 * # $Revision:: 622                $: last committed revision
 * # $Date:: 2013-01-18 13:11:32 -0#$: date of last committed revision
 * # $Author:: cathie               $: author of last committed revision
 *
 * \authors
 *
 * Copyright (c) 2012, Colorado State University

 * All rights reserved.

 * See ../../COPYING for details.

 */

#include "jsonHelper.h"

//using jsoncons::json;
//using namespace iegenlib;

// Reads a list of UFCs from a json structure and stores them in the environment
void addUFCs(json &ufcs){

  for (size_t j = 0; j < ufcs["UFS"].size(); ++j){

    bool bijective = false;
    if( ufcs["UFS"][j]["Bijective"].as<string>() == string("true") ){
      bijective = true;
    }
    iegenlib::MonotonicType monotonicity = iegenlib::Monotonic_NONE;
    if(ufcs["UFS"][j]["Monotonicity"].as<string>() ==
                            string("Monotonic_Nondecreasing")){
      monotonicity = iegenlib::Monotonic_Nondecreasing;
    } else if(ufcs["UFS"][j]["Monotonicity"].as<string>() ==
                                  string("Monotonic_Increasing")){
      monotonicity = iegenlib::Monotonic_Increasing;
    }

    iegenlib::appendCurrEnv(ufcs["UFS"][j]["Name"].as<string>(),// Name
         new Set(ufcs["UFS"][j]["Domain"].as<string>()),   // Domain
         new Set(ufcs["UFS"][j]["Range"].as<string>()),    // Range
         bijective,                                              // Bijective?
         monotonicity                                            // Monotonicity?
                                );
  }
}

// Reads a list of universially quantified constraints from a json structure
// and stores them in the environment
void addUniQuantRules(json &uqCons){

  UniQuantRule *uqRule;
  for (size_t j = 0; j < uqCons.size(); ++j){

    // forall e1, e2, ... : p => q
    uqRule = new UniQuantRule(uqCons[j]["Type"].as<string>(),
                uqCons[j]["UniQuantVar"].as<string>(),
                uqCons[j]["p"].as<string>(), uqCons[j]["q"].as<string>());
    currentEnv.addUniQuantRule( uqRule );
  }
}

// Reads iterators that we should not project from a json sructure
void notProjectIters(Relation* rel, std::set<int> &parallelTvs, json &np){

  iegenlib::TupleDecl td = rel->getTupleDecl();
  for (size_t j = 0; j < np.size(); ++j){
    string tvS = np[j].as<string>();
    int tvN = -1;
    for (unsigned int c = 0 ; c < td.getSize() ; c++){
      if( tvS == td.elemToString(c) ){
        tvN = c;
        break;
      }
    }
    parallelTvs.insert( tvN );
  }
}

// Reads iterators that we should not project from a json sructure
void notProjectIters(Set* s, std::set<int> &parallelTvs, json &np){

  iegenlib::TupleDecl td = s->getTupleDecl();
  for (size_t j = 0; j < np.size(); ++j){
    string tvS = np[j].as<string>();
    int tvN = -1;
    for (unsigned int c = 0 ; c < td.getSize() ; c++){
      if( tvS == td.elemToString(c) ){
        tvN = c;
        break;
      }
    }
    parallelTvs.insert( tvN );
  }
}
<|endoftext|>


<commit_before>/*
Copyright (c) 2013 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.

Author: Leonardo de Moura
*/
#if defined(LEAN_WINDOWS) && !defined(LEAN_CYGWIN)
#include <windows.h>
#endif
#include <string>
#include <cstdlib>
#include <fstream>
#include <vector>
#include <sys/types.h>
#include <sys/stat.h>
#include "util/exception.h"
#include "util/sstream.h"
#include "util/name.h"
#include "util/optional.h"
#include "util/realpath.h"
#include "util/lean_path.h"

#ifndef LEAN_DEFAULT_MODULE_FILE_NAME
#define LEAN_DEFAULT_MODULE_FILE_NAME "default"
#endif

namespace lean {
file_not_found_exception::file_not_found_exception(std::string const & fname):
    exception(sstream() << "file '" << fname << "' not found in the LEAN_PATH"),
    m_fname(fname) {}

static std::string * g_default_file_name = nullptr;

bool is_directory(char const * pathname) {
    struct stat info;
    if (stat(pathname, &info) != 0 )
        return false; // failed to access pathname
    return info.st_mode & S_IFDIR;
}

#if defined(LEAN_WINDOWS) && !defined(LEAN_CYGWIN)
// Windows version
static char g_path_sep     = ';';
static char g_path_alt_sep = ':';
static char g_sep          = '\\';
static char g_bad_sep      = '/';
static std::string get_exe_location() {
    HMODULE hModule = GetModuleHandleW(NULL);
    WCHAR path[MAX_PATH];
    GetModuleFileNameW(hModule, path, MAX_PATH);
    std::wstring pathstr(path);
    return std::string(pathstr.begin(), pathstr.end());
}
bool is_path_sep(char c) { return c == g_path_sep || c == g_path_alt_sep; }
#elif defined(__APPLE__)
// OSX version
#include <mach-o/dyld.h>
#include <limits.h>
#include <stdlib.h>
static char g_path_sep     = ':';
static char g_sep          = '/';
static char g_bad_sep      = '\\';
static std::string get_exe_location() {
    char buf1[PATH_MAX];
    char buf2[PATH_MAX];
    uint32_t bufsize = PATH_MAX;
    if (_NSGetExecutablePath(buf1, &bufsize) != 0)
        throw exception("failed to locate Lean executable location");
    if (!realpath(buf1, buf2))
        throw exception("failed to resolve symbolic links in " + std::string(buf1));
    return std::string(buf2);
}
bool is_path_sep(char c) { return c == g_path_sep; }
#else
// Linux version
#include <unistd.h>
#include <string.h>
#include <limits.h> // NOLINT
#include <stdio.h>
static char g_path_sep     = ':';
static char g_sep          = '/';
static char g_bad_sep      = '\\';
static std::string get_exe_location() {
    char path[PATH_MAX];
    char dest[PATH_MAX];
    memset(dest, 0, PATH_MAX);
    pid_t pid = getpid();
    snprintf(path, PATH_MAX, "/proc/%d/exe", pid);
    if (readlink(path, dest, PATH_MAX) == -1) {
        throw exception("failed to locate Lean executable location");
    } else {
        return std::string(dest);
    }
}
bool is_path_sep(char c) { return c == g_path_sep; }
#endif

std::string normalize_path(std::string f) {
    for (auto & c : f) {
        if (c == g_bad_sep)
            c = g_sep;
    }
    return f;
}

std::string get_path(std::string f) {
    while (true) {
        if (f.empty())
            throw exception("failed to locate Lean executable location");
        if (f.back() == g_sep) {
            f.pop_back();
            return f;
        }
        f.pop_back();
    }
}

static std::string *              g_lean_path = nullptr;
static std::vector<std::string> * g_lean_path_vector = nullptr;

void init_lean_path(bool use_hott) {
#if defined(LEAN_EMSCRIPTEN)
    *g_lean_path = "/library";
    g_lean_path_vector->push_back(*g_lean_path);
#else
    char * r = nullptr;
    if (use_hott)
        r = getenv("HLEAN_PATH");
    else
        r = getenv("LEAN_PATH");
    if (r == nullptr) {
        std::string exe_path = get_path(get_exe_location());
        if (use_hott)
            *g_lean_path  = exe_path + g_sep + ".." + g_sep + "hott";
        else
            *g_lean_path  = exe_path + g_sep + ".." + g_sep + "library";
        *g_lean_path += g_path_sep;
        *g_lean_path += exe_path + g_sep + ".." + g_sep + "lib" + g_sep + "lean";
        *g_lean_path += g_path_sep;
        *g_lean_path += ".";
    } else {
        *g_lean_path = r;
    }
    g_lean_path_vector->clear();
    *g_lean_path = normalize_path(*g_lean_path);
    unsigned i  = 0;
    unsigned j  = 0;
    unsigned sz = g_lean_path->size();
    for (; j < sz; j++) {
        if (is_path_sep((*g_lean_path)[j])) {
            if (j > i)
                g_lean_path_vector->push_back(g_lean_path->substr(i, j - i));
            i = j + 1;
        }
    }
    if (j > i)
        g_lean_path_vector->push_back(g_lean_path->substr(i, j - i));
#endif
}

static char g_sep_str[2];

void initialize_lean_path(bool use_hott) {
    g_default_file_name = new std::string(LEAN_DEFAULT_MODULE_FILE_NAME);
    g_lean_path         = new std::string();
    g_lean_path_vector  = new std::vector<std::string>();
    g_sep_str[0]        = g_sep;
    g_sep_str[1]        = 0;
    init_lean_path(use_hott);
}

void finalize_lean_path() {
    delete g_lean_path_vector;
    delete g_lean_path;
    delete g_default_file_name;
}

bool has_file_ext(std::string const & fname, char const * ext) {
    unsigned ext_len = strlen(ext);
    return fname.size() > ext_len && fname.substr(fname.size() - ext_len, ext_len) == ext;
}

bool is_hlean_file(std::string const & fname) {
    return has_file_ext(fname, ".hlean");
}

bool is_lean_file(std::string const & fname) {
    return has_file_ext(fname, ".lean");
}

bool is_olean_file(std::string const & fname) {
    return has_file_ext(fname, ".olean");
}

bool is_lua_file(std::string const & fname) {
    return has_file_ext(fname, ".lua");
}

bool is_known_file_ext(std::string const & fname) {
    return is_lean_file(fname) || is_hlean_file(fname) || is_olean_file(fname) || is_lua_file(fname);
}

optional<std::string> check_file_core(std::string file, char const * ext) {
    if (ext)
        file += ext;
    std::ifstream ifile(file);
    if (ifile)
        return optional<std::string>(lrealpath(file.c_str()));
    else
        return optional<std::string>();
}

optional<std::string> check_file(std::string const & path, std::string const & fname, char const * ext = nullptr) {
    std::string file = path + g_sep + fname;
    if (is_directory(file.c_str())) {
        std::string default_file = file + g_sep + *g_default_file_name;
        if (auto r1 = check_file_core(default_file, ext)) {
            if (auto r2 = check_file_core(file, ext))
                throw exception(sstream() << "ambiguous import, it can be '" << *r1 << "' or '" << *r2 << "'");
            return r1;
        }
    }
    return check_file_core(file, ext);
}

std::string name_to_file(name const & fname) {
    return fname.to_string(g_sep_str);
}

std::string find_file(std::string fname, std::initializer_list<char const *> const & extensions) {
    bool is_known = is_known_file_ext(fname);
    fname = normalize_path(fname);
    for (auto path : *g_lean_path_vector) {
        if (is_known) {
            if (auto r = check_file(path, fname))
                return *r;
        } else {
            for (auto ext : extensions) {
                if (auto r = check_file(path, fname, ext))
                    return *r;
            }
        }
    }
    throw file_not_found_exception(fname);
}

std::string find_file(std::string const & base, optional<unsigned> const & rel, name const & fname,
                      std::initializer_list<char const *> const & extensions) {
    if (!rel) {
        return find_file(fname.to_string(g_sep_str), extensions);
    } else {
        auto path = base;
        for (unsigned i = 0; i < *rel; i++) {
            path += g_sep;
            path += "..";
        }
        for (auto ext : extensions) {
            if (auto r = check_file(path, fname.to_string(g_sep_str), ext))
                return *r;
        }
        throw file_not_found_exception(fname.to_string());
    }
}

std::string find_file(std::string const & base, optional<unsigned> const & k, name const & fname, char const * ext) {
    return find_file(base, k, fname, {ext});
}

std::string find_file(std::string fname) {
    return find_file(fname, {".olean", ".lean", ".lua"});
}

std::string find_file(name const & fname) {
    return find_file(fname.to_string(g_sep_str));
}

std::string find_file(name const & fname, std::initializer_list<char const *> const & exts) {
    return find_file(fname.to_string(g_sep_str), exts);
}

char const * get_lean_path() {
    return g_lean_path->c_str();
}

void display_path(std::ostream & out, std::string const & fname) {
    out << fname;
}

std::string dirname(char const * fname) {
    if (fname == nullptr)
        return ".";
    std::string nfname = normalize_path(std::string(fname));
    fname = nfname.c_str();
    unsigned i        = 0;
    unsigned last_sep = 0;
    bool found_sep    = false;
    char const * it   = fname;
    while (*it) {
        if (*it == g_sep) {
            found_sep = true;
            last_sep  = i;
        }
        ++i;
        ++it;
    }
    if (!found_sep) {
        return ".";
    } else {
        std::string r;
        for (unsigned i = 0; i < last_sep; i++)
            r.push_back(fname[i]);
        return r;
    }
}

std::string path_append(char const * p1, char const * p2) {
    std::string r(p1);
    r += g_sep;
    r += p2;
    return r;
}
}
<commit_msg>fix(util/lean_path): memory leak<commit_after>/*
Copyright (c) 2013 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.

Author: Leonardo de Moura
*/
#if defined(LEAN_WINDOWS) && !defined(LEAN_CYGWIN)
#include <windows.h>
#endif
#include <string>
#include <cstdlib>
#include <fstream>
#include <vector>
#include <sys/types.h>
#include <sys/stat.h>
#include "util/exception.h"
#include "util/sstream.h"
#include "util/name.h"
#include "util/optional.h"
#include "util/realpath.h"
#include "util/lean_path.h"

#ifndef LEAN_DEFAULT_MODULE_FILE_NAME
#define LEAN_DEFAULT_MODULE_FILE_NAME "default"
#endif

namespace lean {
file_not_found_exception::file_not_found_exception(std::string const & fname):
    exception(sstream() << "file '" << fname << "' not found in the LEAN_PATH"),
    m_fname(fname) {}

static std::string * g_default_file_name             = nullptr;
static std::string *              g_lean_path        = nullptr;
static std::vector<std::string> * g_lean_path_vector = nullptr;

bool is_directory(char const * pathname) {
    struct stat info;
    if (stat(pathname, &info) != 0 )
        return false; // failed to access pathname
    return info.st_mode & S_IFDIR;
}

#if defined(LEAN_WINDOWS) && !defined(LEAN_CYGWIN)
// Windows version
static char g_path_sep     = ';';
static char g_path_alt_sep = ':';
static char g_sep          = '\\';
static char g_bad_sep      = '/';
static std::string get_exe_location() {
    HMODULE hModule = GetModuleHandleW(NULL);
    WCHAR path[MAX_PATH];
    GetModuleFileNameW(hModule, path, MAX_PATH);
    std::wstring pathstr(path);
    return std::string(pathstr.begin(), pathstr.end());
}
bool is_path_sep(char c) { return c == g_path_sep || c == g_path_alt_sep; }
#elif defined(__APPLE__)
// OSX version
#include <mach-o/dyld.h>
#include <limits.h>
#include <stdlib.h>
static char g_path_sep     = ':';
static char g_sep          = '/';
static char g_bad_sep      = '\\';
static std::string get_exe_location() {
    char buf1[PATH_MAX];
    char buf2[PATH_MAX];
    uint32_t bufsize = PATH_MAX;
    if (_NSGetExecutablePath(buf1, &bufsize) != 0)
        throw exception("failed to locate Lean executable location");
    if (!realpath(buf1, buf2))
        throw exception("failed to resolve symbolic links in " + std::string(buf1));
    return std::string(buf2);
}
bool is_path_sep(char c) { return c == g_path_sep; }
#else
// Linux version
#include <unistd.h>
#include <string.h>
#include <limits.h> // NOLINT
#include <stdio.h>
static char g_path_sep     = ':';
static char g_sep          = '/';
static char g_bad_sep      = '\\';
static std::string get_exe_location() {
    char path[PATH_MAX];
    char dest[PATH_MAX];
    memset(dest, 0, PATH_MAX);
    pid_t pid = getpid();
    snprintf(path, PATH_MAX, "/proc/%d/exe", pid);
    if (readlink(path, dest, PATH_MAX) == -1) {
        throw exception("failed to locate Lean executable location");
    } else {
        return std::string(dest);
    }
}
bool is_path_sep(char c) { return c == g_path_sep; }
#endif

std::string normalize_path(std::string f) {
    for (auto & c : f) {
        if (c == g_bad_sep)
            c = g_sep;
    }
    return f;
}

std::string get_path(std::string f) {
    while (true) {
        if (f.empty())
            throw exception("failed to locate Lean executable location");
        if (f.back() == g_sep) {
            f.pop_back();
            return f;
        }
        f.pop_back();
    }
}

void init_lean_path(bool use_hott) {
#if defined(LEAN_EMSCRIPTEN)
    *g_lean_path = "/library";
    g_lean_path_vector->push_back(*g_lean_path);
#else
    char * r = nullptr;
    if (use_hott)
        r = getenv("HLEAN_PATH");
    else
        r = getenv("LEAN_PATH");
    if (r == nullptr) {
        std::string exe_path = get_path(get_exe_location());
        if (use_hott)
            *g_lean_path  = exe_path + g_sep + ".." + g_sep + "hott";
        else
            *g_lean_path  = exe_path + g_sep + ".." + g_sep + "library";
        *g_lean_path += g_path_sep;
        *g_lean_path += exe_path + g_sep + ".." + g_sep + "lib" + g_sep + "lean";
        *g_lean_path += g_path_sep;
        *g_lean_path += ".";
    } else {
        *g_lean_path = r;
    }
    g_lean_path_vector->clear();
    *g_lean_path = normalize_path(*g_lean_path);
    unsigned i  = 0;
    unsigned j  = 0;
    unsigned sz = g_lean_path->size();
    for (; j < sz; j++) {
        if (is_path_sep((*g_lean_path)[j])) {
            if (j > i)
                g_lean_path_vector->push_back(g_lean_path->substr(i, j - i));
            i = j + 1;
        }
    }
    if (j > i)
        g_lean_path_vector->push_back(g_lean_path->substr(i, j - i));
#endif
}

static char g_sep_str[2];

void initialize_lean_path(bool use_hott) {
    if (g_default_file_name != nullptr)
        finalize_lean_path();
    g_default_file_name = new std::string(LEAN_DEFAULT_MODULE_FILE_NAME);
    g_lean_path         = new std::string();
    g_lean_path_vector  = new std::vector<std::string>();
    g_sep_str[0]        = g_sep;
    g_sep_str[1]        = 0;
    init_lean_path(use_hott);
}

void finalize_lean_path() {
    delete g_lean_path_vector;
    delete g_lean_path;
    delete g_default_file_name;
}

bool has_file_ext(std::string const & fname, char const * ext) {
    unsigned ext_len = strlen(ext);
    return fname.size() > ext_len && fname.substr(fname.size() - ext_len, ext_len) == ext;
}

bool is_hlean_file(std::string const & fname) {
    return has_file_ext(fname, ".hlean");
}

bool is_lean_file(std::string const & fname) {
    return has_file_ext(fname, ".lean");
}

bool is_olean_file(std::string const & fname) {
    return has_file_ext(fname, ".olean");
}

bool is_lua_file(std::string const & fname) {
    return has_file_ext(fname, ".lua");
}

bool is_known_file_ext(std::string const & fname) {
    return is_lean_file(fname) || is_hlean_file(fname) || is_olean_file(fname) || is_lua_file(fname);
}

optional<std::string> check_file_core(std::string file, char const * ext) {
    if (ext)
        file += ext;
    std::ifstream ifile(file);
    if (ifile)
        return optional<std::string>(lrealpath(file.c_str()));
    else
        return optional<std::string>();
}

optional<std::string> check_file(std::string const & path, std::string const & fname, char const * ext = nullptr) {
    std::string file = path + g_sep + fname;
    if (is_directory(file.c_str())) {
        std::string default_file = file + g_sep + *g_default_file_name;
        if (auto r1 = check_file_core(default_file, ext)) {
            if (auto r2 = check_file_core(file, ext))
                throw exception(sstream() << "ambiguous import, it can be '" << *r1 << "' or '" << *r2 << "'");
            return r1;
        }
    }
    return check_file_core(file, ext);
}

std::string name_to_file(name const & fname) {
    return fname.to_string(g_sep_str);
}

std::string find_file(std::string fname, std::initializer_list<char const *> const & extensions) {
    bool is_known = is_known_file_ext(fname);
    fname = normalize_path(fname);
    for (auto path : *g_lean_path_vector) {
        if (is_known) {
            if (auto r = check_file(path, fname))
                return *r;
        } else {
            for (auto ext : extensions) {
                if (auto r = check_file(path, fname, ext))
                    return *r;
            }
        }
    }
    throw file_not_found_exception(fname);
}

std::string find_file(std::string const & base, optional<unsigned> const & rel, name const & fname,
                      std::initializer_list<char const *> const & extensions) {
    if (!rel) {
        return find_file(fname.to_string(g_sep_str), extensions);
    } else {
        auto path = base;
        for (unsigned i = 0; i < *rel; i++) {
            path += g_sep;
            path += "..";
        }
        for (auto ext : extensions) {
            if (auto r = check_file(path, fname.to_string(g_sep_str), ext))
                return *r;
        }
        throw file_not_found_exception(fname.to_string());
    }
}

std::string find_file(std::string const & base, optional<unsigned> const & k, name const & fname, char const * ext) {
    return find_file(base, k, fname, {ext});
}

std::string find_file(std::string fname) {
    return find_file(fname, {".olean", ".lean", ".lua"});
}

std::string find_file(name const & fname) {
    return find_file(fname.to_string(g_sep_str));
}

std::string find_file(name const & fname, std::initializer_list<char const *> const & exts) {
    return find_file(fname.to_string(g_sep_str), exts);
}

char const * get_lean_path() {
    return g_lean_path->c_str();
}

void display_path(std::ostream & out, std::string const & fname) {
    out << fname;
}

std::string dirname(char const * fname) {
    if (fname == nullptr)
        return ".";
    std::string nfname = normalize_path(std::string(fname));
    fname = nfname.c_str();
    unsigned i        = 0;
    unsigned last_sep = 0;
    bool found_sep    = false;
    char const * it   = fname;
    while (*it) {
        if (*it == g_sep) {
            found_sep = true;
            last_sep  = i;
        }
        ++i;
        ++it;
    }
    if (!found_sep) {
        return ".";
    } else {
        std::string r;
        for (unsigned i = 0; i < last_sep; i++)
            r.push_back(fname[i]);
        return r;
    }
}

std::string path_append(char const * p1, char const * p2) {
    std::string r(p1);
    r += g_sep;
    r += p2;
    return r;
}
}
<|endoftext|>


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

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sd.hxx"

#include "fuoutl.hxx"

#include <svx/outliner.hxx>

#ifndef SD_OUTLINE_VIEW_HXX
#include "OutlineView.hxx"
#endif
#ifndef SD_OUTLINE_VIEW_SHELL_HXX
#include "OutlineViewShell.hxx"
#endif
#ifndef SD_WINDOW_SHELL_HXX
#include "Window.hxx"
#endif

namespace sd {

TYPEINIT1( FuOutline, FuPoor );

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

FuOutline::FuOutline (
    ViewShell* pViewShell,
    ::sd::Window* pWindow,
    ::sd::View* pView,
    SdDrawDocument* pDoc,
    SfxRequest& rReq)
    : FuPoor(pViewShell, pWindow, pView, pDoc, rReq),
      pOutlineViewShell (static_cast<OutlineViewShell*>(pViewShell)),
      pOutlineView (static_cast<OutlineView*>(pView))
{
}

FunctionReference FuOutline::Create( ViewShell* pViewSh, ::sd::Window* pWin, ::sd::View* pView, SdDrawDocument* pDoc, SfxRequest& rReq )
{
    FunctionReference xFunc( new FuOutline( pViewSh, pWin, pView, pDoc, rReq ) );
    return xFunc;
}

/*************************************************************************
|*
|* Command, weiterleiten an OutlinerView
|*
\************************************************************************/

BOOL FuOutline::Command(const CommandEvent& rCEvt)
{
    BOOL bResult = FALSE;

    OutlinerView* pOlView =
        static_cast<OutlineView*>(pView)->GetViewByWindow(pWindow);
    DBG_ASSERT (pOlView, "keine OutlinerView gefunden");

    if (pOlView)
    {
        pOlView->Command(rCEvt);        // liefert leider keinen Returnwert
        bResult = TRUE;
    }
    return bResult;
}

void FuOutline::ScrollStart()
{
}

void FuOutline::ScrollEnd()
{
}

} // end of namespace sd
<commit_msg>INTEGRATION: CWS sdwarningsbegone (1.5.38); FILE MERGED 2006/11/22 12:41:54 cl 1.5.38.1: #i69285# warning free code changes for unxlngi6.pro<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: fuoutl.cxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: kz $ $Date: 2006-12-12 17:21:12 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sd.hxx"

#include "fuoutl.hxx"

#include <svx/outliner.hxx>

#ifndef SD_OUTLINE_VIEW_HXX
#include "OutlineView.hxx"
#endif
#ifndef SD_OUTLINE_VIEW_SHELL_HXX
#include "OutlineViewShell.hxx"
#endif
#ifndef SD_WINDOW_SHELL_HXX
#include "Window.hxx"
#endif

namespace sd {

TYPEINIT1( FuOutline, FuPoor );

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

FuOutline::FuOutline (
    ViewShell* pViewShell,
    ::sd::Window* pWindow,
    ::sd::View* pView,
    SdDrawDocument* pDoc,
    SfxRequest& rReq)
    : FuPoor(pViewShell, pWindow, pView, pDoc, rReq),
      pOutlineViewShell (static_cast<OutlineViewShell*>(pViewShell)),
      pOutlineView (static_cast<OutlineView*>(pView))
{
}

FunctionReference FuOutline::Create( ViewShell* pViewSh, ::sd::Window* pWin, ::sd::View* pView, SdDrawDocument* pDoc, SfxRequest& rReq )
{
    FunctionReference xFunc( new FuOutline( pViewSh, pWin, pView, pDoc, rReq ) );
    return xFunc;
}

/*************************************************************************
|*
|* Command, weiterleiten an OutlinerView
|*
\************************************************************************/

BOOL FuOutline::Command(const CommandEvent& rCEvt)
{
    BOOL bResult = FALSE;

    OutlinerView* pOlView =
        static_cast<OutlineView*>(mpView)->GetViewByWindow(mpWindow);
    DBG_ASSERT (pOlView, "keine OutlinerView gefunden");

    if (pOlView)
    {
        pOlView->Command(rCEvt);        // liefert leider keinen Returnwert
        bResult = TRUE;
    }
    return bResult;
}

void FuOutline::ScrollStart()
{
}

void FuOutline::ScrollEnd()
{
}

} // end of namespace sd
<|endoftext|>


<commit_before>#include "selfdrive/ui/soundd/sound.h"

#include <QAudio>
#include <QAudioDeviceInfo>
#include <QDebug>

#include "cereal/messaging/messaging.h"
#include "selfdrive/common/util.h"

// TODO: detect when we can't play sounds
// TODO: detect when we can't display the UI

Sound::Sound(QObject *parent) : sm({"carState", "controlsState", "deviceState"}) {
  qInfo() << "default audio device: " << QAudioDeviceInfo::defaultOutputDevice().deviceName();

  for (auto &[alert, fn, loops] : sound_list) {
    QSoundEffect *s = new QSoundEffect(this);
    QObject::connect(s, &QSoundEffect::statusChanged, [=]() {
      assert(s->status() != QSoundEffect::Error);
    });
    s->setVolume(Hardware::MIN_VOLUME);
    s->setSource(QUrl::fromLocalFile("../../assets/sounds/" + fn));
    sounds[alert] = {s, loops};
  }

  QTimer *timer = new QTimer(this);
  QObject::connect(timer, &QTimer::timeout, this, &Sound::update);
  timer->start(1000 / UI_FREQ);
};

void Sound::update() {
  const bool started_prev = sm["deviceState"].getDeviceState().getStarted();
  sm.update(0);

  const bool started = sm["deviceState"].getDeviceState().getStarted();
  if (started && !started_prev) {
    started_frame = sm.frame;
  }

  // no sounds while offroad
  // also no sounds if nothing is alive in case thermald crashes while offroad
  const bool crashed = (sm.frame - std::max(sm.rcv_frame("deviceState"), sm.rcv_frame("controlsState"))) > 10*UI_FREQ;
  if (!started || crashed) {
    setAlert({});
    return;
  }

  // scale volume with speed
  if (sm.updated("carState")) {
    float volume = util::map_val(sm["carState"].getCarState().getVEgo(), 11.f, 20.f, 0.f, 1.0f);
    volume = QAudio::convertVolume(volume, QAudio::LogarithmicVolumeScale, QAudio::LinearVolumeScale);
    volume = util::map_val(volume, 0.f, 1.f, Hardware::MIN_VOLUME, Hardware::MAX_VOLUME);
    for (auto &[s, loops] : sounds) {
      s->setVolume(std::round(100 * volume) / 100);
    }
  }

  setAlert(Alert::get(sm, started_frame));
}

void Sound::setAlert(const Alert &alert) {
  if (!current_alert.equal(alert)) {
    current_alert = alert;
    // stop sounds
    for (auto &[s, loops] : sounds) {
      // Only stop repeating sounds
      if (s->loopsRemaining() > 1 || s->loopsRemaining() == QSoundEffect::Infinite) {
        s->stop();
      }
    }

    // play sound
    if (alert.sound != AudibleAlert::NONE) {
      auto &[s, loops] = sounds[alert.sound];
      s->setLoopCount(loops);
      s->play();
    }
  }
}
<commit_msg>soundd: use setLoopCount(0) to stop repeating sound (#23076)<commit_after>#include "selfdrive/ui/soundd/sound.h"

#include <QAudio>
#include <QAudioDeviceInfo>
#include <QDebug>

#include "cereal/messaging/messaging.h"
#include "selfdrive/common/util.h"

// TODO: detect when we can't play sounds
// TODO: detect when we can't display the UI

Sound::Sound(QObject *parent) : sm({"carState", "controlsState", "deviceState"}) {
  qInfo() << "default audio device: " << QAudioDeviceInfo::defaultOutputDevice().deviceName();

  for (auto &[alert, fn, loops] : sound_list) {
    QSoundEffect *s = new QSoundEffect(this);
    QObject::connect(s, &QSoundEffect::statusChanged, [=]() {
      assert(s->status() != QSoundEffect::Error);
    });
    s->setVolume(Hardware::MIN_VOLUME);
    s->setSource(QUrl::fromLocalFile("../../assets/sounds/" + fn));
    sounds[alert] = {s, loops};
  }

  QTimer *timer = new QTimer(this);
  QObject::connect(timer, &QTimer::timeout, this, &Sound::update);
  timer->start(1000 / UI_FREQ);
};

void Sound::update() {
  const bool started_prev = sm["deviceState"].getDeviceState().getStarted();
  sm.update(0);

  const bool started = sm["deviceState"].getDeviceState().getStarted();
  if (started && !started_prev) {
    started_frame = sm.frame;
  }

  // no sounds while offroad
  // also no sounds if nothing is alive in case thermald crashes while offroad
  const bool crashed = (sm.frame - std::max(sm.rcv_frame("deviceState"), sm.rcv_frame("controlsState"))) > 10*UI_FREQ;
  if (!started || crashed) {
    setAlert({});
    return;
  }

  // scale volume with speed
  if (sm.updated("carState")) {
    float volume = util::map_val(sm["carState"].getCarState().getVEgo(), 11.f, 20.f, 0.f, 1.0f);
    volume = QAudio::convertVolume(volume, QAudio::LogarithmicVolumeScale, QAudio::LinearVolumeScale);
    volume = util::map_val(volume, 0.f, 1.f, Hardware::MIN_VOLUME, Hardware::MAX_VOLUME);
    for (auto &[s, loops] : sounds) {
      s->setVolume(std::round(100 * volume) / 100);
    }
  }

  setAlert(Alert::get(sm, started_frame));
}

void Sound::setAlert(const Alert &alert) {
  if (!current_alert.equal(alert)) {
    current_alert = alert;
    // stop sounds
    for (auto &[s, loops] : sounds) {
      // Only stop repeating sounds
      if (s->loopsRemaining() > 1 || s->loopsRemaining() == QSoundEffect::Infinite) {
        s->setLoopCount(0);
      }
    }

    // play sound
    if (alert.sound != AudibleAlert::NONE) {
      auto &[s, loops] = sounds[alert.sound];
      s->setLoopCount(loops);
      s->play();
    }
  }
}
<|endoftext|>


<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/ref_counted.h"
#include "media/base/data_buffer.h"
#include "remoting/jingle_glue/jingle_channel.h"
#include "remoting/jingle_glue/jingle_thread.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/libjingle/source/talk/base/stream.h"

using testing::_;
using testing::Return;
using testing::Mock;
using testing::SetArgumentPointee;

namespace remoting {

namespace {
// Size of test buffer in bytes.
const size_t kBufferSize = 100;
}  // namespace

class MockCallback : public JingleChannel::Callback {
 public:
  MOCK_METHOD2(OnStateChange, void(JingleChannel*, JingleChannel::State));
  MOCK_METHOD2(OnPacketReceived, void(JingleChannel*,
                                      scoped_refptr<media::DataBuffer>));
};

class MockStream : public talk_base::StreamInterface {
 public:
  virtual ~MockStream() {}
  MOCK_CONST_METHOD0(GetState, talk_base::StreamState());

  MOCK_METHOD4(Read, talk_base::StreamResult(void*, size_t, size_t*, int*));
  MOCK_METHOD4(Write, talk_base::StreamResult(const void*, size_t,
                                              size_t*, int*));
  MOCK_CONST_METHOD1(GetAvailable, bool(size_t*));
  MOCK_METHOD0(Close, void());

  MOCK_METHOD3(PostEvent, void(talk_base::Thread*, int, int));
  MOCK_METHOD2(PostEvent, void(int, int));
};

TEST(JingleChannelTest, Init) {
  JingleThread thread;

  MockStream* stream = new MockStream();
  MockCallback callback;

  EXPECT_CALL(*stream, GetState())
      .Times(1)
      .WillRepeatedly(Return(talk_base::SS_OPENING));

  scoped_refptr<JingleChannel> channel = new JingleChannel(&callback);

  EXPECT_CALL(callback, OnStateChange(channel.get(), JingleChannel::CONNECTING))
      .Times(1);

  thread.Start();

  EXPECT_EQ(JingleChannel::INITIALIZING, channel->state());
  channel->Init(&thread, stream, "user@domain.com");
  EXPECT_EQ(JingleChannel::CONNECTING, channel->state());
  channel->state_ = JingleChannel::CLOSED;

  thread.Stop();
}

TEST(JingleChannelTest, Write) {
  JingleThread thread;
  MockStream* stream = new MockStream();  // Freed by the channel.
  MockCallback callback;

  scoped_refptr<media::DataBuffer> data = new media::DataBuffer(kBufferSize);
  data->SetDataSize(kBufferSize);

  EXPECT_CALL(*stream, Write(static_cast<const void*>(data->GetData()),
                             kBufferSize, _, _))
      .WillOnce(DoAll(SetArgumentPointee<2>(kBufferSize),
                      Return(talk_base::SR_SUCCESS)));

  scoped_refptr<JingleChannel> channel = new JingleChannel(&callback);

  channel->thread_ = &thread;
  channel->stream_.reset(stream);
  channel->state_ = JingleChannel::OPEN;
  thread.Start();
  channel->Write(data);
  thread.Stop();
  channel->state_ = JingleChannel::CLOSED;
}

TEST(JingleChannelTest, Read) {
  JingleThread thread;
  MockStream* stream = new MockStream();  // Freed by the channel.
  MockCallback callback;

  scoped_refptr<media::DataBuffer> data = new media::DataBuffer(kBufferSize);
  data->SetDataSize(kBufferSize);

  scoped_refptr<JingleChannel> channel = new JingleChannel(&callback);

  EXPECT_CALL(callback, OnPacketReceived(channel.get(), _))
      .Times(1);

  EXPECT_CALL(*stream, GetAvailable(_))
      .WillOnce(DoAll(SetArgumentPointee<0>(kBufferSize),
                      Return(true)))
      .WillOnce(DoAll(SetArgumentPointee<0>(0),
                      Return(true)));

  EXPECT_CALL(*stream, Read(_, kBufferSize, _, _))
      .WillOnce(DoAll(SetArgumentPointee<2>(kBufferSize),
                      Return(talk_base::SR_SUCCESS)));

  channel->thread_ = &thread;
  channel->stream_.reset(stream);
  channel->state_ = JingleChannel::OPEN;
  thread.Start();
  channel->OnStreamEvent(stream, talk_base::SE_READ, 0);
  thread.Stop();
  channel->state_ = JingleChannel::CLOSED;
}

TEST(JingleChannelTest, Close) {
  JingleThread thread;
  MockStream* stream = new MockStream();  // Freed by the channel.
  MockCallback callback;

  EXPECT_CALL(*stream, Close())
      .Times(1);

  scoped_refptr<JingleChannel> channel = new JingleChannel(&callback);

  channel->thread_ = &thread;
  channel->stream_.reset(stream);
  channel->state_ = JingleChannel::OPEN;
  thread.Start();
  channel->Close();
  thread.Stop();
}

}  // namespace remoting
<commit_msg>Fixed GMock warning about unexpected call in remoting_unittests. BUG=None TEST=unittests<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/ref_counted.h"
#include "media/base/data_buffer.h"
#include "remoting/jingle_glue/jingle_channel.h"
#include "remoting/jingle_glue/jingle_thread.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/libjingle/source/talk/base/stream.h"

using testing::_;
using testing::Return;
using testing::Mock;
using testing::SetArgumentPointee;

namespace remoting {

namespace {
// Size of test buffer in bytes.
const size_t kBufferSize = 100;
}  // namespace

class MockCallback : public JingleChannel::Callback {
 public:
  MOCK_METHOD2(OnStateChange, void(JingleChannel*, JingleChannel::State));
  MOCK_METHOD2(OnPacketReceived, void(JingleChannel*,
                                      scoped_refptr<media::DataBuffer>));
};

class MockStream : public talk_base::StreamInterface {
 public:
  virtual ~MockStream() {}
  MOCK_CONST_METHOD0(GetState, talk_base::StreamState());

  MOCK_METHOD4(Read, talk_base::StreamResult(void*, size_t, size_t*, int*));
  MOCK_METHOD4(Write, talk_base::StreamResult(const void*, size_t,
                                              size_t*, int*));
  MOCK_CONST_METHOD1(GetAvailable, bool(size_t*));
  MOCK_METHOD0(Close, void());

  MOCK_METHOD3(PostEvent, void(talk_base::Thread*, int, int));
  MOCK_METHOD2(PostEvent, void(int, int));
};

TEST(JingleChannelTest, Init) {
  JingleThread thread;

  MockStream* stream = new MockStream();
  MockCallback callback;

  EXPECT_CALL(*stream, GetState())
      .Times(1)
      .WillRepeatedly(Return(talk_base::SS_OPENING));

  scoped_refptr<JingleChannel> channel = new JingleChannel(&callback);

  EXPECT_CALL(callback, OnStateChange(channel.get(), JingleChannel::CONNECTING))
      .Times(1);

  thread.Start();

  EXPECT_EQ(JingleChannel::INITIALIZING, channel->state());
  channel->Init(&thread, stream, "user@domain.com");
  EXPECT_EQ(JingleChannel::CONNECTING, channel->state());
  channel->state_ = JingleChannel::CLOSED;

  thread.Stop();
}

TEST(JingleChannelTest, Write) {
  JingleThread thread;
  MockStream* stream = new MockStream();  // Freed by the channel.
  MockCallback callback;

  scoped_refptr<media::DataBuffer> data = new media::DataBuffer(kBufferSize);
  data->SetDataSize(kBufferSize);

  EXPECT_CALL(*stream, Write(static_cast<const void*>(data->GetData()),
                             kBufferSize, _, _))
      .WillOnce(DoAll(SetArgumentPointee<2>(kBufferSize),
                      Return(talk_base::SR_SUCCESS)));

  scoped_refptr<JingleChannel> channel = new JingleChannel(&callback);

  channel->thread_ = &thread;
  channel->stream_.reset(stream);
  channel->state_ = JingleChannel::OPEN;
  thread.Start();
  channel->Write(data);
  thread.Stop();
  channel->state_ = JingleChannel::CLOSED;
}

TEST(JingleChannelTest, Read) {
  JingleThread thread;
  MockStream* stream = new MockStream();  // Freed by the channel.
  MockCallback callback;

  scoped_refptr<media::DataBuffer> data = new media::DataBuffer(kBufferSize);
  data->SetDataSize(kBufferSize);

  scoped_refptr<JingleChannel> channel = new JingleChannel(&callback);

  EXPECT_CALL(callback, OnPacketReceived(channel.get(), _))
      .Times(1);

  EXPECT_CALL(*stream, GetAvailable(_))
      .WillOnce(DoAll(SetArgumentPointee<0>(kBufferSize),
                      Return(true)))
      .WillOnce(DoAll(SetArgumentPointee<0>(0),
                      Return(true)));

  EXPECT_CALL(*stream, Read(_, kBufferSize, _, _))
      .WillOnce(DoAll(SetArgumentPointee<2>(kBufferSize),
                      Return(talk_base::SR_SUCCESS)));

  channel->thread_ = &thread;
  channel->stream_.reset(stream);
  channel->state_ = JingleChannel::OPEN;
  thread.Start();
  channel->OnStreamEvent(stream, talk_base::SE_READ, 0);
  thread.Stop();
  channel->state_ = JingleChannel::CLOSED;
}

TEST(JingleChannelTest, Close) {
  JingleThread thread;
  MockStream* stream = new MockStream();  // Freed by the channel.
  MockCallback callback;

  EXPECT_CALL(*stream, Close())
      .Times(1);

  scoped_refptr<JingleChannel> channel = new JingleChannel(&callback);

  channel->thread_ = &thread;
  channel->stream_.reset(stream);
  channel->state_ = JingleChannel::OPEN;

  EXPECT_CALL(callback, OnStateChange(channel.get(), JingleChannel::CLOSED))
      .Times(1);

  thread.Start();
  channel->Close();
  thread.Stop();
}

}  // namespace remoting
<|endoftext|>


<commit_before>#pragma once

#include "base/mappable.hpp"
#include "geometry/grassmann.hpp"
#include "geometry/linear_map.hpp"
#include "geometry/r3_element.hpp"
#include "geometry/sign.hpp"
#include "gtest/gtest_prod.h"
#include "serialization/geometry.pb.h"

namespace principia {
namespace geometry {

template<typename FromFrame, typename ToFrame>
class OrthogonalMap;

// A permutation of the coordinates. Obviously not coordinate-free, but
// practical.  There are no precision losses when composing or applying
// permutations.
template<typename FromFrame, typename ToFrame>
class Permutation : public LinearMap<FromFrame, ToFrame> {
  // Declare shorter names for the protocol buffer enums.
  static int const EVEN = serialization::Permutation::EVEN;
  static int const ODD = serialization::Permutation::ODD;
  static int const X = serialization::Permutation::X;
  static int const Y = serialization::Permutation::Y;
  static int const Z = serialization::Permutation::Z;
  static int const INDEX = serialization::Permutation::INDEX;
 public:
  // Danger, Will Robinson!  This enum is stored in the serialized
  // representation.  Any change to the formulae below is likely to make it
  // impossible to read existing files.
  enum CoordinatePermutation {
    XYZ = EVEN + (X << X * 2) + (Y << Y * 2) + (Z << Z * 2) + (0 << INDEX),
    YZX = EVEN + (Y << X * 2) + (Z << Y * 2) + (X << Z * 2) + (1 << INDEX),
    ZXY = EVEN + (Z << X * 2) + (X << Y * 2) + (Y << Z * 2) + (2 << INDEX),
    XZY = ODD  + (X << X * 2) + (Z << Y * 2) + (Y << Z * 2) + (3 << INDEX),
    ZYX = ODD  + (Z << X * 2) + (Y << Y * 2) + (X << Z * 2) + (4 << INDEX),
    YXZ = ODD  + (Y << X * 2) + (X << Y * 2) + (Z << Z * 2) + (5 << INDEX)
  };

  explicit Permutation(CoordinatePermutation const coordinate_permutation);
  ~Permutation() override = default;

  Sign Determinant() const override;

  Permutation<ToFrame, FromFrame> Inverse() const;

  template<typename Scalar>
  Vector<Scalar, ToFrame> operator()(
      Vector<Scalar, FromFrame> const& vector) const;

  template<typename Scalar>
  Bivector<Scalar, ToFrame> operator()(
      Bivector<Scalar, FromFrame> const& bivector) const;

  template<typename Scalar>
  Trivector<Scalar, ToFrame> operator()(
      Trivector<Scalar, FromFrame> const& trivector) const;

  template<typename T>
  typename base::Mappable<Permutation, T>::type operator()(T const& t) const;

  OrthogonalMap<FromFrame, ToFrame> Forget() const;

  static Permutation Identity();

  void WriteToMessage(not_null<serialization::LinearMap*> const message) const;
  static Permutation ReadFromMessage(serialization::LinearMap const& message);

  void WriteToMessage(
      not_null<serialization::Permutation*> const message) const;
  static Permutation ReadFromMessage(serialization::Permutation const& message);

 private:
  template<typename Scalar>
  R3Element<Scalar> operator()(R3Element<Scalar> const& r3_element) const;

  CoordinatePermutation coordinate_permutation_;

  template<typename From, typename Through, typename To>
  friend Permutation<From, To> operator*(
      Permutation<Through, To> const& left,
      Permutation<From, Through> const& right);

  // As much as I dislike FRIEND_TEST(), it seems like the most convenient way
  // to access the above operator.
  FRIEND_TEST(PermutationTest, Identity);
  FRIEND_TEST(PermutationTest, XYZ);
  FRIEND_TEST(PermutationTest, YZX);
  FRIEND_TEST(PermutationTest, ZXY);
  FRIEND_TEST(PermutationTest, XZY);
  FRIEND_TEST(PermutationTest, ZYX);
  FRIEND_TEST(PermutationTest, YXZ);
};

template<typename FromFrame, typename ThroughFrame, typename ToFrame>
Permutation<FromFrame, ToFrame> operator*(
    Permutation<ThroughFrame, ToFrame> const& left,
    Permutation<FromFrame, ThroughFrame> const& right);

}  // namespace geometry
}  // namespace principia

#include "geometry/permutation_body.hpp"
<commit_msg>Lint.<commit_after>#pragma once

#include "base/mappable.hpp"
#include "geometry/grassmann.hpp"
#include "geometry/linear_map.hpp"
#include "geometry/r3_element.hpp"
#include "geometry/sign.hpp"
#include "gtest/gtest_prod.h"
#include "serialization/geometry.pb.h"

namespace principia {
namespace geometry {

template<typename FromFrame, typename ToFrame>
class OrthogonalMap;

// A permutation of the coordinates. Obviously not coordinate-free, but
// practical.  There are no precision losses when composing or applying
// permutations.
template<typename FromFrame, typename ToFrame>
class Permutation : public LinearMap<FromFrame, ToFrame> {
  // Declare shorter names for the protocol buffer enums.
  static int const EVEN = serialization::Permutation::EVEN;
  static int const ODD = serialization::Permutation::ODD;
  static int const X = serialization::Permutation::X;
  static int const Y = serialization::Permutation::Y;
  static int const Z = serialization::Permutation::Z;
  static int const INDEX = serialization::Permutation::INDEX;

 public:
  // Danger, Will Robinson!  This enum is stored in the serialized
  // representation.  Any change to the formulae below is likely to make it
  // impossible to read existing files.
  enum CoordinatePermutation {
    XYZ = EVEN + (X << X * 2) + (Y << Y * 2) + (Z << Z * 2) + (0 << INDEX),
    YZX = EVEN + (Y << X * 2) + (Z << Y * 2) + (X << Z * 2) + (1 << INDEX),
    ZXY = EVEN + (Z << X * 2) + (X << Y * 2) + (Y << Z * 2) + (2 << INDEX),
    XZY = ODD  + (X << X * 2) + (Z << Y * 2) + (Y << Z * 2) + (3 << INDEX),
    ZYX = ODD  + (Z << X * 2) + (Y << Y * 2) + (X << Z * 2) + (4 << INDEX),
    YXZ = ODD  + (Y << X * 2) + (X << Y * 2) + (Z << Z * 2) + (5 << INDEX)
  };

  explicit Permutation(CoordinatePermutation const coordinate_permutation);
  ~Permutation() override = default;

  Sign Determinant() const override;

  Permutation<ToFrame, FromFrame> Inverse() const;

  template<typename Scalar>
  Vector<Scalar, ToFrame> operator()(
      Vector<Scalar, FromFrame> const& vector) const;

  template<typename Scalar>
  Bivector<Scalar, ToFrame> operator()(
      Bivector<Scalar, FromFrame> const& bivector) const;

  template<typename Scalar>
  Trivector<Scalar, ToFrame> operator()(
      Trivector<Scalar, FromFrame> const& trivector) const;

  template<typename T>
  typename base::Mappable<Permutation, T>::type operator()(T const& t) const;

  OrthogonalMap<FromFrame, ToFrame> Forget() const;

  static Permutation Identity();

  void WriteToMessage(not_null<serialization::LinearMap*> const message) const;
  static Permutation ReadFromMessage(serialization::LinearMap const& message);

  void WriteToMessage(
      not_null<serialization::Permutation*> const message) const;
  static Permutation ReadFromMessage(serialization::Permutation const& message);

 private:
  template<typename Scalar>
  R3Element<Scalar> operator()(R3Element<Scalar> const& r3_element) const;

  CoordinatePermutation coordinate_permutation_;

  template<typename From, typename Through, typename To>
  friend Permutation<From, To> operator*(
      Permutation<Through, To> const& left,
      Permutation<From, Through> const& right);

  // As much as I dislike FRIEND_TEST(), it seems like the most convenient way
  // to access the above operator.
  FRIEND_TEST(PermutationTest, Identity);
  FRIEND_TEST(PermutationTest, XYZ);
  FRIEND_TEST(PermutationTest, YZX);
  FRIEND_TEST(PermutationTest, ZXY);
  FRIEND_TEST(PermutationTest, XZY);
  FRIEND_TEST(PermutationTest, ZYX);
  FRIEND_TEST(PermutationTest, YXZ);
};

template<typename FromFrame, typename ThroughFrame, typename ToFrame>
Permutation<FromFrame, ToFrame> operator*(
    Permutation<ThroughFrame, ToFrame> const& left,
    Permutation<FromFrame, ThroughFrame> const& right);

}  // namespace geometry
}  // namespace principia

#include "geometry/permutation_body.hpp"
<|endoftext|>


<commit_before>/***************************************************************************
 *   Copyright (C) 2006 by Tobias Koenig <tokoe@kde.org>                   *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU Library 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 Library General Public     *
 *   License along with this program; if not, write to the                 *
 *   Free Software Foundation, Inc.,                                       *
 *   51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.         *
 ***************************************************************************/

#include <QtCore/QStringList>
#include <QtCore/QUuid>
#include <QtCore/QVariant>
#include <QtSql/QSqlDatabase>
#include <QtSql/QSqlError>
#include <QtSql/QSqlQuery>

#include "akonadi.h"
#include "akonadiconnection.h"
#include "imapparser.h"
#include "fetchquery.h"
#include "response.h"

#include "fetch.h"

using namespace Akonadi;

Fetch::Fetch()
  : Handler()
{
}

Fetch::~Fetch()
{
}

bool Fetch::handleLine( const QByteArray& line )
{
  Response response;
  response.setUntagged();

  int start = line.indexOf( ' ' ); // skip tag

  FetchQuery fetchQuery;
  if ( !fetchQuery.parse( line.mid( start + 1 ) ) ) {
    response.setTag( tag() );
    response.setError();
    response.setString( "Syntax error" );

    emit responseAvailable( response );
    deleteLater();

    return true;
  }

  DataStore *store = connection()->storageBackend();

  QList<PimItem> pimItems;
  if ( connection()->selectedLocation().id() == -1 ) {
    pimItems = store->fetchMatchingPimItemsByUID( fetchQuery );
  } else {
    if ( fetchQuery.isUidFetch() ) {
      pimItems = store->fetchMatchingPimItemsByUID( fetchQuery, connection()->selectedLocation() ) ;
    } else {
      pimItems = store->fetchMatchingPimItemsBySequenceNumbers( fetchQuery, connection()->selectedLocation() );
    }
  }

  for ( int i = 0; i < pimItems.count(); ++i ) {
    response.setUntagged();
    response.setString( buildResponse( pimItems[ i ], fetchQuery ) );
    emit responseAvailable( response );
  }

  response.setTag( tag() );
  response.setSuccess();

  if ( fetchQuery.isUidFetch() )
    response.setString( "UID FETCH completed" );
  else
    response.setString( "FETCH completed" );

  emit responseAvailable( response );

  deleteLater();

  return true;
}

QByteArray Fetch::buildResponse( const PimItem &item, const FetchQuery &fetchQuery  )
{
  QList<QByteArray> attributes;
  if ( fetchQuery.hasAttributeType( FetchQuery::Attribute::Envelope ) ) {
    attributes.append( "ENVELOPE " + buildEnvelope( item, fetchQuery ) );
  }

  if ( fetchQuery.hasAttributeType( FetchQuery::Attribute::Flags ) ) {
    QList<Flag> flagList = item.flags();

    QList<QByteArray> flags;
    for ( int i = 0; i < flagList.count(); ++i )
      flags.append( flagList[ i ].name().toUtf8() );

    MimeType mimeType = item.mimeType();
    flags.append( "\\MimeTypes[" + mimeType.name().toUtf8() + ']' );

    attributes.append( "FLAGS (" + ImapParser::join( flags, " " ) + ')' );
  }

  if ( fetchQuery.hasAttributeType( FetchQuery::Attribute::InternalDate ) ) {
  }

  if ( fetchQuery.hasAttributeType( FetchQuery::Attribute::RFC822 ) ||
       fetchQuery.hasAttributeType( FetchQuery::Attribute::RFC822_Text ) ||
       fetchQuery.hasAttributeType( FetchQuery::Attribute::Body ) ) {
    attributes.append( "RFC822 {" + QByteArray::number( item.data().length() ) +
                       "}\r\n" + item.data() );
  }

  if ( fetchQuery.hasAttributeType( FetchQuery::Attribute::RFC822_Header ) ) {
  }

  if ( fetchQuery.hasAttributeType( FetchQuery::Attribute::RFC822_Size ) ) {
    attributes.append( "RFC822.SIZE " + QByteArray::number( item.data().length() ) );
  }

  if ( fetchQuery.hasAttributeType( FetchQuery::Attribute::Body_Structure ) ) {
  }

  if ( fetchQuery.hasAttributeType( FetchQuery::Attribute::Uid ) || fetchQuery.isUidFetch() ) {
    attributes.append( "UID " + QByteArray::number( item.id() ) );
  }

  if ( fetchQuery.hasAttributeType( FetchQuery::Attribute::RemoteId ) ) {
    attributes.append( "REMOTEID " + item.remoteId() );
  }

  QByteArray attributesString;
  for ( int i = 0; i < attributes.count(); ++i ) {
    if ( i != 0 )
      attributesString += ' ' + attributes[ i ];
    else
      attributesString += attributes[ i ];
  }

  int itemPosition = connection()->storageBackend()->pimItemPosition( item );

  if ( attributes.isEmpty() )
    return QByteArray::number( itemPosition ) + " FETCH";
  else
    return QByteArray::number( itemPosition ) + " FETCH (" + attributesString + ')';
}

// FIXME build from database
QByteArray Fetch::buildEnvelope( const PimItem&, const FetchQuery& )
{
  const QByteArray date( "\"Wed, 1 Feb 2006 13:37:19 UT\"" );
  const QByteArray subject( "\"IMPORTANT: Akonadi Test\"" );
  const QByteArray from( "\"Tobias Koenig\" NIL \"tokoe\" \"kde.org\"" );
  const QByteArray sender = from;
  const QByteArray replyTo( "NIL" );
  const QByteArray to( "\"Ingo Kloecker\" NIL \"kloecker\" \"kde.org\"" );
  const QByteArray cc( "NIL" );
  const QByteArray bcc( "NIL" );
  const QByteArray inReplyTo( "NIL" );
  const QByteArray messageId( '<' + QUuid::createUuid().toString().toLatin1() + "@server.kde.org>" );

  return QByteArray( '('+date+' '+subject+" (("+from+")) (("+sender+")) "+replyTo+" (("+to+")) "+cc+' '+bcc+' '+inReplyTo+' '+messageId+')' );
}
<commit_msg>Get rid of some unecessary ugly IMAP compatibility hack.<commit_after>/***************************************************************************
 *   Copyright (C) 2006 by Tobias Koenig <tokoe@kde.org>                   *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU Library 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 Library General Public     *
 *   License along with this program; if not, write to the                 *
 *   Free Software Foundation, Inc.,                                       *
 *   51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.         *
 ***************************************************************************/

#include <QtCore/QStringList>
#include <QtCore/QUuid>
#include <QtCore/QVariant>
#include <QtSql/QSqlDatabase>
#include <QtSql/QSqlError>
#include <QtSql/QSqlQuery>

#include "akonadi.h"
#include "akonadiconnection.h"
#include "imapparser.h"
#include "fetchquery.h"
#include "response.h"

#include "fetch.h"

using namespace Akonadi;

Fetch::Fetch()
  : Handler()
{
}

Fetch::~Fetch()
{
}

bool Fetch::handleLine( const QByteArray& line )
{
  Response response;
  response.setUntagged();

  int start = line.indexOf( ' ' ); // skip tag

  FetchQuery fetchQuery;
  if ( !fetchQuery.parse( line.mid( start + 1 ) ) ) {
    response.setTag( tag() );
    response.setError();
    response.setString( "Syntax error" );

    emit responseAvailable( response );
    deleteLater();

    return true;
  }

  DataStore *store = connection()->storageBackend();

  QList<PimItem> pimItems;
  if ( connection()->selectedLocation().id() == -1 ) {
    pimItems = store->fetchMatchingPimItemsByUID( fetchQuery );
  } else {
    if ( fetchQuery.isUidFetch() ) {
      pimItems = store->fetchMatchingPimItemsByUID( fetchQuery, connection()->selectedLocation() ) ;
    } else {
      pimItems = store->fetchMatchingPimItemsBySequenceNumbers( fetchQuery, connection()->selectedLocation() );
    }
  }

  for ( int i = 0; i < pimItems.count(); ++i ) {
    response.setUntagged();
    response.setString( buildResponse( pimItems[ i ], fetchQuery ) );
    emit responseAvailable( response );
  }

  response.setTag( tag() );
  response.setSuccess();

  if ( fetchQuery.isUidFetch() )
    response.setString( "UID FETCH completed" );
  else
    response.setString( "FETCH completed" );

  emit responseAvailable( response );

  deleteLater();

  return true;
}

QByteArray Fetch::buildResponse( const PimItem &item, const FetchQuery &fetchQuery  )
{
  QList<QByteArray> attributes;
  if ( fetchQuery.hasAttributeType( FetchQuery::Attribute::Envelope ) ) {
    attributes.append( "ENVELOPE " + buildEnvelope( item, fetchQuery ) );
  }

  if ( fetchQuery.hasAttributeType( FetchQuery::Attribute::Flags ) ) {
    QList<Flag> flagList = item.flags();

    QList<QByteArray> flags;
    for ( int i = 0; i < flagList.count(); ++i )
      flags.append( flagList[ i ].name().toUtf8() );

    MimeType mimeType = item.mimeType();
    attributes.append( "MIMETYPE \"" + mimeType.name().toUtf8() + "\"" );

    attributes.append( "FLAGS (" + ImapParser::join( flags, " " ) + ')' );
  }

  if ( fetchQuery.hasAttributeType( FetchQuery::Attribute::InternalDate ) ) {
  }

  if ( fetchQuery.hasAttributeType( FetchQuery::Attribute::RFC822 ) ||
       fetchQuery.hasAttributeType( FetchQuery::Attribute::RFC822_Text ) ||
       fetchQuery.hasAttributeType( FetchQuery::Attribute::Body ) ) {
    attributes.append( "RFC822 {" + QByteArray::number( item.data().length() ) +
                       "}\r\n" + item.data() );
  }

  if ( fetchQuery.hasAttributeType( FetchQuery::Attribute::RFC822_Header ) ) {
  }

  if ( fetchQuery.hasAttributeType( FetchQuery::Attribute::RFC822_Size ) ) {
    attributes.append( "RFC822.SIZE " + QByteArray::number( item.data().length() ) );
  }

  if ( fetchQuery.hasAttributeType( FetchQuery::Attribute::Body_Structure ) ) {
  }

  if ( fetchQuery.hasAttributeType( FetchQuery::Attribute::Uid ) || fetchQuery.isUidFetch() ) {
    attributes.append( "UID " + QByteArray::number( item.id() ) );
  }

  if ( fetchQuery.hasAttributeType( FetchQuery::Attribute::RemoteId ) ) {
    attributes.append( "REMOTEID " + item.remoteId() );
  }

  QByteArray attributesString;
  for ( int i = 0; i < attributes.count(); ++i ) {
    if ( i != 0 )
      attributesString += ' ' + attributes[ i ];
    else
      attributesString += attributes[ i ];
  }

  int itemPosition = connection()->storageBackend()->pimItemPosition( item );

  if ( attributes.isEmpty() )
    return QByteArray::number( itemPosition ) + " FETCH";
  else
    return QByteArray::number( itemPosition ) + " FETCH (" + attributesString + ')';
}

// FIXME build from database
QByteArray Fetch::buildEnvelope( const PimItem&, const FetchQuery& )
{
  const QByteArray date( "\"Wed, 1 Feb 2006 13:37:19 UT\"" );
  const QByteArray subject( "\"IMPORTANT: Akonadi Test\"" );
  const QByteArray from( "\"Tobias Koenig\" NIL \"tokoe\" \"kde.org\"" );
  const QByteArray sender = from;
  const QByteArray replyTo( "NIL" );
  const QByteArray to( "\"Ingo Kloecker\" NIL \"kloecker\" \"kde.org\"" );
  const QByteArray cc( "NIL" );
  const QByteArray bcc( "NIL" );
  const QByteArray inReplyTo( "NIL" );
  const QByteArray messageId( '<' + QUuid::createUuid().toString().toLatin1() + "@server.kde.org>" );

  return QByteArray( '('+date+' '+subject+" (("+from+")) (("+sender+")) "+replyTo+" (("+to+")) "+cc+' '+bcc+' '+inReplyTo+' '+messageId+')' );
}
<|endoftext|>


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

#ifndef _BASMGR_HXX //autogen
#include <basic/basmgr.hxx>
#endif
#ifndef _SB_SBSTAR_HXX //autogen
#include <basic/sbstar.hxx>
#endif

#ifdef WIN
#define _TL_LANG_SPECIAL
#endif

#ifndef _SVDDE_HXX //autogen
#include <svtools/svdde.hxx>
#endif
#ifndef _MSGBOX_HXX //autogen
#include <vcl/msgbox.hxx>
#endif

#ifndef _SFXENUMITEM_HXX
#include <svtools/eitem.hxx>
#endif

#include <svtools/inethist.hxx>
#include <svtools/saveopt.hxx>

#pragma hdrstop

#include "app.hrc"
#include "app.hxx"
#include "unoctitm.hxx"
#include "appdata.hxx"
#include "viewsh.hxx"
#include "dispatch.hxx"
#include "printer.hxx"
#include "plugobj.hxx"
#include "arrdecl.hxx"
#include "sfxresid.hxx"
#include "newhdl.hxx"
#include "cfgmgr.hxx"
#include "accmgr.hxx"
#include "event.hxx"
#include "macrconf.hxx"
#include "mnumgr.hxx"
#include "imgmgr.hxx"
#include "templdlg.hxx"
#include "tbxconf.hxx"
#include "msgpool.hxx"
#include "frameobj.hxx"
#include "docfile.hxx"
#include "sfxtypes.hxx"
#include "appimp.hxx"
#include "sfxlocal.hrc"
#include "dataurl.hxx"
#include "fcontnr.hxx"
#include "nochaos.hxx"
#include "appuno.hxx"
#include "doctempl.hxx"
#include "viewfrm.hxx"
#include "bmkmenu.hxx"
#include "objsh.hxx"
#include "dlgcont.hxx"
#include "scriptcont.hxx"
#include <svtools/misccfg.hxx>
#include "docfac.hxx"

#ifndef PRODUCT
DECLARE_LIST( SfxFrameWindowFactoryArray_Impl, SfxFrameWindowFactory* )
SV_DECL_PTRARR(SfxInitLinkList, Link*, 2, 2);
#endif

//===================================================================
/*
void SfxApplication::Quit()
{
    QueryExit_Impl();
}
*/
//--------------------------------------------------------------------
BOOL SfxApplication::QueryExit_Impl()

/*  [Beschreibung]

    Liefert FALSE, wenn entweder ein modaler Dialog offen ist, oder
    der Printer einer SfxViewShell einen laufenden Druckjob hat.

    [Anmerkung]

    Wenn diese aus StarView stammende virtuelle Methode vom Applikations-
    entwickler "uberladen wird, mu"s diese SfxApplication::QueryExit() rufen
    und falls diese FALSE zur"uckgibt, ebenfalls FALSE zur"uckgeben.
*/

{
    SaveConfiguration();
    BOOL bQuit = TRUE;

/*
    BOOL bPrinting = FALSE;
    for ( SfxViewShell *pViewSh = SfxViewShell::GetFirst();
          !bPrinting && pViewSh;
          pViewSh = SfxViewShell::GetNext(*pViewSh) )
    {
        SfxPrinter *pPrinter = pViewSh->GetPrinter();
        bPrinting = pPrinter && pPrinter->IsPrinting();
    }

    if ( bPrinting )
    {
        // Benutzer fragen, ob abgebrochen werden soll
        if ( RET_OK == QueryBox( 0, SfxResId( MSG_ISPRINTING_QUERYABORT ) ).Execute() )
        {
            // alle Jobs canceln
            for ( SfxViewShell *pViewSh = SfxViewShell::GetFirst();
                  !bPrinting && pViewSh;
                  pViewSh = SfxViewShell::GetNext(*pViewSh) )
            {
                SfxPrinter *pPrinter = pViewSh->GetPrinter();
                if ( pPrinter && pPrinter->IsPrinting() )
                    pPrinter->AbortJob();
            }

            // da das Canceln asynchron ist, Quit erstmal wieder verlassen
            GetDispatcher_Impl()->Execute( SID_QUITAPP, SFX_CALLMODE_ASYNCHRON );
            DBG_TRACE( "QueryExit => FALSE (printing)" );
            return FALSE;
        }
    }
*/
    // alles canceln was zu canceln ist
    GetCancelManager()->Cancel(TRUE);

/*
    SfxObjectShell *pLastDocSh = SfxObjectShell::GetFirst();
    if ( bQuit )
    {
        // Jetzt zur Sicherheit auch hidden Frames abr"aumen
        SfxViewFrame::CloseHiddenFrames_Impl();
        pLastDocSh = SfxObjectShell::GetFirst();
    }
*/
    // will trotzdem noch jemand, den man nicht abschiessen kann, die App haben?
    if ( !bQuit )
    {
        // nicht wirklich beenden, nur minimieren
        pAppData_Impl->bOLEResize = TRUE;
        InfoBox aInfoBox( NULL, SfxResId(MSG_CANT_QUIT) );
        aInfoBox.Execute();
        DBG_TRACE( "QueryExit => FALSE (in use)" );
        return FALSE;
    }

    return TRUE;
}

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

void SfxApplication::Deinitialize()
{
    if ( bDowning )
        return;

    // Falls man nochmal beim Runterfahren in ein Reschedule l"auft
    pAppData_Impl->EndListening( *this );
    if ( pAppData_Impl->pCancelMgr )
        pAppData_Impl->EndListening( *pAppData_Impl->pCancelMgr );

    //!Wait();
    StarBASIC::Stop();

    // ggf. BASIC speichern
    if ( pImp->pBasicMgr && pImp->pBasicMgr->IsModified() )
        SaveBasicManager();

    SaveBasicContainer();
    SaveDialogContainer();

    bDowning = TRUE; // wegen Timer aus DecAliveCount und QueryExit

    DELETEZ( pAppData_Impl->pTemplates );

    DELETEZ(pImp->pTemplateDlg);
    SetViewFrame(0);
    bDowning = FALSE;
    DBG_ASSERT( !SfxViewFrame::GetFirst(),
                "existing SfxViewFrame after Execute" );
    DBG_ASSERT( !SfxObjectShell::GetFirst(),
                "existing SfxObjectShell after Execute" );
    pAppDispat->Pop( *this, SFX_SHELL_POP_UNTIL );
    pAppDispat->Flush();
    bDowning = TRUE;
    pAppDispat->DoDeactivate_Impl( TRUE );

    INetURLHistory::Delete();

    // call derived application-exit
    bInExit = TRUE;
    Exit();

    // Controller u."a. freigeben
    // dabei sollten auch restliche Komponenten ( Beamer! ) verschwinden
    DELETEZ(pMenuMgr);
    DELETEZ(pAcceleratorMgr);
    SfxObjectFactory::ClearAll_Impl();
    DELETEZ( pImp->pBasicMgr );
    if( pImp->pBasicLibContainer )
        pImp->pBasicLibContainer->release();
    if( pImp->pDialogLibContainer )
        pImp->pDialogLibContainer->release();

    bInExit = FALSE;

    DBG_ASSERT( pViewFrame == 0, "active foreign ViewFrame" );

    delete[] pInterfaces, pInterfaces = 0;
    DELETEZ(pImageMgr);

    // free administration managers
    DELETEZ(pImp->pAutoSaveTimer);
    DELETEZ(pAppDispat);
    SfxResId::DeleteResMgr();
    DELETEZ(pImp->pOfaResMgr);

    // ab hier d"urfen keine SvObjects mehr existieren
    DELETEX(pAppData_Impl->pMatcher);
    DELETEX(pAppData_Impl->pSfxFrameObjectFactoryPtr);
    DELETEX(pAppData_Impl->pSfxPluginObjectFactoryPtr);

    delete pAppData_Impl->pLabelResMgr;

#ifndef PRODUCT
    DELETEX(pSlotPool);
    DELETEX(pAppData_Impl->pEventConfig);
    DELETEX(pAppData_Impl->pMiscConfig);
    SfxMacroConfig::Release_Impl();
    DELETEX(pAppData_Impl->pVerbs);
    DELETEX(pAppData_Impl->pFactArr);
    DELETEX(pAppData_Impl->pInitLinkList);
#endif

#ifndef PRODUCT
    DELETEX(pImp->pTbxCtrlFac);
    DELETEX(pImp->pStbCtrlFac);
    DELETEX(pImp->pMenuCtrlFac);
    DELETEX(pImp->pEventHdl);
    SfxNewHdl::Delete();
    DELETEX(pImp->pAutoSaveTimer);
    DELETEX(pImp->pViewFrames);
    DELETEX(pImp->pViewShells);
    DELETEX(pImp->pObjShells);
#endif

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

#ifndef _BASMGR_HXX //autogen
#include <basic/basmgr.hxx>
#endif
#ifndef _SB_SBSTAR_HXX //autogen
#include <basic/sbstar.hxx>
#endif

#ifdef WIN
#define _TL_LANG_SPECIAL
#endif

#ifndef _SVDDE_HXX //autogen
#include <svtools/svdde.hxx>
#endif
#ifndef _MSGBOX_HXX //autogen
#include <vcl/msgbox.hxx>
#endif

#ifndef _SFXENUMITEM_HXX
#include <svtools/eitem.hxx>
#endif

#include <svtools/inethist.hxx>
#include <svtools/saveopt.hxx>

#ifndef GCC
#pragma hdrstop
#endif

#include "app.hrc"
#include "app.hxx"
#include "unoctitm.hxx"
#include "appdata.hxx"
#include "viewsh.hxx"
#include "dispatch.hxx"
#include "printer.hxx"
#include "plugobj.hxx"
#include "arrdecl.hxx"
#include "sfxresid.hxx"
#include "newhdl.hxx"
#include "cfgmgr.hxx"
#include "accmgr.hxx"
#include "event.hxx"
#include "macrconf.hxx"
#include "mnumgr.hxx"
#include "imgmgr.hxx"
#include "templdlg.hxx"
#include "tbxconf.hxx"
#include "msgpool.hxx"
#include "frameobj.hxx"
#include "docfile.hxx"
#include "sfxtypes.hxx"
#include "appimp.hxx"
#include "sfxlocal.hrc"
#include "dataurl.hxx"
#include "fcontnr.hxx"
#include "nochaos.hxx"
#include "appuno.hxx"
#include "doctempl.hxx"
#include "viewfrm.hxx"
#include "bmkmenu.hxx"
#include "objsh.hxx"
#include "dlgcont.hxx"
#include "scriptcont.hxx"
#include <svtools/misccfg.hxx>
#include "docfac.hxx"

#ifndef PRODUCT
DECLARE_LIST( SfxFrameWindowFactoryArray_Impl, SfxFrameWindowFactory* )
SV_DECL_PTRARR(SfxInitLinkList, Link*, 2, 2);
#endif

//===================================================================
/*
void SfxApplication::Quit()
{
    QueryExit_Impl();
}
*/
//--------------------------------------------------------------------
BOOL SfxApplication::QueryExit_Impl()

/*  [Beschreibung]

    Liefert FALSE, wenn entweder ein modaler Dialog offen ist, oder
    der Printer einer SfxViewShell einen laufenden Druckjob hat.

    [Anmerkung]

    Wenn diese aus StarView stammende virtuelle Methode vom Applikations-
    entwickler "uberladen wird, mu"s diese SfxApplication::QueryExit() rufen
    und falls diese FALSE zur"uckgibt, ebenfalls FALSE zur"uckgeben.
*/

{
    SaveConfiguration();
    BOOL bQuit = TRUE;

/*
    BOOL bPrinting = FALSE;
    for ( SfxViewShell *pViewSh = SfxViewShell::GetFirst();
          !bPrinting && pViewSh;
          pViewSh = SfxViewShell::GetNext(*pViewSh) )
    {
        SfxPrinter *pPrinter = pViewSh->GetPrinter();
        bPrinting = pPrinter && pPrinter->IsPrinting();
    }

    if ( bPrinting )
    {
        // Benutzer fragen, ob abgebrochen werden soll
        if ( RET_OK == QueryBox( 0, SfxResId( MSG_ISPRINTING_QUERYABORT ) ).Execute() )
        {
            // alle Jobs canceln
            for ( SfxViewShell *pViewSh = SfxViewShell::GetFirst();
                  !bPrinting && pViewSh;
                  pViewSh = SfxViewShell::GetNext(*pViewSh) )
            {
                SfxPrinter *pPrinter = pViewSh->GetPrinter();
                if ( pPrinter && pPrinter->IsPrinting() )
                    pPrinter->AbortJob();
            }

            // da das Canceln asynchron ist, Quit erstmal wieder verlassen
            GetDispatcher_Impl()->Execute( SID_QUITAPP, SFX_CALLMODE_ASYNCHRON );
            DBG_TRACE( "QueryExit => FALSE (printing)" );
            return FALSE;
        }
    }
*/
    // alles canceln was zu canceln ist
    GetCancelManager()->Cancel(TRUE);

/*
    SfxObjectShell *pLastDocSh = SfxObjectShell::GetFirst();
    if ( bQuit )
    {
        // Jetzt zur Sicherheit auch hidden Frames abr"aumen
        SfxViewFrame::CloseHiddenFrames_Impl();
        pLastDocSh = SfxObjectShell::GetFirst();
    }
*/
    // will trotzdem noch jemand, den man nicht abschiessen kann, die App haben?
    if ( !bQuit )
    {
        // nicht wirklich beenden, nur minimieren
        pAppData_Impl->bOLEResize = TRUE;
        InfoBox aInfoBox( NULL, SfxResId(MSG_CANT_QUIT) );
        aInfoBox.Execute();
        DBG_TRACE( "QueryExit => FALSE (in use)" );
        return FALSE;
    }

    return TRUE;
}

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

void SfxApplication::Deinitialize()
{
    if ( bDowning )
        return;

    // Falls man nochmal beim Runterfahren in ein Reschedule l"auft
    pAppData_Impl->EndListening( *this );
    if ( pAppData_Impl->pCancelMgr )
        pAppData_Impl->EndListening( *pAppData_Impl->pCancelMgr );

    //!Wait();
    StarBASIC::Stop();

    // ggf. BASIC speichern
    if ( pImp->pBasicMgr && pImp->pBasicMgr->IsModified() )
        SaveBasicManager();

    SaveBasicContainer();
    SaveDialogContainer();

    bDowning = TRUE; // wegen Timer aus DecAliveCount und QueryExit

    DELETEZ( pAppData_Impl->pTemplates );

    DELETEZ(pImp->pTemplateDlg);
    SetViewFrame(0);
    bDowning = FALSE;
    DBG_ASSERT( !SfxViewFrame::GetFirst(),
                "existing SfxViewFrame after Execute" );
    DBG_ASSERT( !SfxObjectShell::GetFirst(),
                "existing SfxObjectShell after Execute" );
    pAppDispat->Pop( *this, SFX_SHELL_POP_UNTIL );
    pAppDispat->Flush();
    bDowning = TRUE;
    pAppDispat->DoDeactivate_Impl( TRUE );

    INetURLHistory::Delete();

    // call derived application-exit
    bInExit = TRUE;
    Exit();

    // Controller u."a. freigeben
    // dabei sollten auch restliche Komponenten ( Beamer! ) verschwinden
    DELETEZ(pMenuMgr);
    DELETEZ(pAcceleratorMgr);
    SfxObjectFactory::ClearAll_Impl();
    DELETEZ( pImp->pBasicMgr );
    if( pImp->pBasicLibContainer )
        pImp->pBasicLibContainer->release();
    if( pImp->pDialogLibContainer )
        pImp->pDialogLibContainer->release();

    bInExit = FALSE;

    DBG_ASSERT( pViewFrame == 0, "active foreign ViewFrame" );

    delete[] pInterfaces, pInterfaces = 0;
    DELETEZ(pImageMgr);

    // free administration managers
    DELETEZ(pImp->pAutoSaveTimer);
    DELETEZ(pAppDispat);
    SfxResId::DeleteResMgr();
    DELETEZ(pImp->pOfaResMgr);

    // ab hier d"urfen keine SvObjects mehr existieren
    DELETEX(pAppData_Impl->pMatcher);
    DELETEX(pAppData_Impl->pSfxFrameObjectFactoryPtr);
    DELETEX(pAppData_Impl->pSfxPluginObjectFactoryPtr);

    delete pAppData_Impl->pLabelResMgr;

#ifndef PRODUCT
    DELETEX(pSlotPool);
    DELETEX(pAppData_Impl->pEventConfig);
    DELETEX(pAppData_Impl->pMiscConfig);
    SfxMacroConfig::Release_Impl();
    DELETEX(pAppData_Impl->pVerbs);
    DELETEX(pAppData_Impl->pFactArr);
    DELETEX(pAppData_Impl->pInitLinkList);
#endif

#ifndef PRODUCT
    DELETEX(pImp->pTbxCtrlFac);
    DELETEX(pImp->pStbCtrlFac);
    DELETEX(pImp->pMenuCtrlFac);
    DELETEX(pImp->pEventHdl);
    SfxNewHdl::Delete();
    DELETEX(pImp->pAutoSaveTimer);
    DELETEX(pImp->pViewFrames);
    DELETEX(pImp->pViewShells);
    DELETEX(pImp->pObjShells);
#endif

    NoChaos::ReleaseItemPool();
    pAppData_Impl->pPool = NULL;
}
<|endoftext|>


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

#include "ctrlitem.hxx"
#ifndef _LINK_HXX
#include <tools/link.hxx>
#endif

class SfxCommonTemplateDialog_Impl;

class SfxTemplateControllerItem: public SfxControllerItem {
    SfxCommonTemplateDialog_Impl  &rTemplateDlg;
    BYTE                            nWaterCanState;
    long                            nUserEventId;

    DECL_STATIC_LINK(SfxTemplateControllerItem, SetWaterCanStateHdl_Impl,
                                SfxTemplateControllerItem*);

protected:
    virtual void    StateChanged( USHORT, SfxItemState, const SfxPoolItem* pState );

public:
    SfxTemplateControllerItem( USHORT nId, SfxCommonTemplateDialog_Impl &rDlg, SfxBindings &);
    ~SfxTemplateControllerItem();
};

#endif
<commit_msg>INTEGRATION: CWS vgbugs07 (1.4.520); FILE MERGED 2007/06/04 13:34:58 vg 1.4.520.1: #i76605# Remove -I .../inc/module hack introduced by hedaburemove01<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: tplcitem.hxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: hr $ $Date: 2007-06-27 23:29:54 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/
#ifndef _TPLCITEM_HXX
#define _TPLCITEM_HXX

#include <sfx2/ctrlitem.hxx>
#ifndef _LINK_HXX
#include <tools/link.hxx>
#endif

class SfxCommonTemplateDialog_Impl;

class SfxTemplateControllerItem: public SfxControllerItem {
    SfxCommonTemplateDialog_Impl  &rTemplateDlg;
    BYTE                            nWaterCanState;
    long                            nUserEventId;

    DECL_STATIC_LINK(SfxTemplateControllerItem, SetWaterCanStateHdl_Impl,
                                SfxTemplateControllerItem*);

protected:
    virtual void    StateChanged( USHORT, SfxItemState, const SfxPoolItem* pState );

public:
    SfxTemplateControllerItem( USHORT nId, SfxCommonTemplateDialog_Impl &rDlg, SfxBindings &);
    ~SfxTemplateControllerItem();
};

#endif
<|endoftext|>