<commit_before>#include <ast/op-expr.hh>

namespace ast
{
    OpExpr::OpExpr(const yy::location& location,
                   Expr* lexpr,
                   OpExpr::Operator op,
                   Expr* rexpr)
        : Expr(location)
        , lexpr_(lexpr)
        , rexpr_(rexpr)
        , op_(op)
    {}

    OpExpr::~OpExpr()
    {
        delete lexpr_;
        delete rexpr_;
    }

    const Expr* OpExpr::left_expr_get() const
    {
        return lexpr_;
    }

    Expr* OpExpr::left_expr_get()
    {
        return lexpr_;
    }

    const Expr* OpExpr::right_expr_get() const
    {
        return rexpr_;
    }

    Expr* OpExpr::right_expr_get()
    {
        return rexpr_;
    }

    OpExpr::Operator OpExpr::op_get() const
    {
        return op_;
    }

    std::string OpExpr::op_to_string() const
    {
        switch (op_)
        {
            case PLUS:
                return "+";
            case MINUS:
                return "-";
            case MULT:
                return "*";
            case DIV:
                return "/";
            case FDIV:
                return "//";
            case MOD:
                return "%";
            case POW:
                return "**";
            case RSHIFT:
                return ">>";
            case LSHIFT:
                return "<<";
            case XOR:
                return "^";
            case BOOL_AND:
                return "and";
            case BOOL_OR:
                return "or";
            case BIT_AND:
                return "&";
            case BIT_OR:
                return "|";
            case EQ:
                return "==";
            case NEQ:
                return "!=";
            case GT:
                return ">";
            case GE:
                return ">=";
            case LT:
                return "<";
            case LE:
                return "<=";
            case IN:
                return "in";
            case IS:
                return "is";
            case NOT_IN:
                return "not in";
            case IS_NOT:
                return "is not";
        }

        return "";
    }

    std::string OpExpr::to_cpp() const
    {
        switch (op_)
        {
            case PLUS:
                return "__repy::__add__";
            case MINUS:
                return "__repy::__sub__";
            case MULT:
                return "__repy::__mul__";
            case DIV:
                return "__repy::__divmod__";
            case FDIV:
                return "__repy::__floordiv__";
            case MOD:
                return "__repy::__mod__";
            case POW:
                return "__repy::__pow__";
            case RSHIFT:
                return "__repy::__lshift__";
            case LSHIFT:
                return "__repy::__rshift__";
            case XOR:
                return "__repy::__xor__";
            case BIT_AND:
                return "__repy::__and__";
            case BIT_OR:
                return "__repy::__or__";
            case EQ:
                return "__repy::__eq__";
            case NEQ:
                return "__repy::__ne__";
            case GT:
                return "__repy::__gt__";
            case GE:
                return "__repy::__ge__";
            case LT:
                return "__repy::__lt__";
            case LE:
                return "__repy::__le__";
            default:
                assert(false && "Internal compiler error");
                break;
        }

        return "";
    }

    void OpExpr::set_left_expr(Expr* expr)
    {
        if (lexpr_ == nullptr)
        {
            lexpr_ = expr;
            return;
        }

        OpExpr* e = dynamic_cast<OpExpr*> (lexpr_);

        if (e)
            e->set_left_expr(expr);
    }

    void OpExpr::accept(Visitor& v)
    {
        v(*this);
    }

    void OpExpr::accept(ConstVisitor& v) const
    {
        v(*this);
    }
} // namespace ast
<commit_msg>[AST] Update operator generation<commit_after>#include <ast/op-expr.hh>

namespace ast
{
    OpExpr::OpExpr(const yy::location& location,
                   Expr* lexpr,
                   OpExpr::Operator op,
                   Expr* rexpr)
        : Expr(location)
        , lexpr_(lexpr)
        , rexpr_(rexpr)
        , op_(op)
    {}

    OpExpr::~OpExpr()
    {
        delete lexpr_;
        delete rexpr_;
    }

    const Expr* OpExpr::left_expr_get() const
    {
        return lexpr_;
    }

    Expr* OpExpr::left_expr_get()
    {
        return lexpr_;
    }

    const Expr* OpExpr::right_expr_get() const
    {
        return rexpr_;
    }

    Expr* OpExpr::right_expr_get()
    {
        return rexpr_;
    }

    OpExpr::Operator OpExpr::op_get() const
    {
        return op_;
    }

    std::string OpExpr::op_to_string() const
    {
        switch (op_)
        {
            case PLUS:
                return "+";
            case MINUS:
                return "-";
            case MULT:
                return "*";
            case DIV:
                return "/";
            case FDIV:
                return "//";
            case MOD:
                return "%";
            case POW:
                return "**";
            case RSHIFT:
                return ">>";
            case LSHIFT:
                return "<<";
            case XOR:
                return "^";
            case BOOL_AND:
                return "and";
            case BOOL_OR:
                return "or";
            case BIT_AND:
                return "&";
            case BIT_OR:
                return "|";
            case EQ:
                return "==";
            case NEQ:
                return "!=";
            case GT:
                return ">";
            case GE:
                return ">=";
            case LT:
                return "<";
            case LE:
                return "<=";
            case IN:
                return "in";
            case IS:
                return "is";
            case NOT_IN:
                return "not in";
            case IS_NOT:
                return "is not";
        }

        return "";
    }

    std::string OpExpr::to_cpp() const
    {
        switch (op_)
        {
            case PLUS:
                return "repy::__add__";
            case MINUS:
                return "repy::__sub__";
            case MULT:
                return "repy::__mul__";
            case DIV:
                return "repy::__divmod__";
            case FDIV:
                return "repy::__floordiv__";
            case MOD:
                return "repy::__mod__";
            case POW:
                return "repy::__pow__";
            case RSHIFT:
                return "repy::__lshift__";
            case LSHIFT:
                return "repy::__rshift__";
            case XOR:
                return "repy::__xor__";
            case BIT_AND:
                return "repy::__and__";
            case BIT_OR:
                return "repy::__or__";
            case EQ:
                return "repy::__eq__";
            case NEQ:
                return "repy::__ne__";
            case GT:
                return "repy::__gt__";
            case GE:
                return "repy::__ge__";
            case LT:
                return "repy::__lt__";
            case LE:
                return "repy::__le__";
            default:
                assert(false && "Internal compiler error");
                break;
        }

        return "";
    }

    void OpExpr::set_left_expr(Expr* expr)
    {
        if (lexpr_ == nullptr)
        {
            lexpr_ = expr;
            return;
        }

        OpExpr* e = dynamic_cast<OpExpr*> (lexpr_);

        if (e)
            e->set_left_expr(expr);
    }

    void OpExpr::accept(Visitor& v)
    {
        v(*this);
    }

    void OpExpr::accept(ConstVisitor& v) const
    {
        v(*this);
    }
} // namespace ast
<|endoftext|>


<commit_before>/*
	Flexisip, a flexible SIP proxy server with media capabilities.
	Copyright (C) 2010-2015  Belledonne Communications SARL, All rights reserved.

	This program is free software: you can redistribute it and/or modify
	it under the terms of the GNU Affero General Public License as
	published by the Free Software Foundation, either version 3 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 Affero General Public License for more details.

	You should have received a copy of the GNU Affero General Public License
	along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#define SU_MSG_ARG_T struct auth_splugin_t

#include "authdb.hh"
#include <iostream>
#include <fstream>
#include <sstream>

using namespace std;

void FileAuthDb::parsePasswd(string *pass, string user, string domain, passwd_algo_t *password) {
	// parse password and calcul passmd5, passsha256 if there is clrtxt pass.
	int i;
	for (i = 0; i < 3; i++) {
		if (pass[i].substr(0, 7) == "clrtxt:") {
			password->pass = pass[i].substr(7);
		}
	}

	if (password->pass != "") {
		string input;
		input = user + ":" + domain + ":" + password->pass;
		password->passmd5 = syncMd5(input.c_str(), 16);
		password->passsha256 = syncSha256(input.c_str(), 32);
		return;
	}

	for (i = 0; i < 3; i++) {
		if (pass[i].substr(0, 4) == "md5:") {
			password->passmd5 = pass[i].substr(4);
		}
		if (pass[i].substr(0, 7) == "sha256:") {
			password->passsha256 = pass[i].substr(7);
		}
	}
}

FileAuthDb::FileAuthDb() {
	GenericStruct *cr = GenericManager::get()->getRoot();
	GenericStruct *ma = cr->get<GenericStruct>("module::Authentication");

	mLastSync = 0;
	mFileString = ma->get<ConfigString>("datasource")->read();
	sync();
}

void FileAuthDb::getUserWithPhoneFromBackend(const std::string &phone, const std::string &domain, AuthDbListener *listener) {
	AuthDbResult res = AuthDbResult::PASSWORD_NOT_FOUND;
	if (mLastSync == 0) {
		sync();
	}
	std::string user;
	if (getCachedUserWithPhone(phone, domain, user) == VALID_PASS_FOUND) {
		res = AuthDbResult::PASSWORD_FOUND;
	}
	if (listener) listener->onResult(res, user);
}

void FileAuthDb::getPasswordFromBackend(const std::string &id, const std::string &domain,
                                        const std::string &authid, AuthDbListener *listener) {
	AuthDbResult res = AuthDbResult::PASSWORD_NOT_FOUND;
	time_t now = getCurrentTime();

	if (difftime(now, mLastSync) >= mCacheExpire) {
		sync();
	}

	string key(createPasswordKey(id, authid));

	passwd_algo_t passwd;
	if (getCachedPassword(key, domain, passwd) == VALID_PASS_FOUND) {
		res = AuthDbResult::PASSWORD_FOUND;
	}
	if (listener) listener->onResult(res, passwd);
}

/*
 * The following ABNF grammar should describe the syntax of the password file:
token =  1*(alphanum / "-" / "." / "!" / "%" / "*" / "_" / "+" / "`" / "'" / "~" )
user-id = token
phone = token
user = token
domain = token
algo = "clrtxt" / "md5" / "sha256"
identity = user "@" domain
auth-line = identity 1*WSP 1*(algo ":" token) 1*WSP ";" 1*WSP [user-id] 1*WSP [phone]
ctext    =  %x21-27 / %x2A-5B / %x5D-7E / UTF8-NONASCII
                  / LWS
comment = "#" *ctext LF
void = *WSP LF
password-file = "version:0" LF *(comment | void | auth-line)

*/

