<commit_before>#include <sstream>
#include <pwd.h>
#include <iostream>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <dirent.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <string>
#include <errno.h>
#include <iomanip>
#include <vector>
#include <algorithm>
#include <time.h>
#include <stdlib.h>
#include <fcntl.h>

using namespace std;

//PRINTING OUT VECTOR OF FILES
void print_files(vector<string>& x) {
	unsigned z = 0;
	for(unsigned i = 0; i < x.size(); ++i) {
		if(z == 5)
			cout << endl;
		cout << setw(16) << left << x.at(i) << "  ";
			++z;
	}
	cout << endl;
	return;
}

void print_l(vector<string>& x) {
	struct stat club;
	int intake;
	string cow;
	string now;
	ssize_t g = 0;
	for(unsigned i = 0; i < x.size(); ++i) {
		now = x[i];
	//	int fd = open(now.c_str(), O_RDONLY);
	//	if(fd == -1)
	//	{
	//		perror("open");
	//		exit(1);
	//	}
		if(stat(now.c_str(), &club) == -1) {
			perror("stat");
			exit(1);
		}
		g += club.st_size;
	//	int fo = close(fd);
	//	if(fo == -1)
	//	{
	//		perror("close");
	//		exit(1);
	//	}

	}
	cout << "total " << g << endl;
	for(unsigned e = 0; e < x.size(); ++e) {
		cow = x[e];
	//	int fd = open(now.c_str(), O_RDONLY);
	//	if(fd == -1)
	//	{
	//		perror("open");
	//		exit(1);
	//	}

		if(stat(cow.c_str(), &club) == -1) {
			perror("stat");
			exit(-1);
		}

		if(S_ISDIR(club.st_mode))
			cout << "d";
		else
			cout << "-";
		if((intake = access(cow.c_str(), R_OK)) == 0)
			cout << "r";
		else
			cout << "-";

		if((intake = access(cow.c_str(), W_OK)) == 0)
			cout << "w";
		else
			cout << "-";

		if((intake = access(cow.c_str(), X_OK)) == 0)
			cout << "x";
		else
			cout << "-";

		cout << "------" << " ";

		cout << club.st_nlink << " ";
		cout << club.st_uid << " ";
		cout << club.st_gid << " ";
		cout << setw(5) << club.st_size << " ";
		cout << setw(5) << club.st_mtime << "sec ";
		cout << left << setw(0) << x[e] << endl;
	//	int fo = close(fd);
	//	if(fo == -1)
	//	{
	//		perror("close");
	//		exit(1);
	//	}

	}

	return;

}

//-a
void alphabetize2(vector<string>& x) {
	unsigned i;
	vector<string> ad;
	vector<string> qw;
	unsigned j;
	unsigned k;
	for(i = 0; i < x.size(); i++)
	{
		if(x[i][0] >= 65 && x[i][0] <= 90){
			x[i][0] += 32;
			qw.push_back(x[i]);
		}

		if(x[i][0] == '.' && x[i][1] != '.'){
 			x[i].erase(0,1);
			ad.push_back(x[i]);
		}

	}
	sort(x.begin(), x.end());
	for(i = 0; i < x.size(); i++)
	{
		for(j = 0; j < qw.size(); j++)
		{
			if(qw[j] == x[i])
				x[i][0] -= 32;
		}
		for(k = 0; k < ad.size(); k++)
		{
			if(ad[k] == x[i])
				x[i].insert(0, ".");

		}
	}
}

//default alphabetize
void alphabetize(vector<string>& x) {
	unsigned i;
	vector<string> qw;
	unsigned j;
	for(i = 0; i < x.size(); i++)
	{
		if(x[i][0] >= 65 && x[i][0] <= 90){
			x[i][0] += 32;
			qw.push_back(x[i]);
		}
	}
	sort(x.begin(), x.end());
	for(i = 0; i < x.size(); i++)
	{
		for(j = 0; j < qw.size(); j++)
		{
			if(qw[j] == x[i])
				x[i][0] -= 32;
		}
	}
}

//default
static void lookup()//ls (no flags)
{
	vector<string> temp;
	DIR *start;
	struct dirent *entry;
	char* x;
	if((start=opendir(".")) == NULL)
	{
		perror("opendir");
		return;
	}

	do {
		errno = 0;
		if((entry = readdir(start)) != NULL)
		{
			x = entry->d_name;

			if(x[0] == '.')
				continue;

			temp.push_back(entry->d_name);
		}

	} while(entry != NULL);

	alphabetize(temp);
	print_files(temp);

	if(errno != 0)
		perror("error reading directory");

	closedir(start);
	return;
}

//-a
static void lookup2()
{
	vector<string> temp;
	DIR *start;
	struct dirent *entry;
	if((start=opendir(".")) == NULL) {
		perror("opendir");
		return;
	}

	do {
		errno = 0;
		if((entry = readdir(start)) != NULL) {
			temp.push_back(entry->d_name);
		}

	} while(entry != NULL);

	alphabetize2(temp);
	print_files(temp);

	if(errno != 0)
		perror("error reading directory");

	closedir(start);
	return;
}

//-la
static void lookup31()
{
	vector<string> temp;
	DIR *start;
	struct dirent *entry;

	if((start=opendir(".")) == NULL)
	{
		perror("opendir");
		return;
	}

	do {
		errno = 0;
		if((entry = readdir(start)) != NULL)
		{
			temp.push_back(entry->d_name);
		}

	} while(entry != NULL);

	alphabetize(temp);
	print_l(temp);

	if(errno != 0)
		perror("error reading directory");

	closedir(start);
	return;
}

//-l
static void lookup3()
{
	vector<string> temp;
	DIR *start;
	struct dirent *entry;
	char* x;

	if((start=opendir(".")) == NULL)
	{
		perror("opendir");
		return;
	}

	do {
		errno = 0;
		if((entry = readdir(start)) != NULL)
		{
			x = entry->d_name;

			if(x[0] == '.')
				continue;

			temp.push_back(entry->d_name);
		}

	} while(entry != NULL);

	alphabetize(temp);
	print_l(temp);

	if(errno != 0){

		perror("error reading directory");
	}

	closedir(start);
	return;
}

static void lookup_d1(char* q)
{
	vector<string> temp;
	DIR *start;
	struct dirent *entry;
	if((start=opendir(q)) == NULL)
	{
		perror("opendir");
		return;
	}

	do {
		errno = 0;
		if((entry = readdir(start)) != NULL)
		{
			temp.push_back(entry->d_name);
		}

	} while(entry != NULL);

	alphabetize(temp);
	print_files(temp);

	if(errno != 0)
		perror("error reading directory");

	closedir(start);
	return;
}

//-lR
static void dlookup_d(char* q)
{
	vector<string> temp;
	DIR *start;
	struct dirent *entry;
	char* x;
	if((start=opendir(q)) == NULL)
	{
		perror("opendir");
		return;
	}

	do {
		errno = 0;
		if((entry = readdir(start)) != NULL)
		{
			x = entry->d_name;

			if(x[0] == '.')
				continue;

			temp.push_back(entry->d_name);
		}

	} while(entry != NULL);

	alphabetize(temp);
	print_l(temp);

	if(errno != 0)
		perror("error reading directory");

	closedir(start);
	return;
}

//ls (passed in directory
static void lookup_d(char* q)
{
	vector<string> temp;
	DIR *start;
	struct dirent *entry;
	char* x;
	if((start=opendir(q)) == NULL)
	{
		perror("opendir");
		return;
	}

	do {
		errno = 0;
		if((entry = readdir(start)) != NULL)
		{
			x = entry->d_name;

			if(x[0] == '.')
				continue;

			temp.push_back(entry->d_name);
		}

	} while(entry != NULL);

	alphabetize(temp);
	print_files(temp);

	if(errno != 0)
		perror("error reading directory");

	closedir(start);
	return;
}

//-Ra
static void lookup41()
{

	vector<string> temp;
	DIR *start;
	struct dirent *entry;
	char* x;
	if((start=opendir(".")) == NULL)
	{
		perror("opendir");
		closedir(start);
		return;
	}

	do {
		errno = 0;
		if((entry = readdir(start)) != NULL)
		{
			if(entry->d_type == DT_DIR)
			{
				x = entry->d_name;
				if(x[0] == '.' && x[1] == '.')
					continue;
				cout << x << ":" << endl;
				lookup_d1(x);

			}

		}

	} while(entry != NULL);

	if(errno != 0)
	{
		perror("error reading directory");
		closedir(start);
		return;
	}

	closedir(start);
	return;
}

//-R
static void lookup4()
{

	vector<string> temp;
	DIR *start;
	struct dirent *entry;
	char* x;

	if((start=opendir(".")) == NULL)
	{
		perror("opendir");
		closedir(start);
		return;
	}

	do {
		errno = 0;
		if((entry = readdir(start)) != NULL)
		{
			if(entry->d_type == DT_DIR)
			{
				x = entry->d_name;
				if(x[0] == '.' && x[1] == '.')
					continue;
				cout << x << ":" << endl;
				lookup_d(x);

			}
		}

	} while(entry != NULL);

	if(errno != 0)
	{
		perror("error reading directory");
		closedir(start);
		return;
	}
	closedir(start);
	return;
}

//-Rl
static void lookup42()
{

	vector<string> temp;
	DIR *start;
	struct dirent *entry;
	char* x;

	if((start=opendir(".")) == NULL)
	{
		perror("opendir");
		closedir(start);
		return;
	}

	do {
		errno = 0;
		if((entry = readdir(start)) != NULL)
		{
			if(entry->d_type == DT_DIR)
			{
				x = entry->d_name;
				if(x[0] == '.' && x[1] == '.')
					continue;
				cout << x << ":" << endl;
				dlookup_d(x);

			}

		}

	} while(entry != NULL);

	if(errno != 0)
	{
		perror("error reading directory");
		closedir(start);
		return;
	}

	closedir(start);
	return;
}

int main( int argc, char *argv[]) {
	string flag = "-a";
	string flag2 = "-l";
	string flag3 = "-R";
	stringstream d;
	if(argc == 1)
	{
		lookup();
		return 0;
	}
	//for(int k = 0; k < argc; ++k)
	//	d << argv[k] << " ";

	int i = 1;
	for(; i < argc; ++i) {
		if(argv[i][0] != '-'){
			lookup_d(argv[i]);
			break;
		}
		else if(argv[i] == flag) {
			if(argc >= 3) {
			if(argv[2] == flag2)
				lookup31();
			else if(argv[2] == flag3)
				lookup41();
			}
			else
				lookup2();

		}
		else if(argv[i] == flag2) {
			if(argc >= 3) {
			if(argv[2] == flag)
				lookup31();
			else if(argv[2] == flag3)
				lookup42();
			}
			else
				lookup3();

		}
		else if(argv[i] == flag3){
			if(argc >= 3) {
			if(argv[2] == flag)
				lookup41();
			else if(argv[2] == flag2)
				lookup42();
			}
			else
				lookup4();
		}
		else if(strstr(argv[i], "a") != NULL)
		{
			if(strstr(argv[i], "l") != NULL)
				lookup31();
			if(strstr(argv[i], "R") != NULL)
				lookup41();
		}
		else if(strstr(argv[i], "l") != NULL)
		{
			if(strstr(argv[i], "R") != NULL)
				lookup42();
		}
	}

	return 0;
}
<commit_msg>ls.cpp added<commit_after>#include <sstream>
#include <pwd.h>
#include <iostream>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <dirent.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <string>
#include <errno.h>
#include <iomanip>
#include <vector>
#include <algorithm>
#include <time.h>
#include <stdlib.h>
#include <fcntl.h>