void FileAuthDb::sync() {
	LOGD("Syncing password file");
	GenericStruct *cr = GenericManager::get()->getRoot();
	GenericStruct *ma = cr->get<GenericStruct>("module::Authentication");
	list<string> domains = ma->get<ConfigStringList>("auth-domains")->read();
	bool firstTime = false;

	if (mLastSync == 0) firstTime = true;

	mLastSync = getCurrentTime();

	ifstream file;

	stringstream ss;
	ss.exceptions(ifstream::failbit | ifstream::badbit);

	string line;
	string user;
	string domain;
	passwd_algo_t password;
	string userid;
	string phone;
	string pass[3];
	string version;
	string passwd_tag;
	int i;

	if (mFileString.empty()){
		LOGF("'file' authentication backend was requested but no path specified in datasource.");
		return;
	}

	LOGD("Opening file %s", mFileString.c_str());
	file.open(mFileString);
	if (file.is_open()) {
		while (file.good() && getline(file, line)) {
			if (line.empty()) continue;
			ss.clear();
			ss.str(line);
			version.clear();
			getline(ss, version, ' ');
			if (version.substr(0, 8) == "version:")
				version = version.substr(8);
			else
				LOGF("%s file must start with version:X.", mFileString.c_str());
			break;
		}
		if (version == "1") {
			while (file.good() && getline(file, line)) {
				if (line.empty()) continue;
				ss.clear();
				ss.str(line);
				user.clear();
				domain.clear();
				pass[0].clear();
				pass[1].clear();
				pass[2].clear();
				password.pass.clear();
				password.passmd5.clear();
				password.passsha256.clear();
				userid.clear();
				phone.clear();
				try {
					getline(ss, user, '@');
					getline(ss, domain, ' ');
					for (i = 0; i < 3 && (!ss.eof()); i++) {
						passwd_tag.clear();
						getline(ss, passwd_tag, ' ');
						if (passwd_tag != ";")
							pass[i] = passwd_tag;
						else break;
					}
					if (passwd_tag != ";") {
						if (ss.eof()){
							LOGF("%s: unterminated password section at line '%s'. Missing ';'.", mFileString.c_str(), line.c_str());
						}else {
							passwd_tag.clear();
							getline(ss, passwd_tag, ' ');
							if ((!ss.eof()) && (passwd_tag != ";")){
								LOGF("%s: unterminated password section at line '%s'. Missing ';'.", mFileString.c_str(), line.c_str());
							}
						}
					}

					// if user with space, replace %20 by space
					string user_ref=user;
					user_ref.reserve(user.size());
					url_unescape(&user_ref[0], user.c_str());
					if (!ss.eof()) {
						// TODO read userid with space
						getline(ss, userid, ' ');
						if (!ss.eof()) {
							getline(ss, phone);
						} else {
							phone = "";
						}
					} else {
						userid = user_ref;
						phone = "";
					}

					cacheUserWithPhone(phone, domain, user);
					parsePasswd(pass, user_ref, domain, &password);

					if (find(domains.begin(), domains.end(), domain) != domains.end()) {
						string key(createPasswordKey(user, userid));
						cachePassword(key, domain, password, mCacheExpire);
					} else if (find(domains.begin(), domains.end(), "*") != domains.end()) {
						string key(createPasswordKey(user, userid));
						cachePassword(key, domain, password, mCacheExpire);
					} else {
						LOGW("Domain '%s' is not handled by Authentication module", domain.c_str());
					}
				} catch (const stringstream::failure &e) {
					LOGW("Incorrect line format: %s (error: %s)", line.c_str(), e.what());
				}
			}
		} else {
			LOGF("Version %s is not supported for file %s", version.c_str(), mFileString.c_str());
		}
	} else {
		if (firstTime){
			LOGF("Can't open file %s", mFileString.c_str());
		}else{
			LOGE("Can't open file %s", mFileString.c_str());
		}
	}
	LOGD("Syncing done");
}
<commit_msg>fix uninitialized username again<commit_after>/*
	Flexisip, a flexible SIP proxy server with media capabilities.
	Copyright (C) 2010-2015  Belledonne Communications SARL, All rights reserved.

	This program is free software: you can redistribute it and/or modify
	it under the terms of the GNU Affero General Public License as
	published by the Free Software Foundation, either version 3 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 Affero General Public License for more details.

	You should have received a copy of the GNU Affero General Public License
	along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#define SU_MSG_ARG_T struct auth_splugin_t

#include "authdb.hh"
#include <iostream>
#include <fstream>
#include <sstream>

using namespace std;

void FileAuthDb::parsePasswd(string *pass, string user, string domain, passwd_algo_t *password) {
	// parse password and calcul passmd5, passsha256 if there is clrtxt pass.
	int i;
	for (i = 0; i < 3; i++) {
		if (pass[i].substr(0, 7) == "clrtxt:") {
			password->pass = pass[i].substr(7);
		}
	}

	if (password->pass != "") {
		string input;
		input = user + ":" + domain + ":" + password->pass;
		password->passmd5 = syncMd5(input.c_str(), 16);
		password->passsha256 = syncSha256(input.c_str(), 32);
		return;
	}

	for (i = 0; i < 3; i++) {
		if (pass[i].substr(0, 4) == "md5:") {
			password->passmd5 = pass[i].substr(4);
		}
		if (pass[i].substr(0, 7) == "sha256:") {
			password->passsha256 = pass[i].substr(7);
		}
	}
}

FileAuthDb::FileAuthDb() {
	GenericStruct *cr = GenericManager::get()->getRoot();
	GenericStruct *ma = cr->get<GenericStruct>("module::Authentication");

	mLastSync = 0;
	mFileString = ma->get<ConfigString>("datasource")->read();
	sync();
}

void FileAuthDb::getUserWithPhoneFromBackend(const std::string &phone, const std::string &domain, AuthDbListener *listener) {
	AuthDbResult res = AuthDbResult::PASSWORD_NOT_FOUND;
	if (mLastSync == 0) {
		sync();
	}
	std::string user;
	if (getCachedUserWithPhone(phone, domain, user) == VALID_PASS_FOUND) {
		res = AuthDbResult::PASSWORD_FOUND;
	}
	if (listener) listener->onResult(res, user);
}

void FileAuthDb::getPasswordFromBackend(const std::string &id, const std::string &domain,
                                        const std::string &authid, AuthDbListener *listener) {
	AuthDbResult res = AuthDbResult::PASSWORD_NOT_FOUND;
	time_t now = getCurrentTime();

	if (difftime(now, mLastSync) >= mCacheExpire) {
		sync();
	}

	string key(createPasswordKey(id, authid));

	passwd_algo_t passwd;
	if (getCachedPassword(key, domain, passwd) == VALID_PASS_FOUND) {
		res = AuthDbResult::PASSWORD_FOUND;
	}
	if (listener) listener->onResult(res, passwd);
}

/*
 * The following ABNF grammar should describe the syntax of the password file:
token =  1*(alphanum / "-" / "." / "!" / "%" / "*" / "_" / "+" / "`" / "'" / "~" )
user-id = token
phone = token
user = token
domain = token
algo = "clrtxt" / "md5" / "sha256"
identity = user "@" domain
auth-line = identity 1*WSP 1*(algo ":" token) 1*WSP ";" 1*WSP [user-id] 1*WSP [phone]
ctext    =  %x21-27 / %x2A-5B / %x5D-7E / UTF8-NONASCII
                  / LWS
comment = "#" *ctext LF
void = *WSP LF
password-file = "version:0" LF *(comment | void | auth-line)

*/

void FileAuthDb::sync() {
	LOGD("Syncing password file");
	GenericStruct *cr = GenericManager::get()->getRoot();
	GenericStruct *ma = cr->get<GenericStruct>("module::Authentication");
	list<string> domains = ma->get<ConfigStringList>("auth-domains")->read();
	bool firstTime = false;

	if (mLastSync == 0) firstTime = true;

	mLastSync = getCurrentTime();

	ifstream file;

	stringstream ss;
	ss.exceptions(ifstream::failbit | ifstream::badbit);

	string line;
	string user;
	string domain;
	passwd_algo_t password;
	string userid;
	string phone;
	string pass[3];
	string version;
	string passwd_tag;
	int i;

	if (mFileString.empty()){
		LOGF("'file' authentication backend was requested but no path specified in datasource.");
		return;
	}

	LOGD("Opening file %s", mFileString.c_str());
	file.open(mFileString);
	if (file.is_open()) {
		while (file.good() && getline(file, line)) {
			if (line.empty()) continue;
			ss.clear();
			ss.str(line);
			version.clear();
			getline(ss, version, ' ');
			if (version.substr(0, 8) == "version:")
				version = version.substr(8);
			else
				LOGF("%s file must start with version:X.", mFileString.c_str());
			break;
		}
		if (version == "1") {
			while (file.good() && getline(file, line)) {
				if (line.empty()) continue;
				ss.clear();
				ss.str(line);
				user.clear();
				domain.clear();
				pass[0].clear();
				pass[1].clear();
				pass[2].clear();
				password.pass.clear();
				password.passmd5.clear();
				password.passsha256.clear();
				userid.clear();
				phone.clear();
				try {
					getline(ss, user, '@');
					getline(ss, domain, ' ');
					for (i = 0; i < 3 && (!ss.eof()); i++) {
						passwd_tag.clear();
						getline(ss, passwd_tag, ' ');
						if (passwd_tag != ";")
							pass[i] = passwd_tag;
						else break;
					}
					if (passwd_tag != ";") {
						if (ss.eof()){
							LOGF("%s: unterminated password section at line '%s'. Missing ';'.", mFileString.c_str(), line.c_str());
						}else {
							passwd_tag.clear();
							getline(ss, passwd_tag, ' ');
							if ((!ss.eof()) && (passwd_tag != ";")){
								LOGF("%s: unterminated password section at line '%s'. Missing ';'.", mFileString.c_str(), line.c_str());
							}
						}
					}

					// if user with space, replace %20 by space
					string user_ref;
					user_ref.resize(user.size());
					url_unescape(&user_ref[0], user.c_str());
                    user_ref.resize(strlen(&user_ref[0]));
					if (!ss.eof()) {
						// TODO read userid with space
						getline(ss, userid, ' ');
						if (!ss.eof()) {
							getline(ss, phone);
						} else {
							phone = "";
						}
					} else {
						userid = user_ref;
						phone = "";
					}

					cacheUserWithPhone(phone, domain, user);
					parsePasswd(pass, user_ref, domain, &password);

					if (find(domains.begin(), domains.end(), domain) != domains.end()) {
						string key(createPasswordKey(user, userid));
						cachePassword(key, domain, password, mCacheExpire);
					} else if (find(domains.begin(), domains.end(), "*") != domains.end()) {
						string key(createPasswordKey(user, userid));
						cachePassword(key, domain, password, mCacheExpire);
					} else {
						LOGW("Domain '%s' is not handled by Authentication module", domain.c_str());
					}
				} catch (const stringstream::failure &e) {
					LOGW("Incorrect line format: %s (error: %s)", line.c_str(), e.what());
				}
			}
		} else {
			LOGF("Version %s is not supported for file %s", version.c_str(), mFileString.c_str());
		}
	} else {
		if (firstTime){
			LOGF("Can't open file %s", mFileString.c_str());
		}else{
			LOGE("Can't open file %s", mFileString.c_str());
		}
	}
	LOGD("Syncing done");
}
<|endoftext|>


<commit_before>/****************************************************************/
/*                                                              */
/*  Implementation of Cardiac Tissue elasticity as given in     */
/*  [Whiteley2007]                                              */
/*                                                              */
/****************************************************************/

#include "CardiacWhiteley2007Material.h"
#include "ColumnMajorMatrix.h"
#include "CardiacSolidMechanicsMaterial.h"
#include "SymmOrthotropicElasticityTensor.h"
#include "VolumetricModel.h"