using namespace std;

//PRINTING OUT VECTOR OF FILES
void print_files(vector<string>& x) {
	unsigned z = 0;
	for(unsigned i = 0; i < x.size(); ++i) {
		if(z == 5)
			cout << endl;
		cout << setw(16) << left << x.at(i) << "  ";
			++z;
	}
	cout << endl;
	return;
}

void print_l(vector<string>& x) {
	struct stat club;
	int intake;
	string cow;
	string now;
	ssize_t g = 0;
	for(unsigned i = 0; i < x.size(); ++i) {
		now = x[i];
	//	int fd = open(now.c_str(), O_RDONLY);
	//	if(fd == -1)
	//	{
	//		perror("open");
	//		exit(1);
	//	}
		if(stat(now.c_str(), &club) == -1) {
			perror("stat");
			exit(1);
		}
		g += club.st_size;
	//	int fo = close(fd);
	//	if(fo == -1)
	//	{
	//		perror("close");
	//		exit(1);
	//	}

	}
	cout << "total " << g << endl;
	for(unsigned e = 0; e < x.size(); ++e) {
		cow = x[e];
	//	int fd = open(now.c_str(), O_RDONLY);
	//	if(fd == -1)
	//	{
	//		perror("open");
	//		exit(1);
	//	}

		if(stat(cow.c_str(), &club) == -1) {
			perror("stat");
			exit(-1);
		}

		if(S_ISDIR(club.st_mode))
			cout << "d";
		else
			cout << "-";
		if((intake = access(cow.c_str(), R_OK)) == 0)
			cout << "r";
		else
			cout << "-";

		if((intake = access(cow.c_str(), W_OK)) == 0)
			cout << "w";
		else
			cout << "-";

		if((intake = access(cow.c_str(), X_OK)) == 0)
			cout << "x";
		else
			cout << "-";

		cout << "------" << " ";

		cout << club.st_nlink << " ";
		cout << club.st_uid << " ";
		cout << club.st_gid << " ";
		cout << setw(5) << club.st_size << " ";
		cout << setw(5) << club.st_mtime << "sec ";
		cout << left << setw(0) << x[e] << endl;
	//	int fo = close(fd);
	//	if(fo == -1)
	//	{
	//		perror("close");
	//		exit(1);
	//	}

	}

	return;

}

//-a
void alphabetize2(vector<string>& x) {
	unsigned i;
	vector<string> ad;
	vector<string> qw;
	unsigned j;
	unsigned k;
	for(i = 0; i < x.size(); i++)
	{
		if(x[i][0] >= 65 && x[i][0] <= 90){
			x[i][0] += 32;
			qw.push_back(x[i]);
		}

		if(x[i][0] == '.' && x[i][1] != '.'){
 			x[i].erase(0,1);
			ad.push_back(x[i]);
		}

	}
	sort(x.begin(), x.end());
	for(i = 0; i < x.size(); i++)
	{
		for(j = 0; j < qw.size(); j++)
		{
			if(qw[j] == x[i])
				x[i][0] -= 32;
		}
		for(k = 0; k < ad.size(); k++)
		{
			if(ad[k] == x[i])
				x[i].insert(0, ".");

		}
	}
}

//default alphabetize
void alphabetize(vector<string>& x) {
	unsigned i;
	vector<string> qw;
	unsigned j;
	for(i = 0; i < x.size(); i++)
	{
		if(x[i][0] >= 65 && x[i][0] <= 90){
			x[i][0] += 32;
			qw.push_back(x[i]);
		}
	}
	sort(x.begin(), x.end());
	for(i = 0; i < x.size(); i++)
	{
		for(j = 0; j < qw.size(); j++)
		{
			if(qw[j] == x[i])
				x[i][0] -= 32;
		}
	}
}

//default
static void lookup()//ls (no flags)
{
	vector<string> temp;
	DIR *start;
	struct dirent *entry;
	char* x;
	if((start=opendir(".")) == NULL)
	{
		perror("opendir");
		return;
	}

	do {
		errno = 0;
		if((entry = readdir(start)) != NULL)
		{
			x = entry->d_name;

			if(x[0] == '.')
				continue;

			temp.push_back(entry->d_name);
		}

	} while(entry != NULL);

	alphabetize(temp);
	print_files(temp);

	if(errno != 0)
		perror("error reading directory");

	closedir(start);
	return;
}

//-a
static void lookup2()
{
	vector<string> temp;
	DIR *start;
	struct dirent *entry;
	if((start=opendir(".")) == NULL) {
		perror("opendir");
		return;
	}

	do {
		errno = 0;
		if((entry = readdir(start)) != NULL) {
			temp.push_back(entry->d_name);
		}

	} while(entry != NULL);

	alphabetize2(temp);
	print_files(temp);

	if(errno != 0)
		perror("error reading directory");

	closedir(start);
	return;
}

//-la
static void lookup31()
{
	vector<string> temp;
	DIR *start;
	struct dirent *entry;

	if((start=opendir(".")) == NULL)
	{
		perror("opendir");
		return;
	}

	do {
		errno = 0;
		if((entry = readdir(start)) != NULL)
		{
			temp.push_back(entry->d_name);
		}

	} while(entry != NULL);

	alphabetize(temp);
	print_l(temp);

	if(errno != 0)
		perror("error reading directory");

	closedir(start);
	return;
}

//-l
static void lookup3()
{
	vector<string> temp;
	DIR *start;
	struct dirent *entry;
	char* x;

	if((start=opendir(".")) == NULL)
	{
		perror("opendir");
		return;
	}

	do {
		errno = 0;
		if((entry = readdir(start)) != NULL)
		{
			x = entry->d_name;

			if(x[0] == '.')
				continue;

			temp.push_back(entry->d_name);
		}

	} while(entry != NULL);

	alphabetize(temp);
	print_l(temp);

	if(errno != 0){

		perror("error reading directory");
	}

	closedir(start);
	return;
}

static void lookup_d1(char* q)
{
	vector<string> temp;
	DIR *start;
	struct dirent *entry;
	if((start=opendir(q)) == NULL)
	{
		perror("opendir");
		return;
	}

	do {
		errno = 0;
		if((entry = readdir(start)) != NULL)
		{
			temp.push_back(entry->d_name);
		}

	} while(entry != NULL);

	alphabetize(temp);
	print_files(temp);

	if(errno != 0)
		perror("error reading directory");

	closedir(start);
	return;
}

//-lR
static void dlookup_d(char* q)
{
	vector<string> temp;
	DIR *start;
	struct dirent *entry;
	char* x;
	if((start=opendir(q)) == NULL)
	{
		perror("opendir");
		return;
	}

	do {
		errno = 0;
		if((entry = readdir(start)) != NULL)
		{
			x = entry->d_name;

			if(x[0] == '.')
				continue;

			temp.push_back(entry->d_name);
		}

	} while(entry != NULL);

	alphabetize(temp);
	print_l(temp);

	if(errno != 0)
		perror("error reading directory");

	closedir(start);
	return;
}

//ls (passed in directory
static void lookup_d(char* q)
{
	vector<string> temp;
	DIR *start;
	struct dirent *entry;
	char* x;
	if((start=opendir(q)) == NULL)
	{
		perror("opendir");
		return;
	}

	do {
		errno = 0;
		if((entry = readdir(start)) != NULL)
		{
			x = entry->d_name;

			if(x[0] == '.')
				continue;

			temp.push_back(entry->d_name);
		}

	} while(entry != NULL);

	alphabetize(temp);
	print_files(temp);

	if(errno != 0)
		perror("error reading directory");

	closedir(start);
	return;
}

//-Ra
static void lookup41()
{

	vector<string> temp;
	DIR *start;
	struct dirent *entry;
	char* x;
	if((start=opendir(".")) == NULL)
	{
		perror("opendir");
		closedir(start);
		return;
	}

	do {
		errno = 0;
		if((entry = readdir(start)) != NULL)
		{
			if(entry->d_type == DT_DIR)
			{
				x = entry->d_name;
				if(x[0] == '.' && x[1] == '.')
					continue;
				cout << x << ":" << endl;
				lookup_d1(x);

			}

		}

	} while(entry != NULL);

	if(errno != 0)
	{
		perror("error reading directory");
		closedir(start);
		return;
	}

	closedir(start);
	return;
}

//-R
static void lookup4()
{

	vector<string> temp;
	DIR *start;
	struct dirent *entry;
	char* x;

	if((start=opendir(".")) == NULL)
	{
		perror("opendir");
		closedir(start);
		return;
	}

	do {
		errno = 0;
		if((entry = readdir(start)) != NULL)
		{
			if(entry->d_type == DT_DIR)
			{
				x = entry->d_name;
				if(x[0] == '.' && x[1] == '.')
					continue;
				cout << x << ":" << endl;
				lookup_d(x);

			}
		}

	} while(entry != NULL);

	if(errno != 0)
	{
		perror("error reading directory");
		closedir(start);
		return;
	}
	closedir(start);
	return;
}

//-Rl
static void lookup42()
{

	vector<string> temp;
	DIR *start;
	struct dirent *entry;
	char* x;

	if((start=opendir(".")) == NULL)
	{
		perror("opendir");
		closedir(start);
		return;
	}

	do {
		errno = 0;
		if((entry = readdir(start)) != NULL)
		{
			if(entry->d_type == DT_DIR)
			{
				x = entry->d_name;
				if(x[0] == '.' && x[1] == '.')
					continue;
				cout << x << ":" << endl;
				dlookup_d(x);

			}

		}

	} while(entry != NULL);

	if(errno != 0)
	{
		perror("error reading directory");
		closedir(start);
		return;
	}

	closedir(start);
	return;
}

int main( int argc, char *argv[]) {
	string flag = "-a";
	string flag2 = "-l";
	string flag3 = "-R";

	if(argc == 1)
	{
		lookup();
		return 0;
	}

	int i = 1;
	for(; i < argc; ++i) {
		if(argv[i][0] != '-'){
			lookup_d(argv[i]);
		}
		else if(argv[i] == flag) {
			if(argc >= 3) {
			if(argv[2] == flag2)
				lookup31();
			else if(argv[2] == flag3)
				lookup41();
			}
			else
				lookup2();

		}
		else if(argv[i] == flag2) {
			if(argc >= 3) {
			if(argv[2] == flag)
				lookup31();
			else if(argv[2] == flag3)
				lookup42();
			}
			else
				lookup3();

		}
		else if(argv[i] == flag3){
			if(argc >= 3) {
			if(argv[2] == flag)
				lookup41();
			else if(argv[2] == flag2)
				lookup42();
			}
			else
				lookup4();
		}
		else if(strstr(argv[i], "a") != NULL)
		{
			if(strstr(argv[i], "l") != NULL)
				lookup31();
			if(strstr(argv[i], "R") != NULL)
				lookup41();
		}
		else if(strstr(argv[i], "l") != NULL)
		{
			if(strstr(argv[i], "R") != NULL)
				lookup42();
		}
	}

	return 0;
}
<|endoftext|>


<commit_before>//
// Copyright (c) 2018 The nanoFramework project contributors
// Portions Copyright (c) 2006-2015, ARM Limited, All Rights Reserved
// Portions Copyright (c) Microsoft Corporation.  All rights reserved.
// See LICENSE file in the project root for full license information.
//

#include <ssl.h>
#include "mbedtls.h"

int ssl_connect_internal(int sd, const char* szTargetHost, int sslContextHandle)
{
    mbedTLS_NFContext* context;

    int ret = -1;

    // Retrieve SSL struct from g_SSL_Driver
    if((sslContextHandle >= (int)ARRAYSIZE(g_SSL_Driver.m_sslContextArray)) || (sslContextHandle < 0))
    {
        goto error;
    }

    // sd should already have been created
    // Now do the SSL negotiation
    context = (mbedTLS_NFContext*)g_SSL_Driver.m_sslContextArray[sslContextHandle].SslContext;
    if (context == NULL) goto error;

    // set socket
    context->server_fd->fd = sd;

    if(szTargetHost != NULL && szTargetHost[0] != 0)
    {
        if( (ret = mbedtls_ssl_set_hostname( context->ssl, szTargetHost )) != 0 )
        {
            // hostname_failed
            goto error;
        }
    }

    mbedtls_ssl_set_bio( context->ssl, context->server_fd, mbedtls_net_send, mbedtls_net_recv, mbedtls_net_recv_timeout );

    while( ( ret = mbedtls_ssl_handshake( context->ssl ) ) != 0 )
    {
        if( ret != MBEDTLS_ERR_SSL_WANT_READ && ret != MBEDTLS_ERR_SSL_WANT_WRITE )
        {
            // SSL handshake failed
            //mbedtls_printf( " failed\n  ! mbedtls_ssl_handshake returned -0x%x\n\n", -ret );
            goto error;
        }
    }

    SOCKET_DRIVER.SetSocketSslData(sd, (void*)context);

error:
    return ret;
}
<commit_msg>Improve comments<commit_after>//
// Copyright (c) 2018 The nanoFramework project contributors
// Portions Copyright (c) 2006-2015, ARM Limited, All Rights Reserved
// Portions Copyright (c) Microsoft Corporation.  All rights reserved.
// See LICENSE file in the project root for full license information.
//

#include <ssl.h>
#include "mbedtls.h"

int ssl_connect_internal(int sd, const char* szTargetHost, int sslContextHandle)
{
    mbedTLS_NFContext* context;

    int ret = -1;

    // Retrieve SSL struct from g_SSL_Driver
    if((sslContextHandle >= (int)ARRAYSIZE(g_SSL_Driver.m_sslContextArray)) || (sslContextHandle < 0))
    {
        goto error;
    }

    // sd should already have been created
    // Now do the SSL negotiation
    context = (mbedTLS_NFContext*)g_SSL_Driver.m_sslContextArray[sslContextHandle].SslContext;
    if (context == NULL) goto error;

    // set socket in network context
    context->server_fd->fd = sd;

    if(szTargetHost != NULL && szTargetHost[0] != 0)
    {
        if( (ret = mbedtls_ssl_set_hostname( context->ssl, szTargetHost )) != 0 )
        {
            // hostname_failed
            goto error;
        }
    }

    // setup internal SSL context and calls to transport layer send, receive and receive with timeout
    mbedtls_ssl_set_bio( context->ssl, context->server_fd, mbedtls_net_send, mbedtls_net_recv, mbedtls_net_recv_timeout );

    // perform SSL handshake
    while( ( ret = mbedtls_ssl_handshake( context->ssl ) ) != 0 )
    {
        if( ret != MBEDTLS_ERR_SSL_WANT_READ && ret != MBEDTLS_ERR_SSL_WANT_WRITE )
        {
            // SSL handshake failed
            //mbedtls_printf( " failed\n  ! mbedtls_ssl_handshake returned -0x%x\n\n", -ret );
            goto error;
        }
    }

    // store SSL context in sockets driver
    SOCKET_DRIVER.SetSocketSslData(sd, (void*)context);

error:
    return ret;
}
<|endoftext|>


<commit_before>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/memory/lib/eff_config/memory_size.C $ */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2016,2019                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* 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.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */

///
/// @file memory_size.C
/// @brief Return the effective memory size behind a target
///
// *HWP HWP Owner: Brian Silver <bsilver@us.ibm.com>
// *HWP HWP Backup: Andre Marin <aamarin@us.ibm.com>
// *HWP Team: Memory
// *HWP Level: 2
// *HWP Consumed by: HB:FSP

#include <fapi2.H>
#include <lib/mss_attribute_accessors.H>

#include <lib/shared/mss_const.H>
#include <lib/eff_config/memory_size.H>

#include <lib/utils/find.H>

namespace mss
{

///
/// @brief Return the total memory size behind an MCA
/// @param[in] i_target the MCA target
/// @param[out] o_size the size of memory in GB behind the target
/// @return FAPI2_RC_SUCCESS if ok
///
template<>
fapi2::ReturnCode eff_memory_size( const fapi2::Target<fapi2::TARGET_TYPE_MCA>& i_target, uint64_t& o_size )
{
    // Don't try to get cute and read the attributes once and loop over the array.
    // Cronus honors initToZero which would work, but HB might not and so we might get
    // crap in some of the attributes (which we shouldn't access as there's no DIMM there)
    uint32_t l_sizes = 0;
    o_size = 0;

    for (const auto& d : mss::find_targets<fapi2::TARGET_TYPE_DIMM>(i_target))
    {
        FAPI_TRY( mss::eff_dimm_size(d, l_sizes) );
        o_size += l_sizes;
    }

fapi_try_exit:
    return fapi2::current_err;
}

///
/// @brief Return the total memory size behind an MBIST
/// @param[in] i_target the MCBIST target
/// @param[out] o_size the size of memory in GB behind the target
/// @return FAPI2_RC_SUCCESS if ok
///
template<>
fapi2::ReturnCode eff_memory_size( const fapi2::Target<fapi2::TARGET_TYPE_MCBIST>& i_target, uint64_t& o_size )
{
    o_size = 0;

    for (const auto& p : mss::find_targets<fapi2::TARGET_TYPE_MCA>(i_target))
    {
        uint64_t l_size = 0;
        FAPI_TRY( eff_memory_size(p, l_size) );
        o_size += l_size;
    }

fapi_try_exit:
    return fapi2::current_err;
}

}
<commit_msg>Update mss_eff_config to L3<commit_after>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/memory/lib/eff_config/memory_size.C $ */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2016,2019                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* 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.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */

///
/// @file memory_size.C
/// @brief Return the effective memory size behind a target
///
// *HWP HWP Owner: Brian Silver <bsilver@us.ibm.com>
// *HWP HWP Backup: Andre Marin <aamarin@us.ibm.com>
// *HWP Team: Memory
// *HWP Level: 3
// *HWP Consumed by: HB:FSP

#include <fapi2.H>
#include <lib/mss_attribute_accessors.H>

#include <lib/shared/mss_const.H>
#include <lib/eff_config/memory_size.H>

#include <lib/utils/find.H>

namespace mss
{

///
/// @brief Return the total memory size behind an MCA
/// @param[in] i_target the MCA target
/// @param[out] o_size the size of memory in GB behind the target
/// @return FAPI2_RC_SUCCESS if ok
///
template<>
fapi2::ReturnCode eff_memory_size( const fapi2::Target<fapi2::TARGET_TYPE_MCA>& i_target, uint64_t& o_size )
{
    // Don't try to get cute and read the attributes once and loop over the array.
    // Cronus honors initToZero which would work, but HB might not and so we might get
    // crap in some of the attributes (which we shouldn't access as there's no DIMM there)
    uint32_t l_sizes = 0;
    o_size = 0;

    for (const auto& d : mss::find_targets<fapi2::TARGET_TYPE_DIMM>(i_target))
    {
        FAPI_TRY( mss::eff_dimm_size(d, l_sizes) );
        o_size += l_sizes;
    }

fapi_try_exit:
    return fapi2::current_err;
}

///
/// @brief Return the total memory size behind an MBIST
/// @param[in] i_target the MCBIST target
/// @param[out] o_size the size of memory in GB behind the target
/// @return FAPI2_RC_SUCCESS if ok
///
template<>
fapi2::ReturnCode eff_memory_size( const fapi2::Target<fapi2::TARGET_TYPE_MCBIST>& i_target, uint64_t& o_size )
{
    o_size = 0;

    for (const auto& p : mss::find_targets<fapi2::TARGET_TYPE_MCA>(i_target))
    {
        uint64_t l_size = 0;
        FAPI_TRY( eff_memory_size(p, l_size) );
        o_size += l_size;
    }

fapi_try_exit:
    return fapi2::current_err;
}

}
<|endoftext|>


<commit_before>// Copyright 2017 Global Phasing Ltd.

#include "gemmi/symmetry.hpp"
#include <stdio.h>

void print_symmetry_operations(const gemmi::GroupOps& ops) {
  printf("%zu x %zu symmetry operations:\n",
         ops.cen_ops.size(), ops.sym_ops.size());
  for (const gemmi::Op& op : ops.all_ops_sorted())
    printf("    %s\n", op.triplet().c_str());
}

void process_arg(const char* arg) {
  const gemmi::SpaceGroup* sg = gemmi::find_spacegroup_by_name(arg);
  if (sg == nullptr) {
    try {
      gemmi::GroupOps ops = gemmi::symops_from_hall(arg);
      sg = gemmi::find_spacegroup_by_ops(ops);
      if (sg == nullptr) {
        printf("Hall symbol: %s\n", arg);
        print_symmetry_operations(ops);
      }
    } catch (std::runtime_error&) {
    }
  }
  if (sg == nullptr) {
    fprintf(stderr, "Space group not found: %s\n", arg);
    return;
  }
  printf("Number: %d\n", sg->number);
  printf("CCP4 number: %d\n", sg->ccp4);
  printf("Hermann–Mauguin: %s\n", sg->hm);
  printf("extended H-M: %s\n", sg->xhm().c_str());
  printf("Hall symbol: %s\n", sg->hall);
  print_symmetry_operations(sg->operations());
  printf("\n");
}

int main(int argc, char **argv) {
  for (int i = 1; i < argc; ++i)
    process_arg(argv[i]);
  return 0;
}

// vim:sw=2:ts=2:et:path^=../include,../third_party
<commit_msg>gemmi-sg: don't sort operations<commit_after>// Copyright 2017 Global Phasing Ltd.

#include "gemmi/symmetry.hpp"
#include <stdio.h>

void print_symmetry_operations(const gemmi::GroupOps& ops) {
  printf("%zu x %zu symmetry operations:\n",
         ops.cen_ops.size(), ops.sym_ops.size());
  for (const gemmi::Op& op : ops)
    printf("    %s\n", op.triplet().c_str());
}