template<>
InputParameters validParams<CardiacWhiteley2007Material>()
{
  InputParameters params = validParams<CardiacSolidMechanicsMaterial>();
  params.addRequiredParam<std::vector<Real> >("k_MN", "Material parameters k_MN in following order: k_11, k_22, k_33, k_12, k_23, k_13");
  params.addRequiredParam<std::vector<Real> >("a_MN", "Material parameters a_MN in following order: a_11, a_22, a_33, a_12, a_23, a_13");
  params.addRequiredParam<std::vector<Real> >("b_MN", "Material parameters b_MN in following order: b_11, b_22, b_33, b_12, b_23, b_13");

  params.addCoupledVar("Ta", 0, "The (position dependent) active tension in fibre direction that will finally drive contraction, see (8) in [Whiteley 2007]. Default is Ta=0, i.e. no active tension anywhere.");
  return params;
}

CardiacWhiteley2007Material::CardiacWhiteley2007Material(const std::string  & name,
                                                 InputParameters parameters)
  :CardiacSolidMechanicsMaterial(name, parameters),
    _k(SymmTensor(getParam<std::vector<Real> >("k_MN"))),
    _a(SymmTensor(getParam<std::vector<Real> >("a_MN"))),
    _b(SymmTensor(getParam<std::vector<Real> >("b_MN"))),
   _Rf(getMaterialProperty<RealTensorValue>("R_fibre")),
   _has_Ta(isCoupled("Ta")),
   _Ta(coupledValue("Ta")),
   _id(1, 1, 1, 0, 0, 0)
{}

const RealTensorValue CardiacWhiteley2007Material::fromSymm(const SymmTensor & A)
{
  RealTensorValue B;
  B(1,1) = A(1,1);
  B(2,2) = A(2,2);
  B(3,3) = A(3,3);
  B(1,2) = B(2,1) = A(1,2);
  B(1,3) = B(3,1) = A(1,3);
  B(2,3) = B(3,2) = A(2,3);
  return B;
}

/*
 * computes outer.transpose() * inner * outer
 * TODO: this should be possible in a much more efficient way
 */
const SymmTensor CardiacWhiteley2007Material::symmProd(const RealTensorValue & outer, const SymmTensor & inner)
{
  RealTensorValue in(fromSymm(inner));
  RealTensorValue r(outer.transpose() * in * outer);
  return SymmTensor(r(0,0), r(1,1), r(2,2), r(0,1), r(1,2), r(0,2) );
}

void
CardiacWhiteley2007Material::computeQpProperties()
{
  // TODO: verify that all rotations are done in the correct direction, i.e. where do you have to use _Rf or _Rf.transpose() ?

  // local deformation gradient tensor: insert displacement gradient row-wise
  const RealTensorValue F(_grad_disp_x[_qp],
                          _grad_disp_y[_qp],
                          _grad_disp_z[_qp]);
  // Cauchy-Green deformation tensor
  const SymmTensor C(symmProd(F, _id));
  // Lagrange-Green strain tensor
  const SymmTensor E( (C - _id) * 0.5 );
  // Lagrange-Green strain tensor in fibre coordinates
  const SymmTensor Estar(symmProd(_Rf[_qp], E));

  // Derivative of strain energy density W wrt Estar
  SymmTensor dWdE;
  for (int i=0;i<3;i++)
    for (int j=i;j<3;j++)
      if (Estar(i,j) > 0) {
        const Real d(abs(_a(i,j) - Estar(i,j)));
        dWdE(i,j) = _k(i, j) * Estar(i,j) / pow(d, _b(i,j))  *  ( 2 + _b(i,j)*Estar(i,j)/d );
      } else
        dWdE(i,j) = 0.;
  // rotate back into outer coordinate system
  dWdE = symmProd(_Rf[_qp].transpose(), dWdE);

  const Real p = 0; // TODO: p is the hydrostatic pressure / Lagrange multiplier to guarantee incompressibility
  _stress[_qp] = _id*(-p) + symmProd(F.transpose(), dWdE);

  // compute active tension in fibre direction, rotate into outer coordinates and add to stress if necessary
  if (_has_Ta) {
    SymmTensor Ta( symmProd( _Rf[_qp], SymmTensor(_Ta[_qp], 0, 0, 0, 0, 0) ) );
    _stress[_qp] += Ta;
  }

  /* TODO: currently, though being possibly required (e.g. by the StressDivergence kernel), we do not set the following
     // store elasticity tensor as material property...
     _elasticity_tensor[_qp] =
     //Jacobian multiplier of the stress
     _Jacobian_mult[_qp] =
  // Save off the elastic strain
     _elastic_strain[_qp] =   SymmTensor( _grad_disp_x[_qp](0),
                                          _grad_disp_y[_qp](1),
                                          _grad_disp_z[_qp](2),
                                          0.5*(_grad_disp_x[_qp](1)+_grad_disp_y[_qp](0)),
                                          0.5*(_grad_disp_y[_qp](2)+_grad_disp_z[_qp](1)),
                                          0.5*(_grad_disp_z[_qp](0)+_grad_disp_x[_qp](2)) );;
  */
}

<commit_msg>fixed indexing error: Fortran starts with one, but who cares for Fortran - we are in C++here...<commit_after>/****************************************************************/
/*                                                              */
/*  Implementation of Cardiac Tissue elasticity as given in     */
/*  [Whiteley2007]                                              */
/*                                                              */
/****************************************************************/

#include "CardiacWhiteley2007Material.h"
#include "ColumnMajorMatrix.h"
#include "CardiacSolidMechanicsMaterial.h"
#include "SymmOrthotropicElasticityTensor.h"
#include "VolumetricModel.h"

template<>
InputParameters validParams<CardiacWhiteley2007Material>()
{
  InputParameters params = validParams<CardiacSolidMechanicsMaterial>();
  params.addRequiredParam<std::vector<Real> >("k_MN", "Material parameters k_MN in following order: k_11, k_22, k_33, k_12, k_23, k_13");
  params.addRequiredParam<std::vector<Real> >("a_MN", "Material parameters a_MN in following order: a_11, a_22, a_33, a_12, a_23, a_13");
  params.addRequiredParam<std::vector<Real> >("b_MN", "Material parameters b_MN in following order: b_11, b_22, b_33, b_12, b_23, b_13");

  params.addCoupledVar("Ta", 0, "The (position dependent) active tension in fibre direction that will finally drive contraction, see (8) in [Whiteley 2007]. Default is Ta=0, i.e. no active tension anywhere.");
  return params;
}

CardiacWhiteley2007Material::CardiacWhiteley2007Material(const std::string  & name,
                                                 InputParameters parameters)
  :CardiacSolidMechanicsMaterial(name, parameters),
    _k(SymmTensor(getParam<std::vector<Real> >("k_MN"))),
    _a(SymmTensor(getParam<std::vector<Real> >("a_MN"))),
    _b(SymmTensor(getParam<std::vector<Real> >("b_MN"))),
   _Rf(getMaterialProperty<RealTensorValue>("R_fibre")),
   _has_Ta(isCoupled("Ta")),
   _Ta(coupledValue("Ta")),
   _id(1, 1, 1, 0, 0, 0)
{}

const RealTensorValue CardiacWhiteley2007Material::fromSymm(const SymmTensor & A)
{
  RealTensorValue B;
  B(0,0) = A(0,0);
  B(1,1) = A(1,1);
  B(2,2) = A(2,2);
  B(0,1) = B(1,0) = A(0,1);
  B(0,2) = B(2,0) = A(0,2);
  B(1,2) = B(2,1) = A(1,2);
  return B;
}

/*
 * computes outer.transpose() * inner * outer
 * TODO: this should be possible in a much more efficient way
 */
const SymmTensor CardiacWhiteley2007Material::symmProd(const RealTensorValue & outer, const SymmTensor & inner)
{
  RealTensorValue in(fromSymm(inner));
  RealTensorValue r(outer.transpose() * in * outer);
  return SymmTensor(r(0,0), r(1,1), r(2,2), r(0,1), r(1,2), r(0,2) );
}

void
CardiacWhiteley2007Material::computeQpProperties()
{
  // TODO: verify that all rotations are done in the correct direction, i.e. where do you have to use _Rf or _Rf.transpose() ?

  // local deformation gradient tensor: insert displacement gradient row-wise
  const RealTensorValue F(_grad_disp_x[_qp],
                          _grad_disp_y[_qp],
                          _grad_disp_z[_qp]);
  // Cauchy-Green deformation tensor
  const SymmTensor C(symmProd(F, _id));
  // Lagrange-Green strain tensor
  const SymmTensor E( (C - _id) * 0.5 );
  // Lagrange-Green strain tensor in fibre coordinates
  const SymmTensor Estar(symmProd(_Rf[_qp], E));

  // Derivative of strain energy density W wrt Estar
  SymmTensor dWdE;
  for (int i=0;i<3;i++)
    for (int j=i;j<3;j++)
      if (Estar(i,j) > 0) {
        const Real d(abs(_a(i,j) - Estar(i,j)));
        dWdE(i,j) = _k(i, j) * Estar(i,j) / pow(d, _b(i,j))  *  ( 2 + _b(i,j)*Estar(i,j)/d );
      } else
        dWdE(i,j) = 0.;
  // rotate back into outer coordinate system
  dWdE = symmProd(_Rf[_qp].transpose(), dWdE);

  const Real p = 0; // TODO: p is the hydrostatic pressure / Lagrange multiplier to guarantee incompressibility
  _stress[_qp] = _id*(-p) + symmProd(F.transpose(), dWdE);

  // compute active tension in fibre direction, rotate into outer coordinates and add to stress if necessary
  if (_has_Ta) {
    SymmTensor Ta( symmProd( _Rf[_qp], SymmTensor(_Ta[_qp], 0, 0, 0, 0, 0) ) );
    _stress[_qp] += Ta;
  }

  /* TODO: currently, though being possibly required (e.g. by the StressDivergence kernel), we do not set the following
     // store elasticity tensor as material property...
     _elasticity_tensor[_qp] =
     //Jacobian multiplier of the stress
     _Jacobian_mult[_qp] =
  // Save off the elastic strain
     _elastic_strain[_qp] =   SymmTensor( _grad_disp_x[_qp](0),
                                          _grad_disp_y[_qp](1),
                                          _grad_disp_z[_qp](2),
                                          0.5*(_grad_disp_x[_qp](1)+_grad_disp_y[_qp](0)),
                                          0.5*(_grad_disp_y[_qp](2)+_grad_disp_z[_qp](1)),
                                          0.5*(_grad_disp_z[_qp](0)+_grad_disp_x[_qp](2)) );;
  */
}

<|endoftext|>


<commit_before>#include "dlib/bam_util.h"
#include "dlib/bed_util.h"
#include <getopt.h>
#include <functional>

int usage(char **argv, int retcode=EXIT_FAILURE) {
    fprintf(stderr, "bmftools %s <-l output_compression_level> in.bam out.bam\n"
                    "Use - for stdin or stdout.\n"
                    "Flags-\n"
                    "-F\t\tSkip all reads with any bits in parameter set.\n"
                    "-f\t\tSkip reads sharing no bits in parameter set.\n"
                    "-b\t\tPath to bed file with which to filter.\n"
                    "-P\t\tNumber of bases around bed file regions to pad.\n"
                    "-s\t\tMinimum family size for inclusion.\n"
                    "-r\t\tIf set, writes failed reads to this file.\n"
                    "-v\t\tInvert pass/fail, analogous to grep.\n"
            , argv[0]);
    return retcode;
}