void process_arg(const char* arg) {
  const gemmi::SpaceGroup* sg = gemmi::find_spacegroup_by_name(arg);
  if (sg == nullptr) {
    try {
      gemmi::GroupOps ops = gemmi::symops_from_hall(arg);
      sg = gemmi::find_spacegroup_by_ops(ops);
      if (sg == nullptr) {
        printf("Hall symbol: %s\n", arg);
        print_symmetry_operations(ops);
      }
    } catch (std::runtime_error&) {
    }
  }
  if (sg == nullptr) {
    fprintf(stderr, "Space group not found: %s\n", arg);
    return;
  }
  printf("Number: %d\n", sg->number);
  printf("CCP4 number: %d\n", sg->ccp4);
  printf("Hermann–Mauguin: %s\n", sg->hm);
  printf("extended H-M: %s\n", sg->xhm().c_str());
  printf("Hall symbol: %s\n", sg->hall);
  print_symmetry_operations(sg->operations());
  printf("\n");
}

int main(int argc, char **argv) {
  for (int i = 1; i < argc; ++i)
    process_arg(argv[i]);
  return 0;
}

// vim:sw=2:ts=2:et:path^=../include,../third_party
<|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (C) 2013 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 "qmlmodelview.h"
#include "qmlobjectnode.h"
#include "qmlitemnode.h"
#include "itemlibraryinfo.h"
#include "mathutils.h"
#include "invalididexception.h"
#include <QDir>
#include <QFileInfo>
#include <QDebug>
#include <QMessageBox>
#include <QPlainTextEdit>
#include <utils/fileutils.h>
#include "nodeabstractproperty.h"
#include "variantproperty.h"
#include "rewritingexception.h"
#include "rewriterview.h"
#include "plaintexteditmodifier.h"
#include "modelmerger.h"
#include "nodemetainfo.h"

#include <utils/qtcassert.h>