struct opts {
    uint32_t minFM:14;
    uint32_t v:1;
    uint32_t skip_flag:16;
    uint32_t require_flag:16;
    uint32_t minMQ:8;
    khash_t(bed) *bed;
};

#define TEST(b, data, options) \
        (\
             (((data = bam_aux_get(b, "FM")) != NULL) ? bam_aux2i(data) : 1 >= (int)((opts *)options)->minFM) &&\
             b->core.qual >= ((opts *)options)->minMQ &&\
             ((b->core.flag & ((opts *)options)->skip_flag) == 0) &&\
             ((b->core.flag & ((opts *)options)->require_flag)) &&\
             bed_test(b, ((opts *)options)->bed)\
        )

int bam_test(bam1_t *b, void *options) {
    uint8_t *data;
    return ((opts *)options)->v ? !TEST(b, data, options): TEST(b, data, options);
}

#undef TEST

int filter_main(int argc, char *argv[]) {
    if(argc < 3)
        return usage(argv);
    if(strcmp(argv[1], "--help") == 0)
        return usage(argv, EXIT_SUCCESS);
    int c;
    char out_mode[4] = "wb";
    opts param = {0};
    char *bedpath = NULL;
    int padding = DEFAULT_PADDING;
    std::string refused_path("");
    while((c = getopt(argc, argv, "r:P:b:m:F:f:l:hv?")) > -1) {
        switch(c) {
        case 'P': padding = atoi(optarg); break;
        case 'b': bedpath = optarg; break;
        case 'm': param.minMQ = strtoul(optarg, NULL, 0); break;
        case 's': param.minFM = strtoul(optarg, NULL, 0); break;
        case 'F': param.skip_flag = strtoul(optarg, NULL, 0); break;
        case 'f': param.require_flag = strtoul(optarg, NULL, 0); break;
        case 'v': param.v = 1; break;
        case 'r': refused_path = optarg; break;
        case 'l': out_mode[2] = atoi(optarg) % 10 + '0'; break;
        case 'h': case '?': return usage(argv, EXIT_SUCCESS);
        }
    }
    check_bam_tag_exit(argv[optind], "FM");
    if(argc - 2 != optind) {
        LOG_EXIT("Required: precisely two positional arguments (in bam, out bam).\n");
    }
    dlib::BamHandle in(argv[optind]);
    if(bedpath) {
        param.bed = parse_bed_hash(bedpath, in.header, padding);
    }
    dlib::BamHandle out(argv[optind] + 1, in.header, out_mode);
    // Core
    if(!refused_path.size()) {
        in.for_each(bam_test, out, (void *)&param);
    } else {
        dlib::BamHandle refused(refused_path.c_str(), in.header, out_mode);
        while(in.next() >= 0) {
            if(bam_test(in.rec, (void *)&param))
                out.write(in.rec);
            else
                refused.write(in.rec);
        }
    }
    // Clean up.
    if(param.bed) bed_destroy_hash((void *)param.bed);
    return EXIT_SUCCESS;
}

<commit_msg>filter_split_core might contain the most offensive line of code I've ever written.<commit_after>#include "dlib/bam_util.h"
#include "dlib/bed_util.h"
#include <getopt.h>
#include <functional>

int usage(char **argv, int retcode=EXIT_FAILURE) {
    fprintf(stderr, "bmftools %s <-l output_compression_level> in.bam out.bam\n"
                    "Use - for stdin or stdout.\n"
                    "Flags-\n"
                    "-F\t\tSkip all reads with any bits in parameter set.\n"
                    "-f\t\tSkip reads sharing no bits in parameter set.\n"
                    "-b\t\tPath to bed file with which to filter.\n"
                    "-P\t\tNumber of bases around bed file regions to pad.\n"
                    "-s\t\tMinimum family size for inclusion.\n"
                    "-r\t\tIf set, writes failed reads to this file.\n"
                    "-v\t\tInvert pass/fail, analogous to grep.\n"
            , argv[0]);
    return retcode;
}

struct opts {
    uint32_t minFM:14;
    uint32_t v:1;
    uint32_t skip_flag:16;
    uint32_t require_flag:16;
    uint32_t minMQ:8;
    float minAF;
    khash_t(bed) *bed;
};

#define TEST(b, data, options) \
        (\
             (((data = bam_aux_get(b, "FM")) != NULL) ? bam_aux2i(data) : 1 >= (int)((opts *)options)->minFM) &&\
             b->core.qual >= ((opts *)options)->minMQ &&\
             ((b->core.flag & ((opts *)options)->skip_flag) == 0) &&\
             ((b->core.flag & ((opts *)options)->require_flag)) &&\
             bed_test(b, ((opts *)options)->bed)\
        )

int bam_test(bam1_t *b, void *options) {
    uint8_t *data;
    return ((opts *)options)->v ? !TEST(b, data, options): TEST(b, data, options);
}

#undef TEST

int filter_split_core(dlib::BamHandle& in, dlib::BamHandle& out, dlib::BamHandle& refused, opts *param)
{
    while(in.next() >= 0) (bam_test(in.rec, (void *)param) ? out: refused).write(in.rec);
    return EXIT_SUCCESS;
}

int filter_main(int argc, char *argv[]) {
    if(argc < 3)
        return usage(argv);
    if(strcmp(argv[1], "--help") == 0)
        return usage(argv, EXIT_SUCCESS);
    int c;
    char out_mode[4] = "wb";
    opts param = {0};
    char *bedpath = NULL;
    int padding = DEFAULT_PADDING;
    std::string refused_path("");
    while((c = getopt(argc, argv, "a:r:P:b:m:F:f:l:hv?")) > -1) {
        switch(c) {
        case 'a': param.minAF = atof(optarg); break;
        case 'P': padding = atoi(optarg); break;
        case 'b': bedpath = optarg; break;
        case 'm': param.minMQ = strtoul(optarg, NULL, 0); break;
        case 's': param.minFM = strtoul(optarg, NULL, 0); break;
        case 'F': param.skip_flag = strtoul(optarg, NULL, 0); break;
        case 'f': param.require_flag = strtoul(optarg, NULL, 0); break;
        case 'v': param.v = 1; break;
        case 'r': refused_path = optarg; break;
        case 'l': out_mode[2] = atoi(optarg) % 10 + '0'; break;
        case 'h': case '?': return usage(argv, EXIT_SUCCESS);
        }
    }
    check_bam_tag_exit(argv[optind], "FM");
    if(argc - 2 != optind) {
        LOG_EXIT("Required: precisely two positional arguments (in bam, out bam).\n");
    }
    dlib::BamHandle in(argv[optind]);
    if(bedpath) {
        param.bed = parse_bed_hash(bedpath, in.header, padding);
    }
    dlib::BamHandle out(argv[optind] + 1, in.header, out_mode);
    // Core
    if(refused_path.size()) { // refused path is set.
        dlib::BamHandle refused(refused_path.c_str(), in.header, out_mode);
        filter_split_core(in, out, refused, &param);
    } else in.for_each(bam_test, out, (void *)&param);
    // Clean up.
    if(param.bed) bed_destroy_hash((void *)param.bed);
    return EXIT_SUCCESS;
}

<|endoftext|>


<commit_before>//////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2007-2016 musikcube team
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
//    * Redistributions of source code must retain the above copyright notice,
//      this list of conditions and the following disclaimer.
//
//    * Redistributions in binary form must reproduce the above copyright
//      notice, this list of conditions and the following disclaimer in the
//      documentation and/or other materials provided with the distribution.
//
//    * Neither the name of the author nor the names of other contributors may
//      be used to endorse or promote products derived from this software
//      without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////////

#include "stdafx.h"

#include <core/support/Common.h>

#include <cursespp/ScrollAdapterBase.h>
#include <cursespp/SingleLineEntry.h>

#include "DirectoryAdapter.h"

using namespace musik::box;
using namespace cursespp;
using namespace boost::filesystem;

#ifdef WIN32
void buildDriveList(std::vector<std::string>& target) {
    target.clear();
    static char buffer[4096];
    DWORD result = ::GetLogicalDriveStringsA(4096, buffer);
    if (result) {
        char* current = buffer;
        while (*current) {
            target.push_back(std::string(current));
            current += strlen(current) + 1;
        }
    }
}
#endif

void buildDirectoryList(const path& p, std::vector<std::string>& target)
{
    target.clear();

    try {
        directory_iterator end;
        directory_iterator file(p);

        while (file != end) {
            if (is_directory(file->status())) {
                std::string leaf = file->path().leaf().string();
                if (leaf[0] != '.') {
                    target.push_back(leaf);
                }
            }
            ++file;
        }
    }
    catch (...) {
        /* todo: log maybe? */
    }
}

DirectoryAdapter::DirectoryAdapter() {
    this->dir = musik::core::GetHomeDirectory();
    buildDirectoryList(this->dir, this->subdirs);
}

DirectoryAdapter::~DirectoryAdapter() {

}

void DirectoryAdapter::Select(size_t index) {
    bool hasParent = dir.has_parent_path();
    if (hasParent && index == 0) {
        this->dir = this->dir.parent_path();
    }
    else {
        dir /= this->subdirs[hasParent ? index - 1 : index];
    }

#ifdef WIN32
    std::string pathstr = this->dir.string();
    if ((pathstr.size() == 2 && pathstr[1] == ':') ||
        (pathstr.size() == 3 && pathstr[2] == ':'))
    {
        dir = path();
        buildDriveList(subdirs);
        return;
    }

#endif
    buildDirectoryList(dir, subdirs);
}

std::string DirectoryAdapter::GetFullPathAt(size_t index) {
    bool hasParent = dir.has_parent_path();

    if (hasParent && index == 0) {
        return "";
    }

    index = (hasParent ? index - 1 : index);
    return (dir / this->subdirs[index]).string();
}

size_t DirectoryAdapter::GetEntryCount() {
    size_t count = subdirs.size();
    return dir.has_parent_path() ? count + 1 : count;
}

IScrollAdapter::EntryPtr DirectoryAdapter::GetEntry(size_t index) {
    if (dir.has_parent_path()) {
        if (index == 0) {
            return IScrollAdapter::EntryPtr(new SingleLineEntry(".."));
        }
        --index;
    }

    return IScrollAdapter::EntryPtr(new SingleLineEntry(this->subdirs[index]));
}
<commit_msg>Added sorting to the directory browser<commit_after>//////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2007-2016 musikcube team
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
//    * Redistributions of source code must retain the above copyright notice,
//      this list of conditions and the following disclaimer.
//
//    * Redistributions in binary form must reproduce the above copyright
//      notice, this list of conditions and the following disclaimer in the
//      documentation and/or other materials provided with the distribution.
//
//    * Neither the name of the author nor the names of other contributors may
//      be used to endorse or promote products derived from this software
//      without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////////

#include "stdafx.h"

#include <core/support/Common.h>

#include <cursespp/ScrollAdapterBase.h>
#include <cursespp/SingleLineEntry.h>

#include "DirectoryAdapter.h"

using namespace musik::box;
using namespace cursespp;
using namespace boost::filesystem;

#ifdef WIN32
void buildDriveList(std::vector<std::string>& target) {
    target.clear();
    static char buffer[4096];
    DWORD result = ::GetLogicalDriveStringsA(4096, buffer);
    if (result) {
        char* current = buffer;
        while (*current) {
            target.push_back(std::string(current));
            current += strlen(current) + 1;
        }
    }
}
#endif