namespace QmlDesigner {

QmlModelView::QmlModelView(QObject *parent)
    : AbstractView(parent)
{
}

void QmlModelView::setCurrentState(const QmlModelState &state)
{
    if (!state.isValid())
        return;

    if (!model())
        return;

    if (actualStateNode() != state.modelNode())
        setAcutalStateNode(state.modelNode());
}

QmlModelState QmlModelView::currentState() const
{
    return QmlModelState(actualStateNode());
}

QmlModelState QmlModelView::baseState() const
{
    return QmlModelState::createBaseState(this);
}

QmlModelStateGroup QmlModelView::rootStateGroup() const
{
    return QmlModelStateGroup(rootModelNode());
}

QmlObjectNode QmlModelView::createQmlObjectNode(const TypeName &typeString,
                     int majorVersion,
                     int minorVersion,
                     const PropertyListType &propertyList)
{
    return QmlObjectNode(createModelNode(typeString, majorVersion, minorVersion, propertyList));
}

QmlItemNode QmlModelView::createQmlItemNode(const TypeName &typeString,
                                int majorVersion,
                                int minorVersion,
                                const PropertyListType &propertyList)
{
    return createQmlObjectNode(typeString, majorVersion, minorVersion, propertyList).toQmlItemNode();
}

QmlItemNode QmlModelView::createQmlItemNodeFromImage(const QString &imageName, const QPointF &position, QmlItemNode parentNode)
{
    if (!parentNode.isValid())
        parentNode = rootQmlItemNode();

    if (!parentNode.isValid())
        return QmlItemNode();

    QmlItemNode newNode;
    RewriterTransaction transaction = beginRewriterTransaction();
    {
        const QString newImportUrl = QLatin1String("QtQuick");
        const QString newImportVersion = QLatin1String("1.1");
        Import newImport = Import::createLibraryImport(newImportUrl, newImportVersion);

        foreach (const Import &import, model()->imports()) {
            if (import.isLibraryImport()
                && import.url() == newImport.url()
                && import.version() == newImport.version()) {
                // reuse this import
                newImport = import;
                break;
            }
        }

        if (!model()->imports().contains(newImport))
            model()->changeImports(QList<Import>() << newImport, QList<Import>());

        QList<QPair<PropertyName, QVariant> > propertyPairList;
        propertyPairList.append(qMakePair(PropertyName("x"), QVariant( round(position.x(), 4))));
        propertyPairList.append(qMakePair(PropertyName("y"), QVariant( round(position.y(), 4))));

        QString relativeImageName = imageName;

        //use relative path
        if (QFileInfo(model()->fileUrl().toLocalFile()).exists()) {
            QDir fileDir(QFileInfo(model()->fileUrl().toLocalFile()).absolutePath());
            relativeImageName = fileDir.relativeFilePath(imageName);
        }

        propertyPairList.append(qMakePair(PropertyName("source"), QVariant(relativeImageName)));
        newNode = createQmlItemNode("QtQuick.Image", -1, -1, propertyPairList);
        parentNode.nodeAbstractProperty("data").reparentHere(newNode);

        Q_ASSERT(newNode.isValid());

        QString id;
        int i = 1;
        QString name("image");
        name.remove(QLatin1Char(' '));
        do {
            id = name + QString::number(i);
            i++;
        } while (hasId(id)); //If the name already exists count upwards

        newNode.setId(id);
        if (!currentState().isBaseState()) {
            newNode.modelNode().variantProperty("opacity") = 0;
            newNode.setVariantProperty("opacity", 1);
        }

        Q_ASSERT(newNode.isValid());
    }

    Q_ASSERT(newNode.isValid());

    return newNode;
}

QmlItemNode QmlModelView::createQmlItemNode(const ItemLibraryEntry &itemLibraryEntry, const QPointF &position, QmlItemNode parentNode)
{
    if (!parentNode.isValid())
        parentNode = rootQmlItemNode();

    Q_ASSERT(parentNode.isValid());

    QmlItemNode newNode;

    try {
        RewriterTransaction transaction = beginRewriterTransaction();

        NodeMetaInfo metaInfo = model()->metaInfo(itemLibraryEntry.typeName());

        int minorVersion = metaInfo.minorVersion();
        int majorVersion = metaInfo.majorVersion();

        if (itemLibraryEntry.typeName().contains('.')) {

            const QString newImportUrl = itemLibraryEntry.requiredImport();

            if (!itemLibraryEntry.requiredImport().isEmpty()) {
                const QString newImportVersion = QString("%1.%2").arg(QString::number(itemLibraryEntry.majorVersion()), QString::number(itemLibraryEntry.minorVersion()));

                Import newImport = Import::createLibraryImport(newImportUrl, newImportVersion);
                if (itemLibraryEntry.majorVersion() == -1 && itemLibraryEntry.minorVersion() == -1)
                    newImport = Import::createFileImport(newImportUrl, QString());
                else
                    newImport = Import::createLibraryImport(newImportUrl, newImportVersion);

                foreach (const Import &import, model()->imports()) {
                    if (import.isLibraryImport()
                            && import.url() == newImport.url()
                            && import.version() == newImport.version()) {
                        // reuse this import
                        newImport = import;
                        break;
                    }
                }

                if (!model()->hasImport(newImport, true, true))
                    model()->changeImports(QList<Import>() << newImport, QList<Import>());
            }
        }

        QList<QPair<PropertyName, QVariant> > propertyPairList;
        propertyPairList.append(qMakePair(PropertyName("x"), QVariant(round(position.x(), 4))));
        propertyPairList.append(qMakePair(PropertyName("y"), QVariant(round(position.y(), 4))));

        if (itemLibraryEntry.qml().isEmpty()) {
            foreach (const PropertyContainer &property, itemLibraryEntry.properties())
                propertyPairList.append(qMakePair(property.name(), property.value()));

            newNode = createQmlItemNode(itemLibraryEntry.typeName(), majorVersion, minorVersion, propertyPairList);
        } else {
            QScopedPointer<Model> inputModel(Model::create("QtQuick.Rectangle", 1, 0, model()));
            inputModel->setFileUrl(model()->fileUrl());
            QPlainTextEdit textEdit;

            textEdit.setPlainText(Utils::FileReader::fetchQrc(itemLibraryEntry.qml()));
            NotIndentingTextEditModifier modifier(&textEdit);

            QScopedPointer<RewriterView> rewriterView(new RewriterView(RewriterView::Amend, 0));
            rewriterView->setCheckSemanticErrors(false);
            rewriterView->setTextModifier(&modifier);
            inputModel->setRewriterView(rewriterView.data());

            if (rewriterView->errors().isEmpty() && rewriterView->rootModelNode().isValid()) {
                ModelNode rootModelNode = rewriterView->rootModelNode();
                inputModel->detachView(rewriterView.data());

                rootModelNode.variantProperty("x") = propertyPairList.first().second;
                rootModelNode.variantProperty("y") = propertyPairList.at(1).second;

                ModelMerger merger(this);
                newNode = merger.insertModel(rootModelNode);
            }
        }

        if (parentNode.hasDefaultProperty())
            parentNode.nodeAbstractProperty(parentNode.defaultProperty()).reparentHere(newNode);

        if (!newNode.isValid())
            return newNode;

        QString id;
        int i = 1;
        QString name(itemLibraryEntry.name().toLower());
        //remove forbidden characters
        name.replace(QRegExp(QLatin1String("[^a-zA-Z0-9_]")), QLatin1String("_"));
        do {
            id = name + QString::number(i);
            i++;
        } while (hasId(id)); //If the name already exists count upwards

        newNode.setId(id);

        if (!currentState().isBaseState()) {
            newNode.modelNode().variantProperty("opacity") = 0;
            newNode.setVariantProperty("opacity", 1);
        }

        Q_ASSERT(newNode.isValid());
    }
    catch (RewritingException &e) {
        QMessageBox::warning(0, "Error", e.description());
    }
    catch (InvalidIdException &e) {
        // should never happen
        QMessageBox::warning(0, tr("Invalid Id"), e.description());
    }

    Q_ASSERT(newNode.isValid());

    return newNode;
}

QmlObjectNode QmlModelView::rootQmlObjectNode() const
{
    return QmlObjectNode(rootModelNode());
}

QmlItemNode QmlModelView::rootQmlItemNode() const
{
    return rootQmlObjectNode().toQmlItemNode();
}

void QmlModelView::setSelectedQmlObjectNodes(const QList<QmlObjectNode> &selectedNodeList)
{
    setSelectedModelNodes(QmlDesigner::toModelNodeList(selectedNodeList));
}

void QmlModelView::selectQmlObjectNode(const QmlObjectNode &node)
{
     selectModelNode(node.modelNode());
}

void QmlModelView::deselectQmlObjectNode(const QmlObjectNode &node)
{
    deselectModelNode(node.modelNode());
}

QList<QmlObjectNode> QmlModelView::selectedQmlObjectNodes() const
{
    return toQmlObjectNodeList(selectedModelNodes());
}

QList<QmlItemNode> QmlModelView::selectedQmlItemNodes() const
{
    return toQmlItemNodeList(selectedModelNodes());
}

void QmlModelView::setSelectedQmlItemNodes(const QList<QmlItemNode> &selectedNodeList)
{
    return setSelectedModelNodes(QmlDesigner::toModelNodeList(selectedNodeList));
}

QmlObjectNode QmlModelView::fxObjectNodeForId(const QString &id)
{
    return QmlObjectNode(modelNodeForId(id));
}

NodeInstance QmlModelView::instanceForModelNode(const ModelNode &modelNode)
{
    return nodeInstanceView()->instanceForNode(modelNode);
}

bool QmlModelView::hasInstanceForModelNode(const ModelNode &modelNode)
{
    return nodeInstanceView() && nodeInstanceView()->hasInstanceForNode(modelNode);
}

void QmlModelView::modelAttached(Model *model)
{
    AbstractView::modelAttached(model);
}

void QmlModelView::modelAboutToBeDetached(Model *model)
{
    AbstractView::modelAboutToBeDetached(model);
}

static bool isTransformProperty(const QString &name)
{
    static QStringList transformProperties(QStringList() << "x"
                                                         << "y"
                                                         << "width"
                                                         << "height"
                                                         << "z"
                                                         << "rotation"
                                                         << "scale"
                                                         << "transformOrigin"
                                                         << "paintedWidth"
                                                         << "paintedHeight"
                                                         << "border.width");

    return transformProperties.contains(name);
}

void QmlModelView::nodeOrderChanged(const NodeListProperty &/*listProperty*/, const ModelNode &/*movedNode*/, int /*oldIndex*/)
{

}

void QmlModelView::nodeCreated(const ModelNode &/*createdNode*/) {}
void QmlModelView::nodeAboutToBeRemoved(const ModelNode &/*removedNode*/) {}
void QmlModelView::nodeRemoved(const ModelNode &/*removedNode*/, const NodeAbstractProperty &/*parentProperty*/, PropertyChangeFlags /*propertyChange*/) {}
void QmlModelView::nodeAboutToBeReparented(const ModelNode &/*node*/, const NodeAbstractProperty &/*newPropertyParent*/, const NodeAbstractProperty &/*oldPropertyParent*/, AbstractView::PropertyChangeFlags /*propertyChange*/) {}
void QmlModelView::nodeReparented(const ModelNode &/*node*/, const NodeAbstractProperty &/*newPropertyParent*/, const NodeAbstractProperty &/*oldPropertyParent*/, AbstractView::PropertyChangeFlags /*propertyChange*/) {}
void QmlModelView::nodeIdChanged(const ModelNode& /*node*/, const QString& /*newId*/, const QString& /*oldId*/) {}
void QmlModelView::propertiesAboutToBeRemoved(const QList<AbstractProperty>& /*propertyList*/) {}
void QmlModelView::propertiesRemoved(const QList<AbstractProperty>& /*propertyList*/) {}
void QmlModelView::variantPropertiesChanged(const QList<VariantProperty>& /*propertyList*/, PropertyChangeFlags /*propertyChange*/) {}
void QmlModelView::bindingPropertiesChanged(const QList<BindingProperty>& /*propertyList*/, PropertyChangeFlags /*propertyChange*/) {}
void QmlModelView::rootNodeTypeChanged(const QString &/*type*/, int, int /*minorVersion*/) {}
void QmlModelView::scriptFunctionsChanged(const ModelNode &/*node*/, const QStringList &/*scriptFunctionList*/) {}
void QmlModelView::selectedNodesChanged(const QList<ModelNode> &/*selectedNodeList*/, const QList<ModelNode> &/*lastSelectedNodeList*/) {}

void QmlModelView::instancesCompleted(const QVector<ModelNode> &/*completedNodeList*/)
{
}

void QmlModelView::instanceInformationsChange(const QMultiHash<ModelNode, InformationName> &/*informationChangeHash*/)
{

}

void QmlModelView::instancesRenderImageChanged(const QVector<ModelNode> &/*nodeList*/)
{

}

void QmlModelView::instancesPreviewImageChanged(const QVector<ModelNode> &/*nodeList*/)
{

}

void QmlModelView::instancesChildrenChanged(const QVector<ModelNode> &/*nodeList*/)
{

}

void QmlModelView::importsChanged(const QList<Import> &/*addedImports*/, const QList<Import> &/*removedImports*/)
{

}

void QmlModelView::instancesToken(const QString &/*tokenName*/, int /*tokenNumber*/, const QVector<ModelNode> &/*nodeVector*/)
{

}

void QmlModelView::nodeSourceChanged(const ModelNode &, const QString & /*newNodeSource*/)
{

}

void QmlModelView::rewriterBeginTransaction()
{

}

void QmlModelView::rewriterEndTransaction()
{

}

void QmlModelView::actualStateChanged(const ModelNode & /*node*/)
{

}

void QmlModelView::instancePropertyChange(const QList<QPair<ModelNode, PropertyName> > & /*propertyList*/)
{
}

ModelNode QmlModelView::createQmlState(const QmlDesigner::PropertyListType &propertyList)
{

    QTC_CHECK(rootModelNode().majorQtQuickVersion() < 3);

    if (rootModelNode().majorQtQuickVersion() > 1)
        return createModelNode("QtQuick.State", 2, 0, propertyList);
    else
        return createModelNode("QtQuick.State", 1, 0, propertyList);
}

} //QmlDesigner
<commit_msg>QmlDesigner: remove unused function<commit_after>/****************************************************************************
**
** Copyright (C) 2013 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 "qmlmodelview.h"
#include "qmlobjectnode.h"
#include "qmlitemnode.h"
#include "itemlibraryinfo.h"
#include "mathutils.h"
#include "invalididexception.h"
#include <QDir>
#include <QFileInfo>
#include <QDebug>
#include <QMessageBox>
#include <QPlainTextEdit>
#include <utils/fileutils.h>
#include "nodeabstractproperty.h"
#include "variantproperty.h"
#include "rewritingexception.h"
#include "rewriterview.h"
#include "plaintexteditmodifier.h"
#include "modelmerger.h"
#include "nodemetainfo.h"

#include <utils/qtcassert.h>

namespace QmlDesigner {

QmlModelView::QmlModelView(QObject *parent)
    : AbstractView(parent)
{
}

void QmlModelView::setCurrentState(const QmlModelState &state)
{
    if (!state.isValid())
        return;

    if (!model())
        return;

    if (actualStateNode() != state.modelNode())
        setAcutalStateNode(state.modelNode());
}

QmlModelState QmlModelView::currentState() const
{
    return QmlModelState(actualStateNode());
}

QmlModelState QmlModelView::baseState() const
{
    return QmlModelState::createBaseState(this);
}

QmlModelStateGroup QmlModelView::rootStateGroup() const
{
    return QmlModelStateGroup(rootModelNode());
}

QmlObjectNode QmlModelView::createQmlObjectNode(const TypeName &typeString,
                     int majorVersion,
                     int minorVersion,
                     const PropertyListType &propertyList)
{
    return QmlObjectNode(createModelNode(typeString, majorVersion, minorVersion, propertyList));
}

QmlItemNode QmlModelView::createQmlItemNode(const TypeName &typeString,
                                int majorVersion,
                                int minorVersion,
                                const PropertyListType &propertyList)
{
    return createQmlObjectNode(typeString, majorVersion, minorVersion, propertyList).toQmlItemNode();
}

QmlItemNode QmlModelView::createQmlItemNodeFromImage(const QString &imageName, const QPointF &position, QmlItemNode parentNode)
{
    if (!parentNode.isValid())
        parentNode = rootQmlItemNode();

    if (!parentNode.isValid())
        return QmlItemNode();

    QmlItemNode newNode;
    RewriterTransaction transaction = beginRewriterTransaction();
    {
        const QString newImportUrl = QLatin1String("QtQuick");
        const QString newImportVersion = QLatin1String("1.1");
        Import newImport = Import::createLibraryImport(newImportUrl, newImportVersion);

        foreach (const Import &import, model()->imports()) {
            if (import.isLibraryImport()
                && import.url() == newImport.url()
                && import.version() == newImport.version()) {
                // reuse this import
                newImport = import;
                break;
            }
        }

        if (!model()->imports().contains(newImport))
            model()->changeImports(QList<Import>() << newImport, QList<Import>());

        QList<QPair<PropertyName, QVariant> > propertyPairList;
        propertyPairList.append(qMakePair(PropertyName("x"), QVariant( round(position.x(), 4))));
        propertyPairList.append(qMakePair(PropertyName("y"), QVariant( round(position.y(), 4))));

        QString relativeImageName = imageName;

        //use relative path
        if (QFileInfo(model()->fileUrl().toLocalFile()).exists()) {
            QDir fileDir(QFileInfo(model()->fileUrl().toLocalFile()).absolutePath());
            relativeImageName = fileDir.relativeFilePath(imageName);
        }

        propertyPairList.append(qMakePair(PropertyName("source"), QVariant(relativeImageName)));
        newNode = createQmlItemNode("QtQuick.Image", -1, -1, propertyPairList);
        parentNode.nodeAbstractProperty("data").reparentHere(newNode);

        Q_ASSERT(newNode.isValid());

        QString id;
        int i = 1;
        QString name("image");
        name.remove(QLatin1Char(' '));
        do {
            id = name + QString::number(i);
            i++;
        } while (hasId(id)); //If the name already exists count upwards

        newNode.setId(id);
        if (!currentState().isBaseState()) {
            newNode.modelNode().variantProperty("opacity") = 0;
            newNode.setVariantProperty("opacity", 1);
        }

        Q_ASSERT(newNode.isValid());
    }

    Q_ASSERT(newNode.isValid());

    return newNode;
}

QmlItemNode QmlModelView::createQmlItemNode(const ItemLibraryEntry &itemLibraryEntry, const QPointF &position, QmlItemNode parentNode)
{
    if (!parentNode.isValid())
        parentNode = rootQmlItemNode();

    Q_ASSERT(parentNode.isValid());

    QmlItemNode newNode;

    try {
        RewriterTransaction transaction = beginRewriterTransaction();

        NodeMetaInfo metaInfo = model()->metaInfo(itemLibraryEntry.typeName());

        int minorVersion = metaInfo.minorVersion();
        int majorVersion = metaInfo.majorVersion();

        if (itemLibraryEntry.typeName().contains('.')) {

            const QString newImportUrl = itemLibraryEntry.requiredImport();

            if (!itemLibraryEntry.requiredImport().isEmpty()) {
                const QString newImportVersion = QString("%1.%2").arg(QString::number(itemLibraryEntry.majorVersion()), QString::number(itemLibraryEntry.minorVersion()));

                Import newImport = Import::createLibraryImport(newImportUrl, newImportVersion);
                if (itemLibraryEntry.majorVersion() == -1 && itemLibraryEntry.minorVersion() == -1)
                    newImport = Import::createFileImport(newImportUrl, QString());
                else
                    newImport = Import::createLibraryImport(newImportUrl, newImportVersion);

                foreach (const Import &import, model()->imports()) {
                    if (import.isLibraryImport()
                            && import.url() == newImport.url()
                            && import.version() == newImport.version()) {
                        // reuse this import
                        newImport = import;
                        break;
                    }
                }

                if (!model()->hasImport(newImport, true, true))
                    model()->changeImports(QList<Import>() << newImport, QList<Import>());
            }
        }

        QList<QPair<PropertyName, QVariant> > propertyPairList;
        propertyPairList.append(qMakePair(PropertyName("x"), QVariant(round(position.x(), 4))));
        propertyPairList.append(qMakePair(PropertyName("y"), QVariant(round(position.y(), 4))));

        if (itemLibraryEntry.qml().isEmpty()) {
            foreach (const PropertyContainer &property, itemLibraryEntry.properties())
                propertyPairList.append(qMakePair(property.name(), property.value()));

            newNode = createQmlItemNode(itemLibraryEntry.typeName(), majorVersion, minorVersion, propertyPairList);
        } else {
            QScopedPointer<Model> inputModel(Model::create("QtQuick.Rectangle", 1, 0, model()));
            inputModel->setFileUrl(model()->fileUrl());
            QPlainTextEdit textEdit;

            textEdit.setPlainText(Utils::FileReader::fetchQrc(itemLibraryEntry.qml()));
            NotIndentingTextEditModifier modifier(&textEdit);

            QScopedPointer<RewriterView> rewriterView(new RewriterView(RewriterView::Amend, 0));
            rewriterView->setCheckSemanticErrors(false);
            rewriterView->setTextModifier(&modifier);
            inputModel->setRewriterView(rewriterView.data());

            if (rewriterView->errors().isEmpty() && rewriterView->rootModelNode().isValid()) {
                ModelNode rootModelNode = rewriterView->rootModelNode();
                inputModel->detachView(rewriterView.data());

                rootModelNode.variantProperty("x") = propertyPairList.first().second;
                rootModelNode.variantProperty("y") = propertyPairList.at(1).second;

                ModelMerger merger(this);
                newNode = merger.insertModel(rootModelNode);
            }
        }

        if (parentNode.hasDefaultProperty())
            parentNode.nodeAbstractProperty(parentNode.defaultProperty()).reparentHere(newNode);

        if (!newNode.isValid())
            return newNode;

        QString id;
        int i = 1;
        QString name(itemLibraryEntry.name().toLower());
        //remove forbidden characters
        name.replace(QRegExp(QLatin1String("[^a-zA-Z0-9_]")), QLatin1String("_"));
        do {
            id = name + QString::number(i);
            i++;
        } while (hasId(id)); //If the name already exists count upwards

        newNode.setId(id);

        if (!currentState().isBaseState()) {
            newNode.modelNode().variantProperty("opacity") = 0;
            newNode.setVariantProperty("opacity", 1);
        }

        Q_ASSERT(newNode.isValid());
    }
    catch (RewritingException &e) {
        QMessageBox::warning(0, "Error", e.description());
    }
    catch (InvalidIdException &e) {
        // should never happen
        QMessageBox::warning(0, tr("Invalid Id"), e.description());
    }

    Q_ASSERT(newNode.isValid());

    return newNode;
}

QmlObjectNode QmlModelView::rootQmlObjectNode() const
{
    return QmlObjectNode(rootModelNode());
}

QmlItemNode QmlModelView::rootQmlItemNode() const
{
    return rootQmlObjectNode().toQmlItemNode();
}

void QmlModelView::setSelectedQmlObjectNodes(const QList<QmlObjectNode> &selectedNodeList)
{
    setSelectedModelNodes(QmlDesigner::toModelNodeList(selectedNodeList));
}

void QmlModelView::selectQmlObjectNode(const QmlObjectNode &node)
{
     selectModelNode(node.modelNode());
}

void QmlModelView::deselectQmlObjectNode(const QmlObjectNode &node)
{
    deselectModelNode(node.modelNode());
}

QList<QmlObjectNode> QmlModelView::selectedQmlObjectNodes() const
{
    return toQmlObjectNodeList(selectedModelNodes());
}

QList<QmlItemNode> QmlModelView::selectedQmlItemNodes() const
{
    return toQmlItemNodeList(selectedModelNodes());
}

void QmlModelView::setSelectedQmlItemNodes(const QList<QmlItemNode> &selectedNodeList)
{
    return setSelectedModelNodes(QmlDesigner::toModelNodeList(selectedNodeList));
}

QmlObjectNode QmlModelView::fxObjectNodeForId(const QString &id)
{
    return QmlObjectNode(modelNodeForId(id));
}

NodeInstance QmlModelView::instanceForModelNode(const ModelNode &modelNode)
{
    return nodeInstanceView()->instanceForNode(modelNode);
}

bool QmlModelView::hasInstanceForModelNode(const ModelNode &modelNode)
{
    return nodeInstanceView() && nodeInstanceView()->hasInstanceForNode(modelNode);
}

void QmlModelView::modelAttached(Model *model)
{
    AbstractView::modelAttached(model);
}

void QmlModelView::modelAboutToBeDetached(Model *model)
{
    AbstractView::modelAboutToBeDetached(model);
}

void QmlModelView::nodeOrderChanged(const NodeListProperty &/*listProperty*/, const ModelNode &/*movedNode*/, int /*oldIndex*/)
{

}