void buildDirectoryList(const path& p, std::vector<std::string>& target)
{
    target.clear();

    try {
        directory_iterator end;
        directory_iterator file(p);

        while (file != end) {
            if (is_directory(file->status())) {
                std::string leaf = file->path().leaf().string();
                if (leaf[0] != '.') {
                    target.push_back(leaf);
                }
            }
            ++file;
        }
    }
    catch (...) {
        /* todo: log maybe? */
    }

    std::sort(target.begin(), target.end(), std::locale(""));
}

DirectoryAdapter::DirectoryAdapter() {
    this->dir = musik::core::GetHomeDirectory();
    buildDirectoryList(this->dir, this->subdirs);
}

DirectoryAdapter::~DirectoryAdapter() {

}

void DirectoryAdapter::Select(size_t index) {
    bool hasParent = dir.has_parent_path();
    if (hasParent && index == 0) {
        this->dir = this->dir.parent_path();
    }
    else {
        dir /= this->subdirs[hasParent ? index - 1 : index];
    }

#ifdef WIN32
    std::string pathstr = this->dir.string();
    if ((pathstr.size() == 2 && pathstr[1] == ':') ||
        (pathstr.size() == 3 && pathstr[2] == ':'))
    {
        dir = path();
        buildDriveList(subdirs);
        return;
    }

#endif
    buildDirectoryList(dir, subdirs);
}

std::string DirectoryAdapter::GetFullPathAt(size_t index) {
    bool hasParent = dir.has_parent_path();

    if (hasParent && index == 0) {
        return "";
    }

    index = (hasParent ? index - 1 : index);
    return (dir / this->subdirs[index]).string();
}

size_t DirectoryAdapter::GetEntryCount() {
    size_t count = subdirs.size();
    return dir.has_parent_path() ? count + 1 : count;
}

IScrollAdapter::EntryPtr DirectoryAdapter::GetEntry(size_t index) {
    if (dir.has_parent_path()) {
        if (index == 0) {
            return IScrollAdapter::EntryPtr(new SingleLineEntry(".."));
        }
        --index;
    }

    return IScrollAdapter::EntryPtr(new SingleLineEntry(this->subdirs[index]));
}
<|endoftext|>


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

#include "net/instaweb/apache/instaweb_handler.h"

#include "apr_strings.h"
#include "base/basictypes.h"
#include "base/scoped_ptr.h"
#include "net/instaweb/apache/apache_slurp.h"
#include "net/instaweb/apache/apr_statistics.h"
#include "net/instaweb/apache/apr_timer.h"
#include "net/instaweb/apache/header_util.h"
#include "net/instaweb/apache/instaweb_context.h"
#include "net/instaweb/apache/serf_async_callback.h"
#include "net/instaweb/apache/serf_url_async_fetcher.h"
#include "net/instaweb/apache/mod_instaweb.h"
#include "net/instaweb/rewriter/public/add_instrumentation_filter.h"
#include "net/instaweb/rewriter/public/output_resource.h"
#include "net/instaweb/rewriter/public/rewrite_driver.h"
#include "net/instaweb/util/public/google_message_handler.h"
#include "net/instaweb/util/public/message_handler.h"
#include "net/instaweb/util/public/simple_meta_data.h"
#include "net/instaweb/util/public/string_util.h"
#include "net/instaweb/util/public/string_writer.h"
#include "http_config.h"
#include "http_core.h"
#include "http_log.h"
#include "http_protocol.h"