void QmlModelView::nodeCreated(const ModelNode &/*createdNode*/) {}
void QmlModelView::nodeAboutToBeRemoved(const ModelNode &/*removedNode*/) {}
void QmlModelView::nodeRemoved(const ModelNode &/*removedNode*/, const NodeAbstractProperty &/*parentProperty*/, PropertyChangeFlags /*propertyChange*/) {}
void QmlModelView::nodeAboutToBeReparented(const ModelNode &/*node*/, const NodeAbstractProperty &/*newPropertyParent*/, const NodeAbstractProperty &/*oldPropertyParent*/, AbstractView::PropertyChangeFlags /*propertyChange*/) {}
void QmlModelView::nodeReparented(const ModelNode &/*node*/, const NodeAbstractProperty &/*newPropertyParent*/, const NodeAbstractProperty &/*oldPropertyParent*/, AbstractView::PropertyChangeFlags /*propertyChange*/) {}
void QmlModelView::nodeIdChanged(const ModelNode& /*node*/, const QString& /*newId*/, const QString& /*oldId*/) {}
void QmlModelView::propertiesAboutToBeRemoved(const QList<AbstractProperty>& /*propertyList*/) {}
void QmlModelView::propertiesRemoved(const QList<AbstractProperty>& /*propertyList*/) {}
void QmlModelView::variantPropertiesChanged(const QList<VariantProperty>& /*propertyList*/, PropertyChangeFlags /*propertyChange*/) {}
void QmlModelView::bindingPropertiesChanged(const QList<BindingProperty>& /*propertyList*/, PropertyChangeFlags /*propertyChange*/) {}
void QmlModelView::rootNodeTypeChanged(const QString &/*type*/, int, int /*minorVersion*/) {}
void QmlModelView::scriptFunctionsChanged(const ModelNode &/*node*/, const QStringList &/*scriptFunctionList*/) {}
void QmlModelView::selectedNodesChanged(const QList<ModelNode> &/*selectedNodeList*/, const QList<ModelNode> &/*lastSelectedNodeList*/) {}

void QmlModelView::instancesCompleted(const QVector<ModelNode> &/*completedNodeList*/)
{
}

void QmlModelView::instanceInformationsChange(const QMultiHash<ModelNode, InformationName> &/*informationChangeHash*/)
{

}

void QmlModelView::instancesRenderImageChanged(const QVector<ModelNode> &/*nodeList*/)
{

}

void QmlModelView::instancesPreviewImageChanged(const QVector<ModelNode> &/*nodeList*/)
{

}

void QmlModelView::instancesChildrenChanged(const QVector<ModelNode> &/*nodeList*/)
{

}

void QmlModelView::importsChanged(const QList<Import> &/*addedImports*/, const QList<Import> &/*removedImports*/)
{

}

void QmlModelView::instancesToken(const QString &/*tokenName*/, int /*tokenNumber*/, const QVector<ModelNode> &/*nodeVector*/)
{

}

void QmlModelView::nodeSourceChanged(const ModelNode &, const QString & /*newNodeSource*/)
{

}

void QmlModelView::rewriterBeginTransaction()
{

}

void QmlModelView::rewriterEndTransaction()
{

}

void QmlModelView::actualStateChanged(const ModelNode & /*node*/)
{

}

void QmlModelView::instancePropertyChange(const QList<QPair<ModelNode, PropertyName> > & /*propertyList*/)
{
}

ModelNode QmlModelView::createQmlState(const QmlDesigner::PropertyListType &propertyList)
{

    QTC_CHECK(rootModelNode().majorQtQuickVersion() < 3);

    if (rootModelNode().majorQtQuickVersion() > 1)
        return createModelNode("QtQuick.State", 2, 0, propertyList);
    else
        return createModelNode("QtQuick.State", 1, 0, propertyList);
}

} //QmlDesigner
<|endoftext|>


<commit_before>/*

Copyright 2015-2020 Igor Petrovic

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

*/

#include "Nextion.h"
#include <stdarg.h>
#include <stdio.h>
#include <string.h>

bool Nextion::init()
{
    rxBuffer.reset();
    return hwa.init();
}

bool Nextion::setScreen(size_t screenID)
{
    return writeCommand("page %u", screenID);
}

bool Nextion::update(size_t& buttonID, bool& state)
{
    uint8_t data;

    if (hwa.read(data))
        rxBuffer.insert(data);
    else
        return false;

    if (data == 0xFF)
    {
        endCounter++;
    }
    else
    {
        if (endCounter)
            endCounter = 0;
    }

    if (endCounter == 3)
    {
        //new message received
        endCounter = 0;

        //handle only button messages for now
        bool messageStart = true;

        while (rxBuffer.count())
        {
            rxBuffer.remove(data);

            if ((data == 0x65) && messageStart)
            {
                if (rxBuffer.count() >= 5)
                {
                    //state
                    //1 - pressed, 0 - released
                    rxBuffer.remove(data);

                    state = data ? 1 : 0;

                    //button id
                    rxBuffer.remove(data);
                    buttonID = data;

                    rxBuffer.reset();
                    return true;
                }
            }
            else
            {
                rxBuffer.reset();
            }

            messageStart = false;
        }
    }

    return false;
}

void Nextion::setIconState(IO::Touchscreen::icon_t& icon, bool state)
{
    writeCommand("picq %u,%u,%u,%u,%u", icon.xPos, icon.yPos, icon.width, icon.height, state ? 1 : 0);
}

bool Nextion::writeCommand(const char* line, ...)
{
    va_list args;
    va_start(args, line);

    size_t retVal = vsnprintf(commandBuffer, bufferSize, line, args);

    va_end(args);

    if (retVal < 0)
        return false;

    for (size_t i = 0; i < strlen(commandBuffer); i++)
    {
        if (!hwa.write(commandBuffer[i]))
            return false;
    }

    return endCommand();
}

bool Nextion::endCommand()
{
    for (int i = 0; i < 3; i++)
    {
        if (!hwa.write(0xFF))
            return false;
    }

    return true;
}<commit_msg>touchscreen: don't hardcode on/off screens when setting icon state<commit_after>/*

Copyright 2015-2020 Igor Petrovic

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

*/

#include "Nextion.h"
#include <stdarg.h>
#include <stdio.h>
#include <string.h>

bool Nextion::init()
{
    rxBuffer.reset();
    return hwa.init();
}

bool Nextion::setScreen(size_t screenID)
{
    return writeCommand("page %u", screenID);
}

bool Nextion::update(size_t& buttonID, bool& state)
{
    uint8_t data;

    if (hwa.read(data))
        rxBuffer.insert(data);
    else
        return false;

    if (data == 0xFF)
    {
        endCounter++;
    }
    else
    {
        if (endCounter)
            endCounter = 0;
    }

    if (endCounter == 3)
    {
        //new message received
        endCounter = 0;

        //handle only button messages for now
        bool messageStart = true;

        while (rxBuffer.count())
        {
            rxBuffer.remove(data);

            if ((data == 0x65) && messageStart)
            {
                if (rxBuffer.count() >= 5)
                {
                    //state
                    //1 - pressed, 0 - released
                    rxBuffer.remove(data);

                    state = data ? 1 : 0;

                    //button id
                    rxBuffer.remove(data);
                    buttonID = data;

                    rxBuffer.reset();
                    return true;
                }
            }
            else
            {
                rxBuffer.reset();
            }

            messageStart = false;
        }
    }

    return false;
}

void Nextion::setIconState(IO::Touchscreen::icon_t& icon, bool state)
{
    writeCommand("picq %u,%u,%u,%u,%u", icon.xPos, icon.yPos, icon.width, icon.height, state ? icon.onScreen : icon.offScreen);
}

bool Nextion::writeCommand(const char* line, ...)
{
    va_list args;
    va_start(args, line);

    size_t retVal = vsnprintf(commandBuffer, bufferSize, line, args);

    va_end(args);

    if (retVal < 0)
        return false;

    for (size_t i = 0; i < strlen(commandBuffer); i++)
    {
        if (!hwa.write(commandBuffer[i]))
            return false;
    }

    return endCommand();
}

bool Nextion::endCommand()
{
    for (int i = 0; i < 3; i++)
    {
        if (!hwa.write(0xFF))
            return false;
    }

    return true;
}<|endoftext|>


<commit_before>#include <QSettings>
#include <QThread>
#include "canconnection.h"

CANConnection::CANConnection(QString pPort,
                             QString pDriver,
                             CANCon::type pType,
                             int pNumBuses,
                             int pQueueLen,
                             bool pUseThread) :
    mNumBuses(pNumBuses),
    mQueue(),
    mPort(pPort),
    mDriver(pDriver),
    mType(pType),
    mIsCapSuspended(false),
    mStatus(CANCon::NOT_CONNECTED),
    mStarted(false),
    mThread_p(nullptr)
{
    /* register types */
    qRegisterMetaType<CANBus>("CANBus");
    qRegisterMetaType<CANFrame>("CANFrame");
    qRegisterMetaType<CANConStatus>("CANConStatus");
    qRegisterMetaType<CANFltObserver>("CANFlt");

    /* set queue size */
    mQueue.setSize(pQueueLen); /*TODO add check on returned value */

    /* allocate buses */
    /* TODO: change those tables for a vector */
    mBusData.resize(mNumBuses);
    for(int i=0 ; i<mNumBuses ; i++) {
        mBusData[i].mConfigured  = false;
    }

    /* if needed, create a thread and move ourself into it */
    if(pUseThread) {
        mThread_p = new QThread();
    }
}

CANConnection::~CANConnection()
{
    /* stop and delete thread */
    if(mThread_p) {
        mThread_p->quit();
        mThread_p->wait();
        delete mThread_p;
        mThread_p = nullptr;
    }

    mBusData.clear();
}

void CANConnection::start()
{
    if( mThread_p && (mThread_p != QThread::currentThread()) )
    {
        /* move ourself to the thread */
        moveToThread(mThread_p); /*TODO handle errors */
        /* connect started() */
        connect(mThread_p, SIGNAL(started()), this, SLOT(start()));
        /* start the thread */
        mThread_p->start(QThread::HighPriority);
        return;
    }

    /* set started flag */
    mStarted = true;

    QSettings settings;

    if (settings.value("Main/TimeClock", false).toBool())
    {
        useSystemTime = true;
    }
    else useSystemTime = false;

    /* in multithread case, this will be called before entering thread event loop */
    return piStarted();
}

void CANConnection::suspend(bool pSuspend)
{
    /* execute in mThread_p context */
    if( mThread_p && (mThread_p != QThread::currentThread()) ) {
        QMetaObject::invokeMethod(this, "suspend",
                                  Qt::BlockingQueuedConnection,
                                  Q_ARG(bool, pSuspend));
        return;
    }

    return piSuspend(pSuspend);
}

void CANConnection::stop()
{
    /* 1) execute in mThread_p context */
    if( mThread_p && mStarted && (mThread_p != QThread::currentThread()) )
    {
        /* if thread is finished, it means we call this function for the second time so we can leave */
        if( !mThread_p->isFinished() )
        {
            /* we need to call piStop() */
            QMetaObject::invokeMethod(this, "stop",
                                      Qt::BlockingQueuedConnection);
            /* 3) stop thread */
            mThread_p->quit();
            if(!mThread_p->wait()) {
                qDebug() << "can't stop thread";
            }
        }
        return;
    }

    /* 2) call piStop in mThread context */
    return piStop();
}

bool CANConnection::getBusSettings(int pBusIdx, CANBus& pBus)
{
    /* make sure we execute in mThread context */
    if( mThread_p && (mThread_p != QThread::currentThread()) ) {
        bool ret;
        QMetaObject::invokeMethod(this, "getBusSettings",
                                  Qt::BlockingQueuedConnection,
                                  Q_RETURN_ARG(bool, ret),
                                  Q_ARG(int , pBusIdx),
                                  Q_ARG(CANBus& , pBus));
        return ret;
    }

    return piGetBusSettings(pBusIdx, pBus);
}

void CANConnection::setBusSettings(int pBusIdx, CANBus pBus)
{
    /* make sure we execute in mThread context */
    if( mThread_p && (mThread_p != QThread::currentThread()) ) {
        QMetaObject::invokeMethod(this, "setBusSettings",
                                  Qt::BlockingQueuedConnection,
                                  Q_ARG(int, pBusIdx),
                                  Q_ARG(CANBus, pBus));
        return;
    }

    return piSetBusSettings(pBusIdx, pBus);
}

bool CANConnection::sendFrame(const CANFrame& pFrame)
{
    /* make sure we execute in mThread context */
    if( mThread_p && (mThread_p != QThread::currentThread()) )
    {
        bool ret;
        QMetaObject::invokeMethod(this, "sendFrame",
                                  Qt::BlockingQueuedConnection,
                                  Q_RETURN_ARG(bool, ret),
                                  Q_ARG(const CANFrame&, pFrame));
        return ret;
    }

    return piSendFrame(pFrame);
}

bool CANConnection::sendFrames(const QList<CANFrame>& pFrames)
{
    /* make sure we execute in mThread context */
    if( mThread_p && (mThread_p != QThread::currentThread()) )
    {
        bool ret;
        QMetaObject::invokeMethod(this, "sendFrames",
                                  Qt::BlockingQueuedConnection,
                                  Q_RETURN_ARG(bool, ret),
                                  Q_ARG(const QList<CANFrame>&, pFrames));
        return ret;
    }

    return piSendFrames(pFrames);
}

int CANConnection::getNumBuses() const{
    return mNumBuses;
}

bool CANConnection::isConfigured(int pBusId) {
    if( pBusId < 0 || pBusId >= getNumBuses())
        return false;
    return mBusData[pBusId].mConfigured;
}

void CANConnection::setConfigured(int pBusId, bool pConfigured) {
    if( pBusId < 0 || pBusId >= getNumBuses())
        return;
    mBusData[pBusId].mConfigured = pConfigured;
}

bool CANConnection::getBusConfig(int pBusId, CANBus& pBus) {
    if( pBusId < 0 || pBusId >= getNumBuses() || !isConfigured(pBusId))
        return false;
    qDebug() << "getBusConfig id: " << pBusId;
    pBus = mBusData[pBusId].mBus;
    return true;
}

void CANConnection::setBusConfig(int pBusId, CANBus& pBus) {
    if( pBusId < 0 || pBusId >= getNumBuses())
        return;

    mBusData[pBusId].mConfigured = true;
    mBusData[pBusId].mBus = pBus;
}

QString CANConnection::getPort() {
    return mPort;
}

QString CANConnection::getDriver()
{
    return mDriver;
}

LFQueue<CANFrame>& CANConnection::getQueue() {
    return mQueue;
}

CANCon::type CANConnection::getType() {
    return mType;
}

CANCon::status CANConnection::getStatus() {
    return (CANCon::status) mStatus.load();
}

void CANConnection::setStatus(CANCon::status pStatus) {
    mStatus.store(pStatus);
}

bool CANConnection::isCapSuspended() {
    return mIsCapSuspended;
}

void CANConnection::setCapSuspended(bool pIsSuspended) {
    mIsCapSuspended = pIsSuspended;
}

void CANConnection::debugInput(QByteArray bytes) {
    Q_UNUSED(bytes)
}

bool CANConnection::addTargettedFrame(int pBusId, uint32_t ID, uint32_t mask, QObject *receiver)
{
/*
    if( mThread_p && (mThread_p != QThread::currentThread()) ) {
        bool ret;
        QMetaObject::invokeMethod(this, "addTargettedFrame",
                                  Qt::BlockingQueuedConnection,
                                  Q_RETURN_ARG(bool, ret),
                                  Q_ARG(int, pBusId),
                                  Q_ARG(uint32_t , ID),
                                  Q_ARG(uint32_t , mask),
                                  Q_ARG(QObject *, receiver));
        return ret;
    }
*/
    /* sanity checks */
    if(pBusId < -1 || pBusId >=  getNumBuses())
        return false;

    qDebug() << "Connection is registering a new targetted frame filter, local bus " << pBusId;
    CANFltObserver target;
    target.id = ID;
    target.mask = mask;
    target.observer = receiver;
    mBusData[pBusId].mTargettedFrames.append(target);

    return true;
}

bool CANConnection::removeTargettedFrame(int pBusId, uint32_t ID, uint32_t mask, QObject *receiver)
{
/*
    if( mThread_p && (mThread_p != QThread::currentThread()) ) {
        bool ret;
        QMetaObject::invokeMethod(this, "removeTargettedFrame",
                                  Qt::BlockingQueuedConnection,
                                  Q_RETURN_ARG(bool, ret),
                                  Q_ARG(int, pBusId),
                                  Q_ARG(uint32_t , ID),
                                  Q_ARG(uint32_t , mask),
                                  Q_ARG(QObject *, receiver));
        return ret;
    }
*/
    /* sanity checks */
    if(pBusId < -1 || pBusId >= getNumBuses())
        return false;

    CANFltObserver target;
    target.id = ID;
    target.mask = mask;
    target.observer = receiver;
    mBusData[pBusId].mTargettedFrames.removeAll(target);

    return true;
}

bool CANConnection::removeAllTargettedFrames(QObject *receiver)
{
    for (int i = 0; i < getNumBuses(); i++) {
        foreach (const CANFltObserver filt, mBusData[i].mTargettedFrames)
        {
            if (filt.observer == receiver) mBusData[i].mTargettedFrames.removeOne(filt);
        }
    }

    return true;
}

void CANConnection::checkTargettedFrame(CANFrame &frame)
{
    unsigned int maskedID;
    //qDebug() << "Got frame with ID " << frame.ID << " on bus " << frame.bus;
    if (mBusData.count() == 0) return;

    int bus = frame.bus;
    if (bus > (mBusData.length() - 1)) bus = mBusData.length() - 1;

    if (mBusData[bus].mTargettedFrames.length() == 0) return;
    foreach (const CANFltObserver filt, mBusData[frame.bus].mTargettedFrames)
    {
        //qDebug() << "Checking filter with id " << filt.id << " mask " << filt.mask;
        maskedID = frame.frameId() & filt.mask;
        if (maskedID == filt.id) {
            qDebug() << "In connection object I got a targetted frame. Forwarding it.";
            QMetaObject::invokeMethod(filt.observer, "gotTargettedFrame",Qt::QueuedConnection, Q_ARG(CANFrame, frame));
        }
    }
}