namespace net_instaweb {

namespace {

const char kStatisticsHandler[] = "mod_pagespeed_statistics";
const char kBeaconHandler[] = "mod_pagespeed_beacon";

bool IsCompressibleContentType(const char* content_type) {
  if (content_type == NULL) {
    return false;
  }
  std::string type = content_type;
  size_t separator_idx = type.find(";");
  if (separator_idx != std::string::npos) {
    type.erase(separator_idx);
  }

  bool res = false;
  if (type.find("text/") == 0) {
    res = true;
  } else if (type.find("application/") == 0) {
    if (type.find("javascript") != type.npos ||
        type.find("json") != type.npos ||
        type.find("ecmascript") != type.npos ||
        type == "application/livescript" ||
        type == "application/js" ||
        type == "application/jscript" ||
        type == "application/x-js" ||
        type == "application/xhtml+xml" ||
        type == "application/xml") {
      res = true;
    }
  }

  return res;
}

// Default handler when the file is not found
void instaweb_default_handler(const std::string& url, request_rec* request) {
  request->status = HTTP_NOT_FOUND;
  ap_set_content_type(request, "text/html; charset=utf-8");
  ap_rputs("<title>Not Found</title>", request);
  ap_rputs("
Apache server with mod_pagespeed
OK", request);
  ap_rputs("
NOT FOUND:", request);
  ap_rputs(url.c_str(), request);
  ap_rputs("", request);
}

// predeclare to minimize diffs for now.  TODO(jmarantz): reorder
void send_out_headers_and_body(
    request_rec* request,
    const SimpleMetaData& response_headers,
    const std::string& output);

// Determines whether the url can be handled as a mod_pagespeed resource,
// and handles it, returning true.  A 'true' routine means that this
// method believed the URL was a mod_pagespeed resource -- it does not
// imply that it was handled successfully.  That information will be
// in the status code in the response headers.
bool handle_as_resource(ApacheRewriteDriverFactory* factory,
                        request_rec* request,
                        const std::string& url) {
  RewriteDriver* rewrite_driver = factory->NewRewriteDriver();

  SimpleMetaData request_headers, response_headers;
  int n = arraysize(RewriteDriver::kPassThroughRequestAttributes);
  for (int i = 0; i < n; ++i) {
    const char* value = apr_table_get(
        request->headers_in,
        RewriteDriver::kPassThroughRequestAttributes[i]);
    if (value != NULL) {
      request_headers.Add(RewriteDriver::kPassThroughRequestAttributes[i],
                          value);
    }
  }
  std::string output;  // TODO(jmarantz): quit buffering resource output
  StringWriter writer(&output);
  MessageHandler* message_handler = factory->message_handler();
  SerfAsyncCallback* callback = new SerfAsyncCallback(
      &response_headers, &writer);
  bool handled = rewrite_driver->FetchResource(
      url, request_headers, callback->response_headers(), callback->writer(),
      message_handler, callback);
  if (handled) {
    message_handler->Message(kInfo, "Fetching resource %s...", url.c_str());
    if (!callback->done()) {
      SerfUrlAsyncFetcher* serf_async_fetcher =
          factory->serf_url_async_fetcher();
      AprTimer timer;
      int64 max_ms = factory->fetcher_time_out_ms();
      for (int64 start_ms = timer.NowMs(), now_ms = start_ms;
           !callback->done() && now_ms - start_ms < max_ms;
           now_ms = timer.NowMs()) {
        int64 remaining_us = max_ms - (now_ms - start_ms);
        serf_async_fetcher->Poll(remaining_us);
      }

      if (!callback->done()) {
        message_handler->Message(kError, "Timeout on url %s", url.c_str());
      }
    }
    if (callback->success()) {
      message_handler->Message(kInfo, "Fetch succeeded for %s, status=%d",
                              url.c_str(), response_headers.status_code());
      send_out_headers_and_body(request, response_headers, output);
    } else {
      message_handler->Message(kError, "Fetch failed for %s, status=%d",
                              url.c_str(), response_headers.status_code());
      factory->Increment404Count();
      instaweb_default_handler(url, request);
    }
  } else {
    callback->Done(false);
  }
  callback->Release();
  factory->ReleaseRewriteDriver(rewrite_driver);
  return handled;
}

void send_out_headers_and_body(
    request_rec* request,
    const SimpleMetaData& response_headers,
    const std::string& output) {
  if (response_headers.status_code() != 0) {
    request->status = response_headers.status_code();
  }
  for (int idx = 0; idx < response_headers.NumAttributes(); ++idx) {
    const char* name = response_headers.Name(idx);
    const char* value = response_headers.Value(idx);
    if (strcasecmp(name, HttpAttributes::kContentType) == 0) {
      // ap_set_content_type does not make a copy of the string, we need
      // to duplicate it.
      char* ptr = apr_pstrdup(request->pool, value);
      ap_set_content_type(request, ptr);
    } else {
      if (strcasecmp(name, HttpAttributes::kCacheControl) == 0) {
        SetupCacheRepair(value, request);
      }
      // apr_table_add makes copies of both head key and value, so we do not
      // have to duplicate them.
      apr_table_add(request->headers_out, name, value);
    }
  }
  if (response_headers.status_code() == HttpStatus::kOK &&
      IsCompressibleContentType(request->content_type)) {
    // Make sure compression is enabled for this response.
    ap_add_output_filter("DEFLATE", NULL, request, request->connection);
  }

  // Recompute the content-length, because the content may have changed.
  ap_set_content_length(request, output.size());
  // Send the body
  ap_rwrite(output.c_str(), output.size(), request);
}

}  // namespace

apr_status_t repair_caching_header(ap_filter_t *filter,
                                   apr_bucket_brigade *bb) {
  request_rec* request = filter->r;
  RepairCachingHeaders(request);
  ap_remove_output_filter(filter);
  return ap_pass_brigade(filter->next, bb);
}

std::string get_request_url(request_rec* request) {
  /*
   * In some contexts we are seeing relative URLs passed
   * into request->unparsed_uri.  But when using mod_slurp, the rewritten
   * HTML contains complete URLs, so this construction yields the host:port
   * prefix twice.
   *
   * TODO(jmarantz): Figure out how to do this correctly at all times.
   */
  std::string url;
  if (strncmp(request->unparsed_uri, "http://", 7) == 0) {
    url = request->unparsed_uri;
  } else {
    url = ap_construct_url(request->pool, request->unparsed_uri, request);
  }
  return url;
}

int instaweb_handler(request_rec* request) {
  ApacheRewriteDriverFactory* factory =
      InstawebContext::Factory(request->server);
  int ret = OK;

  // Only handle GET request
  if (request->method_number != M_GET) {
    ap_log_rerror(APLOG_MARK, APLOG_DEBUG, APR_SUCCESS, request,
                  "Not GET request: %d.", request->method_number);
    ret = DECLINED;
  } else if (strcmp(request->handler, kStatisticsHandler) == 0) {
    std::string output;
    SimpleMetaData response_headers;
    StringWriter writer(&output);
    AprStatistics* statistics = factory->statistics();
    if (statistics) {
      statistics->Dump(&writer, factory->message_handler());
    }
    send_out_headers_and_body(request, response_headers, output);
  } else if (strcmp(request->handler, kBeaconHandler) == 0) {
    RewriteDriver* driver = factory->NewRewriteDriver();
    AddInstrumentationFilter* aif = driver->add_instrumentation_filter();
    if (aif && aif->HandleBeacon(request->unparsed_uri)) {
      ret = HTTP_NO_CONTENT;
    } else {
      ret = DECLINED;
    }
    factory->ReleaseRewriteDriver(driver);
  } else {
    std::string url = get_request_url(request);
    if (!handle_as_resource(factory, request, url)) {
      if (factory->slurping_enabled()) {
        SlurpUrl(url, factory, request);
        if (request->status == HTTP_NOT_FOUND) {
          factory->IncrementSlurpCount();
        }
      } else {
        ret = DECLINED;
      }
    }
  }
  return ret;
}

// This translator must be inserted into the translate_name chain
// prior to mod_rewrite.  By responding "OK" we prevent mod_rewrite
// from running on this request and borking URL names that need to be
// handled by mod_pagespeed.
apr_status_t bypass_translators_for_pagespeed_resources(request_rec *request) {
  std::string url = get_request_url(request);
  StringPiece url_piece(url);
  apr_status_t handled = DECLINED;
  if (url_piece.ends_with(kStatisticsHandler) ||
      url_piece.ends_with(kBeaconHandler)) {
    handled = OK;
  } else {
    ApacheRewriteDriverFactory* factory =
        InstawebContext::Factory(request->server);
    RewriteDriver* rewrite_driver = factory->NewRewriteDriver();
    RewriteFilter* filter;
    scoped_ptr<OutputResource> output_resource(
        rewrite_driver->DecodeOutputResource(url, &filter));
    if (output_resource.get() != NULL) {
      handled = OK;
      request->filename = apr_pstrcat(
          request->pool, "mod_pagespeed:", request->unparsed_uri, NULL);
    }
    factory->ReleaseRewriteDriver(rewrite_driver);
  }
  return handled;
}

}  // namespace net_instaweb
<commit_msg>Avoid 403s when serving mod_pagespeed resources due to bogus request->filename.<commit_after>// Copyright 2010 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Author: lsong@google.com (Libo Song)
//         jmarantz@google.com (Joshua Marantz)

#include "net/instaweb/apache/instaweb_handler.h"

#include "apr_strings.h"
#include "base/basictypes.h"
#include "base/scoped_ptr.h"
#include "net/instaweb/apache/apache_slurp.h"
#include "net/instaweb/apache/apr_statistics.h"
#include "net/instaweb/apache/apr_timer.h"
#include "net/instaweb/apache/header_util.h"
#include "net/instaweb/apache/instaweb_context.h"
#include "net/instaweb/apache/serf_async_callback.h"
#include "net/instaweb/apache/serf_url_async_fetcher.h"
#include "net/instaweb/apache/mod_instaweb.h"
#include "net/instaweb/rewriter/public/add_instrumentation_filter.h"
#include "net/instaweb/rewriter/public/output_resource.h"
#include "net/instaweb/rewriter/public/rewrite_driver.h"
#include "net/instaweb/util/public/google_message_handler.h"
#include "net/instaweb/util/public/message_handler.h"
#include "net/instaweb/util/public/simple_meta_data.h"
#include "net/instaweb/util/public/string_util.h"
#include "net/instaweb/util/public/string_writer.h"
#include "http_config.h"
#include "http_core.h"
#include "http_log.h"
#include "http_protocol.h"

namespace net_instaweb {

namespace {

const char kStatisticsHandler[] = "mod_pagespeed_statistics";
const char kBeaconHandler[] = "mod_pagespeed_beacon";

bool IsCompressibleContentType(const char* content_type) {
  if (content_type == NULL) {
    return false;
  }
  std::string type = content_type;
  size_t separator_idx = type.find(";");
  if (separator_idx != std::string::npos) {
    type.erase(separator_idx);
  }

  bool res = false;
  if (type.find("text/") == 0) {
    res = true;
  } else if (type.find("application/") == 0) {
    if (type.find("javascript") != type.npos ||
        type.find("json") != type.npos ||
        type.find("ecmascript") != type.npos ||
        type == "application/livescript" ||
        type == "application/js" ||
        type == "application/jscript" ||
        type == "application/x-js" ||
        type == "application/xhtml+xml" ||
        type == "application/xml") {
      res = true;
    }
  }

  return res;
}

// Default handler when the file is not found
void instaweb_default_handler(const std::string& url, request_rec* request) {
  request->status = HTTP_NOT_FOUND;
  ap_set_content_type(request, "text/html; charset=utf-8");
  ap_rputs("<title>Not Found</title>", request);
  ap_rputs("
Apache server with mod_pagespeed
OK", request);
  ap_rputs("
NOT FOUND:", request);
  ap_rputs(url.c_str(), request);
  ap_rputs("", request);
}

// predeclare to minimize diffs for now.  TODO(jmarantz): reorder
void send_out_headers_and_body(
    request_rec* request,
    const SimpleMetaData& response_headers,
    const std::string& output);

// Determines whether the url can be handled as a mod_pagespeed resource,
// and handles it, returning true.  A 'true' routine means that this
// method believed the URL was a mod_pagespeed resource -- it does not
// imply that it was handled successfully.  That information will be
// in the status code in the response headers.
bool handle_as_resource(ApacheRewriteDriverFactory* factory,
                        request_rec* request,
                        const std::string& url) {
  RewriteDriver* rewrite_driver = factory->NewRewriteDriver();

  SimpleMetaData request_headers, response_headers;
  int n = arraysize(RewriteDriver::kPassThroughRequestAttributes);
  for (int i = 0; i < n; ++i) {
    const char* value = apr_table_get(
        request->headers_in,
        RewriteDriver::kPassThroughRequestAttributes[i]);
    if (value != NULL) {
      request_headers.Add(RewriteDriver::kPassThroughRequestAttributes[i],
                          value);
    }
  }
  std::string output;  // TODO(jmarantz): quit buffering resource output
  StringWriter writer(&output);
  MessageHandler* message_handler = factory->message_handler();
  SerfAsyncCallback* callback = new SerfAsyncCallback(
      &response_headers, &writer);
  bool handled = rewrite_driver->FetchResource(
      url, request_headers, callback->response_headers(), callback->writer(),
      message_handler, callback);
  if (handled) {
    message_handler->Message(kInfo, "Fetching resource %s...", url.c_str());
    if (!callback->done()) {
      SerfUrlAsyncFetcher* serf_async_fetcher =
          factory->serf_url_async_fetcher();
      AprTimer timer;
      int64 max_ms = factory->fetcher_time_out_ms();
      for (int64 start_ms = timer.NowMs(), now_ms = start_ms;
           !callback->done() && now_ms - start_ms < max_ms;
           now_ms = timer.NowMs()) {
        int64 remaining_us = max_ms - (now_ms - start_ms);
        serf_async_fetcher->Poll(remaining_us);
      }

      if (!callback->done()) {
        message_handler->Message(kError, "Timeout on url %s", url.c_str());
      }
    }
    if (callback->success()) {
      message_handler->Message(kInfo, "Fetch succeeded for %s, status=%d",
                              url.c_str(), response_headers.status_code());
      send_out_headers_and_body(request, response_headers, output);
    } else {
      message_handler->Message(kError, "Fetch failed for %s, status=%d",
                              url.c_str(), response_headers.status_code());
      factory->Increment404Count();
      instaweb_default_handler(url, request);
    }
  } else {
    callback->Done(false);
  }
  callback->Release();
  factory->ReleaseRewriteDriver(rewrite_driver);
  return handled;
}

void send_out_headers_and_body(
    request_rec* request,
    const SimpleMetaData& response_headers,
    const std::string& output) {
  if (response_headers.status_code() != 0) {
    request->status = response_headers.status_code();
  }
  for (int idx = 0; idx < response_headers.NumAttributes(); ++idx) {
    const char* name = response_headers.Name(idx);
    const char* value = response_headers.Value(idx);
    if (strcasecmp(name, HttpAttributes::kContentType) == 0) {
      // ap_set_content_type does not make a copy of the string, we need
      // to duplicate it.
      char* ptr = apr_pstrdup(request->pool, value);
      ap_set_content_type(request, ptr);
    } else {
      if (strcasecmp(name, HttpAttributes::kCacheControl) == 0) {
        SetupCacheRepair(value, request);
      }
      // apr_table_add makes copies of both head key and value, so we do not
      // have to duplicate them.
      apr_table_add(request->headers_out, name, value);
    }
  }
  if (response_headers.status_code() == HttpStatus::kOK &&
      IsCompressibleContentType(request->content_type)) {
    // Make sure compression is enabled for this response.
    ap_add_output_filter("DEFLATE", NULL, request, request->connection);
  }

  // Recompute the content-length, because the content may have changed.
  ap_set_content_length(request, output.size());
  // Send the body
  ap_rwrite(output.c_str(), output.size(), request);
}

}  // namespace

apr_status_t repair_caching_header(ap_filter_t *filter,
                                   apr_bucket_brigade *bb) {
  request_rec* request = filter->r;
  RepairCachingHeaders(request);
  ap_remove_output_filter(filter);
  return ap_pass_brigade(filter->next, bb);
}

std::string get_request_url(request_rec* request) {
  /*
   * In some contexts we are seeing relative URLs passed
   * into request->unparsed_uri.  But when using mod_slurp, the rewritten
   * HTML contains complete URLs, so this construction yields the host:port
   * prefix twice.
   *
   * TODO(jmarantz): Figure out how to do this correctly at all times.
   */
  std::string url;
  if (strncmp(request->unparsed_uri, "http://", 7) == 0) {
    url = request->unparsed_uri;
  } else {
    url = ap_construct_url(request->pool, request->unparsed_uri, request);
  }
  return url;
}

int instaweb_handler(request_rec* request) {
  ApacheRewriteDriverFactory* factory =
      InstawebContext::Factory(request->server);
  int ret = OK;

  // Only handle GET request
  if (request->method_number != M_GET) {
    ap_log_rerror(APLOG_MARK, APLOG_DEBUG, APR_SUCCESS, request,
                  "Not GET request: %d.", request->method_number);
    ret = DECLINED;
  } else if (strcmp(request->handler, kStatisticsHandler) == 0) {
    std::string output;
    SimpleMetaData response_headers;
    StringWriter writer(&output);
    AprStatistics* statistics = factory->statistics();
    if (statistics) {
      statistics->Dump(&writer, factory->message_handler());
    }
    send_out_headers_and_body(request, response_headers, output);
  } else if (strcmp(request->handler, kBeaconHandler) == 0) {
    RewriteDriver* driver = factory->NewRewriteDriver();
    AddInstrumentationFilter* aif = driver->add_instrumentation_filter();
    if (aif && aif->HandleBeacon(request->unparsed_uri)) {
      ret = HTTP_NO_CONTENT;
    } else {
      ret = DECLINED;
    }
    factory->ReleaseRewriteDriver(driver);
  } else {
    std::string url = get_request_url(request);
    if (!handle_as_resource(factory, request, url)) {
      if (factory->slurping_enabled()) {
        SlurpUrl(url, factory, request);
        if (request->status == HTTP_NOT_FOUND) {
          factory->IncrementSlurpCount();
        }
      } else {
        ret = DECLINED;
      }
    }
  }
  return ret;
}

// This translator must be inserted into the translate_name chain
// prior to mod_rewrite.  By responding "OK" we prevent mod_rewrite
// from running on this request and borking URL names that need to be
// handled by mod_pagespeed.
apr_status_t bypass_translators_for_pagespeed_resources(request_rec *request) {
  std::string url = get_request_url(request);
  StringPiece url_piece(url);
  apr_status_t handled = DECLINED;
  if (url_piece.ends_with(kStatisticsHandler) ||
      url_piece.ends_with(kBeaconHandler)) {
    handled = OK;
  } else {
    ApacheRewriteDriverFactory* factory =
        InstawebContext::Factory(request->server);
    RewriteDriver* rewrite_driver = factory->NewRewriteDriver();
    RewriteFilter* filter;
    scoped_ptr<OutputResource> output_resource(
        rewrite_driver->DecodeOutputResource(url, &filter));
    if (output_resource.get() != NULL) {
      handled = OK;
      // TODO(jmarantz): What should these lines really be?  Deleting
      // "mod_pagespeed:", doesn't help matters any: we always obtain a 403 for
      // any resource request.  By contrast, the present form yields results
      // reliably, at the cost of 4 error_log entries for each bogus URL lookup
      // we encounter.  Those *are* requests for bogus URLs, but the intent is
      // clearly to avoid DoS when our logs are exhausted by a shower of junk
      // requests.  That said:
      //   1) no setting of request->filename based on request->unparsed_uri
      //      appears to work.
      //   2) We get an error_log entry when we fetch an ordinary bogus url,
      //      too, we just don't get 4 of them.
      // request->filename = NULL;  // Also serves data, but fills logs.
      // request->filename = apr_pstrcat(
      //     request->pool, "mod_pagespeed:", request->unparsed_uri, NULL);
    }
    factory->ReleaseRewriteDriver(rewrite_driver);
  }
  return handled;
}

}  // namespace net_instaweb
<|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia.  For licensing terms and
** conditions see http://qt.digia.com/licensing.  For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights.  These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/

#include "androidpotentialkit.h"
#include "androidconstants.h"
#include "androidconfigurations.h"

#include <utils/detailswidget.h>
#include <coreplugin/icore.h>
#include <projectexplorer/kitmanager.h>
#include <projectexplorer/kit.h>
#include <projectexplorer/kitinformation.h>
#include <qtsupport/qtversionmanager.h>
#include <qtsupport/baseqtversion.h>

#include <QGridLayout>
#include <QLabel>
#include <QPushButton>

using namespace Android;
using namespace Android::Internal;

QString AndroidPotentialKit::displayName() const
{
    return tr("Configure Android...");
}

void Android::Internal::AndroidPotentialKit::executeFromMenu()
{
    Core::ICore::showOptionsDialog(Constants::ANDROID_SETTINGS_CATEGORY,
                                   Constants::ANDROID_SETTINGS_ID);
}

QWidget *AndroidPotentialKit::createWidget(QWidget *parent) const
{
    if (!isEnabled())
        return 0;
    return new AndroidPotentialKitWidget(parent);
}

bool AndroidPotentialKit::isEnabled() const
{
    QList<ProjectExplorer::Kit *> kits = ProjectExplorer::KitManager::kits();
    foreach (ProjectExplorer::Kit *kit, kits) {
        Core::Id deviceId = ProjectExplorer::DeviceKitInformation::deviceId(kit);
        if (kit->isAutoDetected()
                && deviceId == Core::Id(Constants::ANDROID_DEVICE_ID)
                && !kit->isSdkProvided()) {
            return false;
        }
    }

    bool found = false;
    foreach (QtSupport::BaseQtVersion *version, QtSupport::QtVersionManager::validVersions()) {
        if (version->type() == QLatin1String(Constants::ANDROIDQT)) {
            found = true;
            break;
        }
    }

    return found;
}

AndroidPotentialKitWidget::AndroidPotentialKitWidget(QWidget *parent)
    : Utils::DetailsWidget(parent)
{
    setSummaryText(QLatin1String("Create Android Kits"));
    setIcon(QIcon(QLatin1String(Constants::ANDROID_SETTINGS_CATEGORY_ICON)));
    //detailsWidget->setState(Utils::DetailsWidget::NoSummary);
    QWidget *mainWidget = new QWidget(this);
    setWidget(mainWidget);

    QGridLayout *layout = new QGridLayout(mainWidget);
    layout->setMargin(0);
    QLabel *label = new QLabel;
    label->setText(tr("Qt Creator needs additional settings to enable Android support."
                      " You can configure those settings in the Options dialog."));
    label->setWordWrap(true);
    layout->addWidget(label, 0, 0, 1, 2);

    QPushButton *openOptions = new QPushButton;
    openOptions->setText(tr("Open Settings"));
    openOptions->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
    layout->addWidget(openOptions, 1, 1);

    connect(openOptions, SIGNAL(clicked()),
            this, SLOT(openOptions()));

    connect(AndroidConfigurations::instance(), SIGNAL(updated()),
            this, SLOT(recheck()));
}

void AndroidPotentialKitWidget::openOptions()
{
    Core::ICore::showOptionsDialog(Constants::ANDROID_SETTINGS_CATEGORY,
                                   Constants::ANDROID_SETTINGS_ID);
}

void AndroidPotentialKitWidget::recheck()
{
    QList<ProjectExplorer::Kit *> kits = ProjectExplorer::KitManager::kits();
    foreach (ProjectExplorer::Kit *kit, kits) {
        Core::Id deviceId = ProjectExplorer::DeviceKitInformation::deviceId(kit);
        if (kit->isAutoDetected()
                && deviceId == Core::Id(Constants::ANDROID_DEVICE_ID)
                && !kit->isSdkProvided()) {
            setVisible(false);
            return;
        }
    }
}
<commit_msg>Give Android potential kit a warning icon<commit_after>/****************************************************************************
**
** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia.  For licensing terms and
** conditions see http://qt.digia.com/licensing.  For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights.  These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/

#include "androidpotentialkit.h"
#include "androidconstants.h"
#include "androidconfigurations.h"

#include <utils/detailswidget.h>
#include <coreplugin/icore.h>
#include <projectexplorer/kitmanager.h>
#include <projectexplorer/kit.h>
#include <projectexplorer/kitinformation.h>
#include <qtsupport/qtversionmanager.h>
#include <qtsupport/baseqtversion.h>

#include <QGridLayout>
#include <QLabel>
#include <QPushButton>

using namespace Android;
using namespace Android::Internal;

QString AndroidPotentialKit::displayName() const
{
    return tr("Configure Android...");
}

void Android::Internal::AndroidPotentialKit::executeFromMenu()
{
    Core::ICore::showOptionsDialog(Constants::ANDROID_SETTINGS_CATEGORY,
                                   Constants::ANDROID_SETTINGS_ID);
}

QWidget *AndroidPotentialKit::createWidget(QWidget *parent) const
{
    if (!isEnabled())
        return 0;
    return new AndroidPotentialKitWidget(parent);
}

bool AndroidPotentialKit::isEnabled() const
{
    QList<ProjectExplorer::Kit *> kits = ProjectExplorer::KitManager::kits();
    foreach (ProjectExplorer::Kit *kit, kits) {
        Core::Id deviceId = ProjectExplorer::DeviceKitInformation::deviceId(kit);
        if (kit->isAutoDetected()
                && deviceId == Core::Id(Constants::ANDROID_DEVICE_ID)
                && !kit->isSdkProvided()) {
            return false;
        }
    }

    bool found = false;
    foreach (QtSupport::BaseQtVersion *version, QtSupport::QtVersionManager::validVersions()) {
        if (version->type() == QLatin1String(Constants::ANDROIDQT)) {
            found = true;
            break;
        }
    }

    return found;
}

AndroidPotentialKitWidget::AndroidPotentialKitWidget(QWidget *parent)
    : Utils::DetailsWidget(parent)
{
    setSummaryText(QLatin1String("Android has not been configured. Create Android kits."));
    setIcon(QIcon(QLatin1String(":/projectexplorer/images/compile_warning.png")));
    //detailsWidget->setState(Utils::DetailsWidget::NoSummary);
    QWidget *mainWidget = new QWidget(this);
    setWidget(mainWidget);

    QGridLayout *layout = new QGridLayout(mainWidget);
    layout->setMargin(0);
    QLabel *label = new QLabel;
    label->setText(tr("Qt Creator needs additional settings to enable Android support."
                      " You can configure those settings in the Options dialog."));
    label->setWordWrap(true);
    layout->addWidget(label, 0, 0, 1, 2);

    QPushButton *openOptions = new QPushButton;
    openOptions->setText(tr("Open Settings"));
    openOptions->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
    layout->addWidget(openOptions, 1, 1);

    connect(openOptions, SIGNAL(clicked()),
            this, SLOT(openOptions()));

    connect(AndroidConfigurations::instance(), SIGNAL(updated()),
            this, SLOT(recheck()));
}

void AndroidPotentialKitWidget::openOptions()
{
    Core::ICore::showOptionsDialog(Constants::ANDROID_SETTINGS_CATEGORY,
                                   Constants::ANDROID_SETTINGS_ID);
}

void AndroidPotentialKitWidget::recheck()
{
    QList<ProjectExplorer::Kit *> kits = ProjectExplorer::KitManager::kits();
    foreach (ProjectExplorer::Kit *kit, kits) {
        Core::Id deviceId = ProjectExplorer::DeviceKitInformation::deviceId(kit);
        if (kit->isAutoDetected()
                && deviceId == Core::Id(Constants::ANDROID_DEVICE_ID)
                && !kit->isSdkProvided()) {
            setVisible(false);
            return;
        }
    }
}
<|endoftext|>


<commit_before>#include "tools/cabana/messageswidget.h"

#include <QCompleter>
#include <QDialogButtonBox>
#include <QFontDatabase>
#include <QHeaderView>
#include <QLineEdit>
#include <QPushButton>
#include <QSortFilterProxyModel>
#include <QTextEdit>
#include <QVBoxLayout>

#include "tools/cabana/dbcmanager.h"

MessagesWidget::MessagesWidget(QWidget *parent) : QWidget(parent) {
  QVBoxLayout *main_layout = new QVBoxLayout(this);

  // DBC file selector
  QHBoxLayout *dbc_file_layout = new QHBoxLayout();
  dbc_combo = new QComboBox(this);
  auto dbc_names = dbc()->allDBCNames();
  for (const auto &name : dbc_names) {
    dbc_combo->addItem(QString::fromStdString(name));
  }
  dbc_combo->model()->sort(0);
  dbc_combo->setEditable(true);
  dbc_combo->setCurrentText(QString());
  dbc_combo->setInsertPolicy(QComboBox::NoInsert);
  dbc_combo->completer()->setCompletionMode(QCompleter::PopupCompletion);
  QFont font;
  font.setBold(true);
  dbc_combo->lineEdit()->setFont(font);
  dbc_file_layout->addWidget(dbc_combo);

  QPushButton *load_from_paste = new QPushButton(tr("Load from paste"), this);
  dbc_file_layout->addWidget(load_from_paste);

  dbc_file_layout->addStretch();
  QPushButton *save_btn = new QPushButton(tr("Save DBC"), this);
  dbc_file_layout->addWidget(save_btn);
  main_layout->addLayout(dbc_file_layout);

  // message filter
  QLineEdit *filter = new QLineEdit(this);
  filter->setPlaceholderText(tr("filter messages"));
  main_layout->addWidget(filter);

  // message table
  table_widget = new QTableView(this);
  model = new MessageListModel(this);
  QSortFilterProxyModel *proxy_model = new QSortFilterProxyModel(this);
  proxy_model->setSourceModel(model);
  proxy_model->setFilterCaseSensitivity(Qt::CaseInsensitive);
  proxy_model->setDynamicSortFilter(false);
  table_widget->setModel(proxy_model);
  table_widget->setSelectionBehavior(QAbstractItemView::SelectRows);
  table_widget->setSelectionMode(QAbstractItemView::SingleSelection);
  table_widget->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Expanding);
  table_widget->setSortingEnabled(true);
  table_widget->setColumnWidth(0, 250);
  table_widget->setColumnWidth(1, 80);
  table_widget->setColumnWidth(2, 80);
  table_widget->horizontalHeader()->setStretchLastSection(true);
  table_widget->verticalHeader()->hide();
  table_widget->sortByColumn(0, Qt::AscendingOrder);
  main_layout->addWidget(table_widget);

  // signals/slots
  QObject::connect(filter, &QLineEdit::textChanged, proxy_model, &QSortFilterProxyModel::setFilterFixedString);
  QObject::connect(can, &CANMessages::updated, model, &MessageListModel::updateState);
  QObject::connect(dbc_combo, SIGNAL(activated(const QString &)), SLOT(dbcSelectionChanged(const QString &)));
  QObject::connect(load_from_paste, &QPushButton::clicked, this, &MessagesWidget::loadFromPaste);
  QObject::connect(save_btn, &QPushButton::clicked, [=]() {
    // TODO: save DBC to file
  });
  QObject::connect(table_widget->selectionModel(), &QItemSelectionModel::currentChanged, [=](const QModelIndex &current, const QModelIndex &previous) {
    if (current.isValid()) {
      emit msgSelectionChanged(current.data(Qt::UserRole).toString());
    }
  });

  // For test purpose
  dbc_combo->setCurrentText("toyota_nodsu_pt_generated");
}

void MessagesWidget::dbcSelectionChanged(const QString &dbc_file) {
  dbc()->open(dbc_file);
  // TODO: reset model?
  table_widget->sortByColumn(0, Qt::AscendingOrder);
}

void MessagesWidget::loadFromPaste() {
  LoadDBCDialog dlg(this);
  if (dlg.exec()) {
    dbc()->open("from paste", dlg.dbc_edit->toPlainText());
    dbc_combo->setCurrentText("loaded from paste");
  }
}

// MessageListModel

QVariant MessageListModel::headerData(int section, Qt::Orientation orientation, int role) const {
  if (orientation == Qt::Horizontal && role == Qt::DisplayRole)
    return (QString[]){"Name", "ID", "Count", "Bytes"}[section];
  return {};
}

QVariant MessageListModel::data(const QModelIndex &index, int role) const {
  if (role == Qt::DisplayRole) {
    auto it = std::next(can->can_msgs.begin(), index.row());
    if (it != can->can_msgs.end() && !it.value().empty()) {
      const QString &msg_id = it.key();
      switch (index.column()) {
        case 0: {
          auto msg = dbc()->msg(msg_id);
          return msg ? msg->name.c_str() : "untitled";
        }
        case 1: return msg_id;
        case 2: return can->counters[msg_id];
        case 3: return toHex(it.value().front().dat);
      }
    }
  } else if (role == Qt::UserRole) {
    return std::next(can->can_msgs.begin(), index.row()).key();
  } else if (role == Qt::FontRole) {
    if (index.column() == 3) {
      return QFontDatabase::systemFont(QFontDatabase::FixedFont);
    }
  }
  return {};
}

void MessageListModel::updateState() {
  int prev_row_count = row_count;
  row_count = can->can_msgs.size();
  int delta = row_count - prev_row_count;
  if (delta > 0) {
    beginInsertRows({}, prev_row_count, row_count - 1);
    endInsertRows();
  } else if (delta < 0) {
    beginRemoveRows({}, row_count, prev_row_count - 1);
    endRemoveRows();
  }

  if (row_count > 0) {
    emit dataChanged(index(0, 0), index(row_count - 1, 3), {Qt::DisplayRole});
  }
}

LoadDBCDialog::LoadDBCDialog(QWidget *parent) : QDialog(parent) {
  QVBoxLayout *main_layout = new QVBoxLayout(this);
  dbc_edit = new QTextEdit(this);
  dbc_edit->setAcceptRichText(false);
  dbc_edit->setPlaceholderText(tr("paste DBC file here"));
  main_layout->addWidget(dbc_edit);
  auto buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel);
  main_layout->addWidget(buttonBox);

  setFixedWidth(640);
  connect(buttonBox, &QDialogButtonBox::accepted, this, &QDialog::accept);
  connect(buttonBox, &QDialogButtonBox::rejected, this, &QDialog::reject);
}
<commit_msg>cabana: display a clear button in filter string edit box (#26152)<commit_after>#include "tools/cabana/messageswidget.h"

#include <QCompleter>
#include <QDialogButtonBox>
#include <QFontDatabase>
#include <QHeaderView>
#include <QLineEdit>
#include <QPushButton>
#include <QSortFilterProxyModel>
#include <QTextEdit>
#include <QVBoxLayout>

#include "tools/cabana/dbcmanager.h"

MessagesWidget::MessagesWidget(QWidget *parent) : QWidget(parent) {
  QVBoxLayout *main_layout = new QVBoxLayout(this);

  // DBC file selector
  QHBoxLayout *dbc_file_layout = new QHBoxLayout();
  dbc_combo = new QComboBox(this);
  auto dbc_names = dbc()->allDBCNames();
  for (const auto &name : dbc_names) {
    dbc_combo->addItem(QString::fromStdString(name));
  }
  dbc_combo->model()->sort(0);
  dbc_combo->setEditable(true);
  dbc_combo->setCurrentText(QString());
  dbc_combo->setInsertPolicy(QComboBox::NoInsert);
  dbc_combo->completer()->setCompletionMode(QCompleter::PopupCompletion);
  QFont font;
  font.setBold(true);
  dbc_combo->lineEdit()->setFont(font);
  dbc_file_layout->addWidget(dbc_combo);

  QPushButton *load_from_paste = new QPushButton(tr("Load from paste"), this);
  dbc_file_layout->addWidget(load_from_paste);

  dbc_file_layout->addStretch();
  QPushButton *save_btn = new QPushButton(tr("Save DBC"), this);
  dbc_file_layout->addWidget(save_btn);
  main_layout->addLayout(dbc_file_layout);

  // message filter
  QLineEdit *filter = new QLineEdit(this);
  filter->setClearButtonEnabled(true);
  filter->setPlaceholderText(tr("filter messages"));
  main_layout->addWidget(filter);

  // message table
  table_widget = new QTableView(this);
  model = new MessageListModel(this);
  QSortFilterProxyModel *proxy_model = new QSortFilterProxyModel(this);
  proxy_model->setSourceModel(model);
  proxy_model->setFilterCaseSensitivity(Qt::CaseInsensitive);
  proxy_model->setDynamicSortFilter(false);
  table_widget->setModel(proxy_model);
  table_widget->setSelectionBehavior(QAbstractItemView::SelectRows);
  table_widget->setSelectionMode(QAbstractItemView::SingleSelection);
  table_widget->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Expanding);
  table_widget->setSortingEnabled(true);
  table_widget->setColumnWidth(0, 250);
  table_widget->setColumnWidth(1, 80);
  table_widget->setColumnWidth(2, 80);
  table_widget->horizontalHeader()->setStretchLastSection(true);
  table_widget->verticalHeader()->hide();
  table_widget->sortByColumn(0, Qt::AscendingOrder);
  main_layout->addWidget(table_widget);

  // signals/slots
  QObject::connect(filter, &QLineEdit::textChanged, proxy_model, &QSortFilterProxyModel::setFilterFixedString);
  QObject::connect(can, &CANMessages::updated, model, &MessageListModel::updateState);
  QObject::connect(dbc_combo, SIGNAL(activated(const QString &)), SLOT(dbcSelectionChanged(const QString &)));
  QObject::connect(load_from_paste, &QPushButton::clicked, this, &MessagesWidget::loadFromPaste);
  QObject::connect(save_btn, &QPushButton::clicked, [=]() {
    // TODO: save DBC to file
  });
  QObject::connect(table_widget->selectionModel(), &QItemSelectionModel::currentChanged, [=](const QModelIndex &current, const QModelIndex &previous) {
    if (current.isValid()) {
      emit msgSelectionChanged(current.data(Qt::UserRole).toString());
    }
  });

  // For test purpose
  dbc_combo->setCurrentText("toyota_nodsu_pt_generated");
}

void MessagesWidget::dbcSelectionChanged(const QString &dbc_file) {
  dbc()->open(dbc_file);
  // TODO: reset model?
  table_widget->sortByColumn(0, Qt::AscendingOrder);
}

void MessagesWidget::loadFromPaste() {
  LoadDBCDialog dlg(this);
  if (dlg.exec()) {
    dbc()->open("from paste", dlg.dbc_edit->toPlainText());
    dbc_combo->setCurrentText("loaded from paste");
  }
}

// MessageListModel

QVariant MessageListModel::headerData(int section, Qt::Orientation orientation, int role) const {
  if (orientation == Qt::Horizontal && role == Qt::DisplayRole)
    return (QString[]){"Name", "ID", "Count", "Bytes"}[section];
  return {};
}

QVariant MessageListModel::data(const QModelIndex &index, int role) const {
  if (role == Qt::DisplayRole) {
    auto it = std::next(can->can_msgs.begin(), index.row());
    if (it != can->can_msgs.end() && !it.value().empty()) {
      const QString &msg_id = it.key();
      switch (index.column()) {
        case 0: {
          auto msg = dbc()->msg(msg_id);
          return msg ? msg->name.c_str() : "untitled";
        }
        case 1: return msg_id;
        case 2: return can->counters[msg_id];
        case 3: return toHex(it.value().front().dat);
      }
    }
  } else if (role == Qt::UserRole) {
    return std::next(can->can_msgs.begin(), index.row()).key();
  } else if (role == Qt::FontRole) {
    if (index.column() == 3) {
      return QFontDatabase::systemFont(QFontDatabase::FixedFont);
    }
  }
  return {};
}

void MessageListModel::updateState() {
  int prev_row_count = row_count;
  row_count = can->can_msgs.size();
  int delta = row_count - prev_row_count;
  if (delta > 0) {
    beginInsertRows({}, prev_row_count, row_count - 1);
    endInsertRows();
  } else if (delta < 0) {
    beginRemoveRows({}, row_count, prev_row_count - 1);
    endRemoveRows();
  }

  if (row_count > 0) {
    emit dataChanged(index(0, 0), index(row_count - 1, 3), {Qt::DisplayRole});
  }
}

LoadDBCDialog::LoadDBCDialog(QWidget *parent) : QDialog(parent) {
  QVBoxLayout *main_layout = new QVBoxLayout(this);
  dbc_edit = new QTextEdit(this);
  dbc_edit->setAcceptRichText(false);
  dbc_edit->setPlaceholderText(tr("paste DBC file here"));
  main_layout->addWidget(dbc_edit);
  auto buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel);
  main_layout->addWidget(buttonBox);

  setFixedWidth(640);
  connect(buttonBox, &QDialogButtonBox::accepted, this, &QDialog::accept);
  connect(buttonBox, &QDialogButtonBox::rejected, this, &QDialog::reject);
}
<|endoftext|>