bool CANConnection::piSendFrames(const QList<CANFrame>& pFrames)
{
    foreach(const CANFrame& frame, pFrames)
    {
        if(!piSendFrame(frame))
            return false;
    }

    return true;
}
<commit_msg>replace QAtomicInt load()/store() with loadRelaxed()/storeRelaxed()<commit_after>#include <QSettings>
#include <QThread>
#include "canconnection.h"

CANConnection::CANConnection(QString pPort,
                             QString pDriver,
                             CANCon::type pType,
                             int pNumBuses,
                             int pQueueLen,
                             bool pUseThread) :
    mNumBuses(pNumBuses),
    mQueue(),
    mPort(pPort),
    mDriver(pDriver),
    mType(pType),
    mIsCapSuspended(false),
    mStatus(CANCon::NOT_CONNECTED),
    mStarted(false),
    mThread_p(nullptr)
{
    /* register types */
    qRegisterMetaType<CANBus>("CANBus");
    qRegisterMetaType<CANFrame>("CANFrame");
    qRegisterMetaType<CANConStatus>("CANConStatus");
    qRegisterMetaType<CANFltObserver>("CANFlt");

    /* set queue size */
    mQueue.setSize(pQueueLen); /*TODO add check on returned value */

    /* allocate buses */
    /* TODO: change those tables for a vector */
    mBusData.resize(mNumBuses);
    for(int i=0 ; i<mNumBuses ; i++) {
        mBusData[i].mConfigured  = false;
    }

    /* if needed, create a thread and move ourself into it */
    if(pUseThread) {
        mThread_p = new QThread();
    }
}

CANConnection::~CANConnection()
{
    /* stop and delete thread */
    if(mThread_p) {
        mThread_p->quit();
        mThread_p->wait();
        delete mThread_p;
        mThread_p = nullptr;
    }

    mBusData.clear();
}

void CANConnection::start()
{
    if( mThread_p && (mThread_p != QThread::currentThread()) )
    {
        /* move ourself to the thread */
        moveToThread(mThread_p); /*TODO handle errors */
        /* connect started() */
        connect(mThread_p, SIGNAL(started()), this, SLOT(start()));
        /* start the thread */
        mThread_p->start(QThread::HighPriority);
        return;
    }

    /* set started flag */
    mStarted = true;

    QSettings settings;

    if (settings.value("Main/TimeClock", false).toBool())
    {
        useSystemTime = true;
    }
    else useSystemTime = false;

    /* in multithread case, this will be called before entering thread event loop */
    return piStarted();
}

void CANConnection::suspend(bool pSuspend)
{
    /* execute in mThread_p context */
    if( mThread_p && (mThread_p != QThread::currentThread()) ) {
        QMetaObject::invokeMethod(this, "suspend",
                                  Qt::BlockingQueuedConnection,
                                  Q_ARG(bool, pSuspend));
        return;
    }

    return piSuspend(pSuspend);
}

void CANConnection::stop()
{
    /* 1) execute in mThread_p context */
    if( mThread_p && mStarted && (mThread_p != QThread::currentThread()) )
    {
        /* if thread is finished, it means we call this function for the second time so we can leave */
        if( !mThread_p->isFinished() )
        {
            /* we need to call piStop() */
            QMetaObject::invokeMethod(this, "stop",
                                      Qt::BlockingQueuedConnection);
            /* 3) stop thread */
            mThread_p->quit();
            if(!mThread_p->wait()) {
                qDebug() << "can't stop thread";
            }
        }
        return;
    }

    /* 2) call piStop in mThread context */
    return piStop();
}

bool CANConnection::getBusSettings(int pBusIdx, CANBus& pBus)
{
    /* make sure we execute in mThread context */
    if( mThread_p && (mThread_p != QThread::currentThread()) ) {
        bool ret;
        QMetaObject::invokeMethod(this, "getBusSettings",
                                  Qt::BlockingQueuedConnection,
                                  Q_RETURN_ARG(bool, ret),
                                  Q_ARG(int , pBusIdx),
                                  Q_ARG(CANBus& , pBus));
        return ret;
    }

    return piGetBusSettings(pBusIdx, pBus);
}

void CANConnection::setBusSettings(int pBusIdx, CANBus pBus)
{
    /* make sure we execute in mThread context */
    if( mThread_p && (mThread_p != QThread::currentThread()) ) {
        QMetaObject::invokeMethod(this, "setBusSettings",
                                  Qt::BlockingQueuedConnection,
                                  Q_ARG(int, pBusIdx),
                                  Q_ARG(CANBus, pBus));
        return;
    }

    return piSetBusSettings(pBusIdx, pBus);
}

bool CANConnection::sendFrame(const CANFrame& pFrame)
{
    /* make sure we execute in mThread context */
    if( mThread_p && (mThread_p != QThread::currentThread()) )
    {
        bool ret;
        QMetaObject::invokeMethod(this, "sendFrame",
                                  Qt::BlockingQueuedConnection,
                                  Q_RETURN_ARG(bool, ret),
                                  Q_ARG(const CANFrame&, pFrame));
        return ret;
    }

    return piSendFrame(pFrame);
}

bool CANConnection::sendFrames(const QList<CANFrame>& pFrames)
{
    /* make sure we execute in mThread context */
    if( mThread_p && (mThread_p != QThread::currentThread()) )
    {
        bool ret;
        QMetaObject::invokeMethod(this, "sendFrames",
                                  Qt::BlockingQueuedConnection,
                                  Q_RETURN_ARG(bool, ret),
                                  Q_ARG(const QList<CANFrame>&, pFrames));
        return ret;
    }

    return piSendFrames(pFrames);
}

int CANConnection::getNumBuses() const{
    return mNumBuses;
}

bool CANConnection::isConfigured(int pBusId) {
    if( pBusId < 0 || pBusId >= getNumBuses())
        return false;
    return mBusData[pBusId].mConfigured;
}

void CANConnection::setConfigured(int pBusId, bool pConfigured) {
    if( pBusId < 0 || pBusId >= getNumBuses())
        return;
    mBusData[pBusId].mConfigured = pConfigured;
}

bool CANConnection::getBusConfig(int pBusId, CANBus& pBus) {
    if( pBusId < 0 || pBusId >= getNumBuses() || !isConfigured(pBusId))
        return false;
    qDebug() << "getBusConfig id: " << pBusId;
    pBus = mBusData[pBusId].mBus;
    return true;
}

void CANConnection::setBusConfig(int pBusId, CANBus& pBus) {
    if( pBusId < 0 || pBusId >= getNumBuses())
        return;

    mBusData[pBusId].mConfigured = true;
    mBusData[pBusId].mBus = pBus;
}

QString CANConnection::getPort() {
    return mPort;
}

QString CANConnection::getDriver()
{
    return mDriver;
}

LFQueue<CANFrame>& CANConnection::getQueue() {
    return mQueue;
}

CANCon::type CANConnection::getType() {
    return mType;
}

CANCon::status CANConnection::getStatus() {
    return (CANCon::status) mStatus.loadRelaxed();
}

void CANConnection::setStatus(CANCon::status pStatus) {
    mStatus.storeRelaxed(pStatus);
}

bool CANConnection::isCapSuspended() {
    return mIsCapSuspended;
}

void CANConnection::setCapSuspended(bool pIsSuspended) {
    mIsCapSuspended = pIsSuspended;
}

void CANConnection::debugInput(QByteArray bytes) {
    Q_UNUSED(bytes)
}

bool CANConnection::addTargettedFrame(int pBusId, uint32_t ID, uint32_t mask, QObject *receiver)
{
/*
    if( mThread_p && (mThread_p != QThread::currentThread()) ) {
        bool ret;
        QMetaObject::invokeMethod(this, "addTargettedFrame",
                                  Qt::BlockingQueuedConnection,
                                  Q_RETURN_ARG(bool, ret),
                                  Q_ARG(int, pBusId),
                                  Q_ARG(uint32_t , ID),
                                  Q_ARG(uint32_t , mask),
                                  Q_ARG(QObject *, receiver));
        return ret;
    }
*/
    /* sanity checks */
    if(pBusId < -1 || pBusId >=  getNumBuses())
        return false;

    qDebug() << "Connection is registering a new targetted frame filter, local bus " << pBusId;
    CANFltObserver target;
    target.id = ID;
    target.mask = mask;
    target.observer = receiver;
    mBusData[pBusId].mTargettedFrames.append(target);

    return true;
}

bool CANConnection::removeTargettedFrame(int pBusId, uint32_t ID, uint32_t mask, QObject *receiver)
{
/*
    if( mThread_p && (mThread_p != QThread::currentThread()) ) {
        bool ret;
        QMetaObject::invokeMethod(this, "removeTargettedFrame",
                                  Qt::BlockingQueuedConnection,
                                  Q_RETURN_ARG(bool, ret),
                                  Q_ARG(int, pBusId),
                                  Q_ARG(uint32_t , ID),
                                  Q_ARG(uint32_t , mask),
                                  Q_ARG(QObject *, receiver));
        return ret;
    }
*/
    /* sanity checks */
    if(pBusId < -1 || pBusId >= getNumBuses())
        return false;

    CANFltObserver target;
    target.id = ID;
    target.mask = mask;
    target.observer = receiver;
    mBusData[pBusId].mTargettedFrames.removeAll(target);

    return true;
}

bool CANConnection::removeAllTargettedFrames(QObject *receiver)
{
    for (int i = 0; i < getNumBuses(); i++) {
        foreach (const CANFltObserver filt, mBusData[i].mTargettedFrames)
        {
            if (filt.observer == receiver) mBusData[i].mTargettedFrames.removeOne(filt);
        }
    }

    return true;
}

void CANConnection::checkTargettedFrame(CANFrame &frame)
{
    unsigned int maskedID;
    //qDebug() << "Got frame with ID " << frame.ID << " on bus " << frame.bus;
    if (mBusData.count() == 0) return;

    int bus = frame.bus;
    if (bus > (mBusData.length() - 1)) bus = mBusData.length() - 1;

    if (mBusData[bus].mTargettedFrames.length() == 0) return;
    foreach (const CANFltObserver filt, mBusData[frame.bus].mTargettedFrames)
    {
        //qDebug() << "Checking filter with id " << filt.id << " mask " << filt.mask;
        maskedID = frame.frameId() & filt.mask;
        if (maskedID == filt.id) {
            qDebug() << "In connection object I got a targetted frame. Forwarding it.";
            QMetaObject::invokeMethod(filt.observer, "gotTargettedFrame",Qt::QueuedConnection, Q_ARG(CANFrame, frame));
        }
    }
}

bool CANConnection::piSendFrames(const QList<CANFrame>& pFrames)
{
    foreach(const CANFrame& frame, pFrames)
    {
        if(!piSendFrame(frame))
            return false;
    }

    return true;
}
<|endoftext|>