<commit_before>#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <signal.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <dirent.h>
#include <fcntl.h>
#include <errno.h>
#include <string>
#include <functional>
#include <unordered_map>
#include <list>
#include <algorithm>
#include <iostream>
#include <sstream>
#include <map>

#if defined(__APPLE__) || defined(__GNUC__) && __GNUC__ * 10  + __GNUC_MINOR__ >= 49
#include <regex>
#endif

#include <assert.h>
#include <vector>
#include <fstream>
#include <future>

#define BUF_SIZE 4096
#define MAX_LISTEN 128

namespace Cappuccino{

	namespace Log{

		static int LogLevel = 0;
		static void debug(std::string msg){
			if(LogLevel >= 1){
				std::cout << msg << std::endl;
			}
		}

		static void info(std::string msg){
			if(LogLevel >= 2){
				std::cout << msg << std::endl;
			}
		}
	};

	class Request;
	class Response;

	struct {
		int port = 1204;
		int sockfd = 0;
		int sessionfd = 0;
	    fd_set mask1fds, mask2fds;

		std::shared_ptr<std::string> view_root;
		std::shared_ptr<std::string> static_root;

		std::unordered_map<std::string,
			std::function<Response(std::shared_ptr<Request>)>
		> routes;

	} context;

	namespace signal_utils{

		void signal_handler(int signal){
			close(context.sessionfd);
			close(context.sockfd);
			exit(0);
		}

		void signal_handler_child(int SignalName){
			while(waitpid(-1,NULL,WNOHANG)>0){}
	        signal(SIGCHLD, signal_utils::signal_handler_child);
		}

		void init_signal(){
			if(signal(SIGINT, signal_utils::signal_handler) == SIG_ERR){
				exit(1);
			}
			if(signal(SIGCHLD, signal_utils::signal_handler_child) == SIG_ERR){
				exit(1);
			}
		}
	}

	namespace utils{
		std::vector<std::string> split(const std::string& str, std::string delim) noexcept{
			std::vector<std::string> result;
		    std::string::size_type pos = 0;
		    while(pos != std::string::npos ){
		        std::string::size_type p = str.find(delim, pos);
		        if(p == std::string::npos){
		            result.push_back(str.substr(pos));
		            break;
		        }else{
		            result.push_back(str.substr(pos, p - pos));
		        }
		        pos = p + delim.size();
		    }
		    return result;
		}
	};

	void init_socket(){
	    struct sockaddr_in server;
		if((context.sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0){
			exit(EXIT_FAILURE);
		}
		memset( &server, 0, sizeof(server));
		server.sin_family = AF_INET;
		server.sin_addr.s_addr = INADDR_ANY;
		server.sin_port = htons(context.port);

		char opt = 1;
		setsockopt(context.sockfd, SOL_SOCKET, SO_REUSEADDR, (char *)&opt, sizeof(char));

		int temp = 1;
  		if(setsockopt(context.sockfd, SOL_SOCKET, SO_REUSEADDR,
	        &temp, sizeof(int))){
		}

		if (bind(context.sockfd, (struct sockaddr *) &server, sizeof(server)) < 0) {
			exit(EXIT_FAILURE);
		}

		if(listen(context.sockfd,  MAX_LISTEN) < 0) {
			exit(EXIT_FAILURE);
		}

	    FD_ZERO(&context.mask1fds);
	    FD_SET(context.sockfd, &context.mask1fds);
	}

	using namespace std;

	string openFile(string aFilename){
		auto filename = aFilename;
		std::ifstream ifs( filename, std::ios::in | std::ios::binary);
		if(ifs.fail()){
			throw std::runtime_error("No such file or directory \""+ filename +"\"\n");
		}
		ifs.seekg( 0, std::ios::end);
		auto pos = ifs.tellg();
		ifs.seekg( 0, std::ios::beg);

		std::vector<char> buf(pos);
		ifs.read(buf.data(), pos);
		return string(buf.begin(), buf.end());;
	}

	void option(int argc, char *argv[]) noexcept{
		char result;
		while((result = getopt(argc,argv,"dp:")) != -1){
			switch(result){
			case 'd':
				Log::LogLevel = 1;
				break;
			case 'p':
				context.port = atoi(optarg);
				break;
			}
		}
	}

	class Request{
		map<string, string> headerset;
		map<string, string> paramset;
	  public:
		Request(string method, string url,string protocol):
		method(move(method)),
		url(move(url)),
		protocol(move(protocol))
		{}

		const string method;
		const string url;
		const string protocol;

		void addHeader(string key,string value){
			headerset[key] = move(value);
		}

		void addParams(string key,string value){
			paramset[key] = move(value);
		}

		string header(string key){
			if(headerset.find(key) == headerset.end())
				return "INVALID";
			return headerset[key];
		}

		string params(string key){
			if(paramset.find(key) == paramset.end())
				return "INVALID";
			return paramset[key];
		}
	};

    class Response{
		int status_;
		string message_;
		string url_;
		string body_;
		string protocol_;
      public:

		Response(weak_ptr<Request> req){
			auto r = req.lock();
			if(r){
				url_ = r->url;
				protocol_ = r->protocol;
			}else{
				throw std::runtime_error("Request  expired!\n");
			}
		}

		Response(int st,string msg,string pro, string bod):
			status_(st),
			message_(msg),
			body_(bod),
			protocol_(pro)
		{}

		Response* message(string msg){
			message_ = msg;
			return this;
		}

		Response* status(int st){
			status_ = st;
			return this;
		}

		Response* file(string filename){
			body_ = openFile(*context.view_root + "/" + filename);
			return this;
		}

      	operator string(){
      		return protocol_ + " " + to_string(status_) +" "+ message_ + "\n\n" + body_;
      	}
    };

	string createResponse(char* req) noexcept{
		auto lines = utils::split(string(req), "\n");
		if(lines.empty())
			return Response(400, "Bad Request", "HTTP/1.1", "NN");

		auto tops = utils::split(lines[0], " ");
		if(tops.size() < 3)
			return Response(401, "Bad Request", "HTTP/1.1",  "NN");

		cout<< tops[0] << " " << tops[1] << " " <<tops[2] << endl;

		auto request = shared_ptr<Request>(new Request(tops[0],tops[1],tops[2]));

		if(context.routes.find(tops[1]) != context.routes.end()){
			return context.routes[tops[1]](move(request));
		}

		return Response( 404,"Not found", tops[2], "AA");
	}

	string receiveProcess(int sessionfd){
		char buf[BUF_SIZE] = {};

		if (recv(sessionfd, buf, sizeof(buf), 0) < 0) {
			exit(EXIT_FAILURE);
		}
		do{
			if(strstr(buf, "\r\n")){
				break;
			}
			if (strlen(buf) >= sizeof(buf)) {
				memset(&buf, 0, sizeof(buf));
			}
		}while(read(sessionfd, buf+strlen(buf), sizeof(buf) - strlen(buf)) > 0);
		return createResponse(buf);
	}

	void load(string directory, string filename) noexcept{
		if(filename == "." || filename == "..") return;
		if(filename!="")
			directory += "/" + filename;
		DIR* dir = opendir(directory.c_str());
		if(dir != NULL){
			struct dirent* dent;
	        dent = readdir(dir);
		    while(dent!=NULL){
		        dent = readdir(dir);
		        if(dent!=NULL)
			        load(directory, string(dent->d_name));
		    }
		    closedir(dir);
			delete dent;
			delete dir;
		}else{
			cout<<"add "<<directory<< endl;
			context.routes.insert( make_pair(
				"/" + directory,
				[directory,filename](std::shared_ptr<Request> request) -> Cappuccino::Response{
					return Response(200,"OK","HTTP/1.1",openFile(directory));
				}
			));
		}
	}

	void loadStaticFiles() noexcept{
		load(*context.static_root,"");
	}

	void route(string url,std::function<Response(std::shared_ptr<Request>)> F){
		context.routes.insert( make_pair( move(url), move(F) ));
	}

	void root(string r){
		context.view_root =  make_shared<string>(move(r));
	}

	void resource(string s){
		context.static_root = make_shared<string>(move(s));
	}

	void run(){

		init_socket();
		signal_utils::init_signal();
		loadStaticFiles();

	    int cd[FD_SETSIZE];
		struct sockaddr_in client;
        int    fd;
        struct timeval tv;

	    for(int i = 0;i < FD_SETSIZE; i++){
	        cd[i] = 0;
	    }

		int I = 0;
	    while(1) {

			if(I>5){
				return;
			}

	        tv.tv_sec = 0;
	        tv.tv_usec = 0;

	        memcpy(&context.mask2fds, &context.mask1fds, sizeof(context.mask1fds));

	        int select_result = select(FD_SETSIZE, &context.mask2fds, (fd_set *)0, (fd_set *)0, &tv);
	        if(select_result < 1) {
	            for(fd = 0; fd < FD_SETSIZE; fd++) {
	                if(cd[fd] == 1) {
	                    close(fd);
	                    FD_CLR(fd, &context.mask1fds);
	                    cd[fd] = 0;
	                }
	            }
	            continue;
	        }
			for(fd = 0; fd < FD_SETSIZE; fd++){
	            if(FD_ISSET(fd,&context.mask2fds)) {
	                if(fd == context.sockfd) {
	                	memset( &client, 0, sizeof(client));
						int len = sizeof(client);
	                    int clientfd = accept(context.sockfd,
	                        (struct sockaddr *)&client,(socklen_t *) &len);
	                        FD_SET(clientfd, &context.mask1fds);
	                }else {
	                    if(cd[fd] == 1) {
	                        close(fd);
	                        FD_CLR(fd, &context.mask1fds);
	                        cd[fd] = 0;
	                    } else {
							string response = receiveProcess(fd);
							write(fd, response.c_str(), response.size());
	                        cd[fd] = 1;

							I++;

	                    }
	                }
	            }
	        }
	    }
	}

	void Cappuccino(int argc, char *argv[]) {
		option(argc, argv);
		context.view_root = make_shared<string>("");
		context.static_root = make_shared<string>("public");
	}
};

namespace Cocoa{
	using namespace Cappuccino;
	using namespace std;

	// Unit Test
	void testOpenFile(){
		string res = openFile("html/index.html");
		auto lines = utils::split(res, "\n");
		assert(!lines.empty());
	}

	void testOpenInvalidFile(){
		try{
			string res = openFile("html/index");
		}catch(std::runtime_error e){
			cout<< e.what() << endl;
		}
	}
};

<commit_msg>[Imp] clean include, use unordered_map<commit_after>#include <cstdio>
#include <cstdlib>
#include <unistd.h>
#include <string>
#include <csignal>
#include <netinet/in.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <dirent.h>
#include <fcntl.h>
#include <errno.h>
#include <functional>
#include <unordered_map>
#include <algorithm>
#include <iostream>
#include <sstream>

#if defined(__APPLE__) || defined(__GNUC__) && __GNUC__ * 10  + __GNUC_MINOR__ >= 49
#include <regex>
#endif

#include <cassert>
#include <vector>
#include <fstream>
#include <future>

#define BUF_SIZE 4096
#define MAX_LISTEN 128

namespace Cappuccino{

	namespace Log{

		static int LogLevel = 0;
		static void debug(std::string msg){
			if(LogLevel >= 1){
				std::cout << msg << std::endl;
			}
		}

		static void info(std::string msg){
			if(LogLevel >= 2){
				std::cout << msg << std::endl;
			}
		}
	};

	class Request;
	class Response;

	struct {
		int port = 1204;
		int sockfd = 0;
		int sessionfd = 0;
	    fd_set mask1fds, mask2fds;

		std::shared_ptr<std::string> view_root;
		std::shared_ptr<std::string> static_root;

		std::unordered_map<std::string,
			std::function<Response(std::shared_ptr<Request>)>
		> routes;

	} context;

	namespace signal_utils{

		void signal_handler(int signal){
			close(context.sessionfd);
			close(context.sockfd);
			exit(0);
		}

		void signal_handler_child(int SignalName){
			while(waitpid(-1,NULL,WNOHANG)>0){}
	        signal(SIGCHLD, signal_utils::signal_handler_child);
		}

		void init_signal(){
			if(signal(SIGINT, signal_utils::signal_handler) == SIG_ERR){
				exit(1);
			}
			if(signal(SIGCHLD, signal_utils::signal_handler_child) == SIG_ERR){
				exit(1);
			}
		}
	}

	namespace utils{
		std::vector<std::string> split(const std::string& str, std::string delim) noexcept{
			std::vector<std::string> result;
		    std::string::size_type pos = 0;
		    while(pos != std::string::npos ){
		        std::string::size_type p = str.find(delim, pos);
		        if(p == std::string::npos){
		            result.push_back(str.substr(pos));
		            break;
		        }else{
		            result.push_back(str.substr(pos, p - pos));
		        }
		        pos = p + delim.size();
		    }
		    return result;
		}
	};

	void init_socket(){
	    struct sockaddr_in server;
		if((context.sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0){
			exit(EXIT_FAILURE);
		}
		memset( &server, 0, sizeof(server));
		server.sin_family = AF_INET;
		server.sin_addr.s_addr = INADDR_ANY;
		server.sin_port = htons(context.port);

		char opt = 1;
		setsockopt(context.sockfd, SOL_SOCKET, SO_REUSEADDR, (char *)&opt, sizeof(char));

		int temp = 1;
  		if(setsockopt(context.sockfd, SOL_SOCKET, SO_REUSEADDR,
	        &temp, sizeof(int))){
		}

		if (bind(context.sockfd, (struct sockaddr *) &server, sizeof(server)) < 0) {
			exit(EXIT_FAILURE);
		}

		if(listen(context.sockfd,  MAX_LISTEN) < 0) {
			exit(EXIT_FAILURE);
		}

	    FD_ZERO(&context.mask1fds);
	    FD_SET(context.sockfd, &context.mask1fds);
	}

	using namespace std;

	string openFile(string aFilename){
		auto filename = aFilename;
		std::ifstream ifs( filename, std::ios::in | std::ios::binary);
		if(ifs.fail()){
			throw std::runtime_error("No such file or directory \""+ filename +"\"\n");
		}
		ifs.seekg( 0, std::ios::end);
		auto pos = ifs.tellg();
		ifs.seekg( 0, std::ios::beg);

		std::vector<char> buf(pos);
		ifs.read(buf.data(), pos);
		return string(buf.begin(), buf.end());;
	}

	void option(int argc, char *argv[]) noexcept{
		char result;
		while((result = getopt(argc,argv,"dp:")) != -1){
			switch(result){
			case 'd':
				Log::LogLevel = 1;
				break;
			case 'p':
				context.port = atoi(optarg);
				break;
			}
		}
	}

	class Request{
		unordered_map<string, string> headerset;
		unordered_map<string, string> paramset;
	  public:
		Request(string method, string url,string protocol):
		method(move(method)),
		url(move(url)),
		protocol(move(protocol))
		{}

		const string method;
		const string url;
		const string protocol;

		void addHeader(string key,string value){
			headerset[key] = move(value);
		}

		void addParams(string key,string value){
			paramset[key] = move(value);
		}

		string header(string key){
			if(headerset.find(key) == headerset.end())
				return "INVALID";
			return headerset[key];
		}

		string params(string key){
			if(paramset.find(key) == paramset.end())
				return "INVALID";
			return paramset[key];
		}
	};

    class Response{
		int status_;
		string message_;
		string url_;
		string body_;
		string protocol_;
      public:

		Response(weak_ptr<Request> req){
			auto r = req.lock();
			if(r){
				url_ = r->url;
				protocol_ = r->protocol;
			}else{
				throw std::runtime_error("Request  expired!\n");
			}
		}

		Response(int st,string msg,string pro, string bod):
			status_(st),
			message_(msg),
			body_(bod),
			protocol_(pro)
		{}

		Response* message(string msg){
			message_ = msg;
			return this;
		}

		Response* status(int st){
			status_ = st;
			return this;
		}

		Response* file(string filename){
			body_ = openFile(*context.view_root + "/" + filename);
			return this;
		}

      	operator string(){
      		return protocol_ + " " + to_string(status_) +" "+ message_ + "\n\n" + body_;
      	}
    };

	string createResponse(char* req) noexcept{
		auto lines = utils::split(string(req), "\n");
		if(lines.empty())
			return Response(400, "Bad Request", "HTTP/1.1", "NN");

		auto tops = utils::split(lines[0], " ");
		if(tops.size() < 3)
			return Response(401, "Bad Request", "HTTP/1.1",  "NN");

		cout<< tops[0] << " " << tops[1] << " " <<tops[2] << endl;

		auto request = shared_ptr<Request>(new Request(tops[0],tops[1],tops[2]));

		if(context.routes.find(tops[1]) != context.routes.end()){
			return context.routes[tops[1]](move(request));
		}

		return Response( 404,"Not found", tops[2], "AA");
	}

	string receiveProcess(int sessionfd){
		char buf[BUF_SIZE] = {};

		if (recv(sessionfd, buf, sizeof(buf), 0) < 0) {
			exit(EXIT_FAILURE);
		}
		do{
			if(strstr(buf, "\r\n")){
				break;
			}
			if (strlen(buf) >= sizeof(buf)) {
				memset(&buf, 0, sizeof(buf));
			}
		}while(read(sessionfd, buf+strlen(buf), sizeof(buf) - strlen(buf)) > 0);
		return createResponse(buf);
	}

	void load(string directory, string filename) noexcept{
		if(filename == "." || filename == "..") return;
		if(filename!="")
			directory += "/" + filename;
		DIR* dir = opendir(directory.c_str());
		if(dir != NULL){
			struct dirent* dent;
	        dent = readdir(dir);
		    while(dent!=NULL){
		        dent = readdir(dir);
		        if(dent!=NULL)
			        load(directory, string(dent->d_name));
		    }
		    closedir(dir);
			delete dent;
			delete dir;
		}else{
			cout<<"add "<<directory<< endl;
			context.routes.insert( make_pair(
				"/" + directory,
				[directory,filename](std::shared_ptr<Request> request) -> Cappuccino::Response{
					return Response(200,"OK","HTTP/1.1",openFile(directory));
				}
			));
		}
	}

	void loadStaticFiles() noexcept{
		load(*context.static_root,"");
	}

	void route(string url,std::function<Response(std::shared_ptr<Request>)> F){
		context.routes.insert( make_pair( move(url), move(F) ));
	}

	void root(string r){
		context.view_root =  make_shared<string>(move(r));
	}

	void resource(string s){
		context.static_root = make_shared<string>(move(s));
	}

	void run(){

		init_socket();
		signal_utils::init_signal();
		loadStaticFiles();

	    int cd[FD_SETSIZE];
		struct sockaddr_in client;
        int    fd;
        struct timeval tv;

	    for(int i = 0;i < FD_SETSIZE; i++){
	        cd[i] = 0;
	    }

		int I = 0;
	    while(1) {

			if(I>5){
				return;
			}

	        tv.tv_sec = 0;
	        tv.tv_usec = 0;

	        memcpy(&context.mask2fds, &context.mask1fds, sizeof(context.mask1fds));

	        int select_result = select(FD_SETSIZE, &context.mask2fds, (fd_set *)0, (fd_set *)0, &tv);
	        if(select_result < 1) {
	            for(fd = 0; fd < FD_SETSIZE; fd++) {
	                if(cd[fd] == 1) {
	                    close(fd);
	                    FD_CLR(fd, &context.mask1fds);
	                    cd[fd] = 0;
	                }
	            }
	            continue;
	        }
			for(fd = 0; fd < FD_SETSIZE; fd++){
	            if(FD_ISSET(fd,&context.mask2fds)) {
	                if(fd == context.sockfd) {
	                	memset( &client, 0, sizeof(client));
						int len = sizeof(client);
	                    int clientfd = accept(context.sockfd,
	                        (struct sockaddr *)&client,(socklen_t *) &len);
	                        FD_SET(clientfd, &context.mask1fds);
	                }else {
	                    if(cd[fd] == 1) {
	                        close(fd);
	                        FD_CLR(fd, &context.mask1fds);
	                        cd[fd] = 0;
	                    } else {
							string response = receiveProcess(fd);
							write(fd, response.c_str(), response.size());
	                        cd[fd] = 1;

							I++;

	                    }
	                }
	            }
	        }
	    }
	}

	void Cappuccino(int argc, char *argv[]) {
		option(argc, argv);
		context.view_root = make_shared<string>("");
		context.static_root = make_shared<string>("public");
	}
};

namespace Cocoa{
	using namespace Cappuccino;
	using namespace std;

	// Unit Test
	void testOpenFile(){
		string res = openFile("html/index.html");
		auto lines = utils::split(res, "\n");
		assert(!lines.empty());
	}

	void testOpenInvalidFile(){
		try{
			string res = openFile("html/index");
		}catch(std::runtime_error e){
			cout<< e.what() << endl;
		}
	}
};

<|endoftext|>


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

namespace dbaui
{
    OToolBoxHelper::OToolBoxHelper()
        : m_bIsHiContrast(sal_False)
        ,m_pToolBox(NULL)
        ,m_nBitmapSet( getCurrentSymbolSet() )
    {
        SvtMiscOptions().AddListener( LINK( this, OToolBoxHelper, ConfigOptionsChanged ) );
        Application::AddEventListener( LINK( this, OToolBoxHelper, SettingsChanged ) );
    }
    // -----------------------------------------------------------------------------
    OToolBoxHelper::~OToolBoxHelper()
    {
        SvtMiscOptions().RemoveListener( LINK( this, OToolBoxHelper, ConfigOptionsChanged ) );
        Application::RemoveEventListener( LINK( this, OToolBoxHelper, SettingsChanged ) );
    }
    // -----------------------------------------------------------------------------
    sal_Int16 OToolBoxHelper::getCurrentSymbolSet()
    {
        sal_Int16   eOptSymbolSet = SvtMiscOptions().GetSymbolSet();

        if ( eOptSymbolSet == SFX_SYMBOLS_AUTO )
        {
            // Use system settings, we have to retrieve the toolbar icon size from the
            // Application class
            ULONG nStyleIconSize = Application::GetSettings().GetStyleSettings().GetToolbarIconSize();
            if ( nStyleIconSize == STYLE_TOOLBAR_ICONSIZE_LARGE )
                eOptSymbolSet = SFX_SYMBOLS_LARGE;
            else
                eOptSymbolSet = SFX_SYMBOLS_SMALL;
        }

        return eOptSymbolSet;
    }

    // -----------------------------------------------------------------------------
    void OToolBoxHelper::checkImageList()
    {
        if ( m_pToolBox )
        {
            sal_Int16 nCurBitmapSet = getCurrentSymbolSet();
            if ( nCurBitmapSet != m_nBitmapSet ||
                m_bIsHiContrast != m_pToolBox->GetBackground().GetColor().IsDark() )
            {
                m_nBitmapSet    = nCurBitmapSet;
                m_bIsHiContrast = m_pToolBox->GetBackground().GetColor().IsDark();

                m_pToolBox->SetImageList( ModuleRes( getImageListId(m_nBitmapSet,m_bIsHiContrast) ) );
                Size aTbOldSize = m_pToolBox->GetSizePixel();
                adjustToolBoxSize(m_pToolBox);
                Size aTbNewSize = m_pToolBox->GetSizePixel();
                resizeControls(Size(aTbNewSize.Width() - aTbOldSize.Width(),
                                    aTbNewSize.Height() - aTbOldSize.Height())
                                );
            }
        }
    }
    // -----------------------------------------------------------------------------
    IMPL_LINK(OToolBoxHelper, ConfigOptionsChanged, SvtMiscOptions*, _pOptions)
    {
        if ( m_pToolBox )
        {
            SvtMiscOptions aOptions;
            // check if imagelist changed
            checkImageList();
            if ( aOptions.GetToolboxStyle() != m_pToolBox->GetOutStyle() )
                m_pToolBox->SetOutStyle(aOptions.GetToolboxStyle());
        }

        return 0L;
    }
    // -----------------------------------------------------------------------------
    IMPL_LINK(OToolBoxHelper, SettingsChanged, void*, _pVoid)
    {
        if ( m_pToolBox )
        {
            // check if imagelist changed
            checkImageList();
        }

        return 0L;
    }
    // -----------------------------------------------------------------------------
    void OToolBoxHelper::setToolBox(ToolBox* _pTB)
    {
        sal_Bool bFirstTime = (m_pToolBox == NULL);
        m_pToolBox = _pTB;
        if ( m_pToolBox )
        {
            //  m_bIsHiContrast = m_pToolBox->GetBackground().GetColor().IsDark();
            ConfigOptionsChanged(NULL);
            if ( bFirstTime )
                adjustToolBoxSize(m_pToolBox);
        }
    }
// -----------------------------------------------------------------------------
} // namespace
// -----------------------------------------------------------------------------

<commit_msg>INTEGRATION: CWS dba05 (1.2.4); FILE MERGED 2003/04/30 14:44:48 oj 1.2.4.3: #109263# filter only usefull events 2003/04/30 13:27:21 oj 1.2.4.2: #109216# set -1 as default for bitmaps, will be changed afterwards 2003/04/30 11:08:59 oj 1.2.4.1: #109216# set small as default for bitmaps, will be changed afterwards<commit_after>/*************************************************************************
 *
 *  $RCSfile: ToolBoxHelper.cxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: vg $ $Date: 2003-05-19 12:55:49 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the License); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an AS IS basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/
#ifndef DBAUI_TOOLBOXHELPER_HXX
#include "ToolBoxHelper.hxx"
#endif
#ifndef _SV_TOOLBOX_HXX
#include <vcl/toolbox.hxx>
#endif
#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif
#ifndef INCLUDED_SVTOOLS_MISCOPT_HXX
#include <svtools/miscopt.hxx>
#endif
#ifndef DBAUI_TOOLS_HXX
#include "UITools.hxx"
#endif
#ifndef _SVTOOLS_IMGDEF_HXX
#include <svtools/imgdef.hxx>
#endif
#ifndef _DBAUI_MODULE_DBU_HXX_
#include "moduledbu.hxx"
#endif
#include <vcl/event.hxx>

namespace dbaui
{
    OToolBoxHelper::OToolBoxHelper()
        : m_bIsHiContrast(sal_False)
        ,m_pToolBox(NULL)
        ,m_nBitmapSet(-1 )
    {
        OSL_ENSURE(m_nBitmapSet != getCurrentSymbolSet(),"BitmapSet should not be identical");
        SvtMiscOptions().AddListener( LINK( this, OToolBoxHelper, ConfigOptionsChanged ) );
        Application::AddEventListener( LINK( this, OToolBoxHelper, SettingsChanged ) );
    }
    // -----------------------------------------------------------------------------
    OToolBoxHelper::~OToolBoxHelper()
    {
        SvtMiscOptions().RemoveListener( LINK( this, OToolBoxHelper, ConfigOptionsChanged ) );
        Application::RemoveEventListener( LINK( this, OToolBoxHelper, SettingsChanged ) );
    }
    // -----------------------------------------------------------------------------
    sal_Int16 OToolBoxHelper::getCurrentSymbolSet()
    {
        sal_Int16   eOptSymbolSet = SvtMiscOptions().GetSymbolSet();

        if ( eOptSymbolSet == SFX_SYMBOLS_AUTO )
        {
            // Use system settings, we have to retrieve the toolbar icon size from the
            // Application class
            ULONG nStyleIconSize = Application::GetSettings().GetStyleSettings().GetToolbarIconSize();
            if ( nStyleIconSize == STYLE_TOOLBAR_ICONSIZE_LARGE )
                eOptSymbolSet = SFX_SYMBOLS_LARGE;
            else
                eOptSymbolSet = SFX_SYMBOLS_SMALL;
        }

        return eOptSymbolSet;
    }

    // -----------------------------------------------------------------------------
    void OToolBoxHelper::checkImageList()
    {
        if ( m_pToolBox )
        {
            sal_Int16 nCurBitmapSet = getCurrentSymbolSet();
            if ( nCurBitmapSet != m_nBitmapSet ||
                m_bIsHiContrast != m_pToolBox->GetBackground().GetColor().IsDark() )
            {
                m_nBitmapSet    = nCurBitmapSet;
                m_bIsHiContrast = m_pToolBox->GetBackground().GetColor().IsDark();

                m_pToolBox->SetImageList( ModuleRes( getImageListId(m_nBitmapSet,m_bIsHiContrast) ) );
                Size aTbOldSize = m_pToolBox->GetSizePixel();
                adjustToolBoxSize(m_pToolBox);
                Size aTbNewSize = m_pToolBox->GetSizePixel();
                resizeControls(Size(aTbNewSize.Width() - aTbOldSize.Width(),
                                    aTbNewSize.Height() - aTbOldSize.Height())
                                );
            }
        }
    }
    // -----------------------------------------------------------------------------
    IMPL_LINK(OToolBoxHelper, ConfigOptionsChanged, SvtMiscOptions*, _pOptions)
    {
        if ( m_pToolBox )
        {
            SvtMiscOptions aOptions;
            // check if imagelist changed
            checkImageList();
            if ( aOptions.GetToolboxStyle() != m_pToolBox->GetOutStyle() )
                m_pToolBox->SetOutStyle(aOptions.GetToolboxStyle());
        }

        return 0L;
    }
    // -----------------------------------------------------------------------------
    IMPL_LINK(OToolBoxHelper, SettingsChanged, VclWindowEvent*, _pEvt)
    {
        if ( m_pToolBox && _pEvt && _pEvt->GetId() == VCLEVENT_APPLICATION_DATACHANGED )
        {
            DataChangedEvent* pData = reinterpret_cast<DataChangedEvent*>(_pEvt->GetData());
            if ( pData && ((( pData->GetType() == DATACHANGED_SETTINGS  )   ||
            ( pData->GetType() == DATACHANGED_DISPLAY   ))  &&
            ( pData->GetFlags() & SETTINGS_STYLE        )))
                // check if imagelist changed
                checkImageList();
        }

        return 0L;
    }
    // -----------------------------------------------------------------------------
    void OToolBoxHelper::setToolBox(ToolBox* _pTB)
    {
        sal_Bool bFirstTime = (m_pToolBox == NULL);
        m_pToolBox = _pTB;
        if ( m_pToolBox )
        {
            //  m_bIsHiContrast = m_pToolBox->GetBackground().GetColor().IsDark();
            ConfigOptionsChanged(NULL);
            if ( bFirstTime )
                adjustToolBoxSize(m_pToolBox);
        }
    }
// -----------------------------------------------------------------------------
} // namespace
// -----------------------------------------------------------------------------

<|endoftext|>


<commit_before>/*ckwg +5
 * Copyright 2011 by Kitware, Inc. All Rights Reserved. Please refer to
 * KITWARE_LICENSE.TXT for licensing information, or contact General Counsel,
 * Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065.
 */

#include <vistk/pipeline/edge.h>
#include <vistk/pipeline/edge_exception.h>
#include <vistk/pipeline/stamp.h>

#include <boost/python.hpp>
#include <boost/python/suite/indexing/vector_indexing_suite.hpp>

/**
 * \file edge.cxx
 *
 * \brief Python bindings for \link vistk::edge\endlink.
 */

using namespace boost::python;

static vistk::datum_t edge_datum_datum(vistk::edge_datum_t const& edatum);
static void edge_datum_datum_set(vistk::edge_datum_t& edatum, vistk::datum_t const& dat);
static vistk::stamp_t edge_datum_stamp(vistk::edge_datum_t const& edatum);
static void edge_datum_stamp_set(vistk::edge_datum_t& edatum, vistk::stamp_t const& st);

static void translator(vistk::edge_exception const& e);

BOOST_PYTHON_MODULE(edge)
{
  register_exception_translator<
    vistk::edge_exception>(translator);

  class_<vistk::edge_datum_t>("EdgeDatum"
    , no_init)
    .def(init<vistk::datum_t, vistk::stamp_t>())
    .add_property("datum", &edge_datum_datum, &edge_datum_datum_set)
    .add_property("stamp", &edge_datum_stamp, &edge_datum_stamp_set)
  ;
  class_<vistk::edge_data_t>("EdgeData")
    .def(vector_indexing_suite<vistk::edge_data_t>())
  ;
  class_<vistk::edges_t>("Edges")
    .def(vector_indexing_suite<vistk::edges_t>())
  ;

  class_<vistk::edge, vistk::edge_t, boost::noncopyable>("Edge"
    , no_init)
    .def(init<vistk::config_t>())
    .def("makes_dependency", &vistk::edge::makes_dependency)
    .def("has_data", &vistk::edge::has_data)
    .def("full_of_data", &vistk::edge::full_of_data)
    .def("datum_count", &vistk::edge::datum_count)
    .def("push_datum", &vistk::edge::push_datum)
    .def("get_datum", &vistk::edge::get_datum)
    .def("peek_datum", &vistk::edge::peek_datum)
    .def("pop_datum", &vistk::edge::pop_datum)
    .def("set_required_by_downstream", &vistk::edge::set_required_by_downstream)
    .def("required_by_downstream", &vistk::edge::required_by_downstream)
    .def("set_upstream_process", &vistk::edge::set_upstream_process)
    .def("set_downstream_process", &vistk::edge::set_downstream_process)
  ;
}

vistk::datum_t
edge_datum_datum(vistk::edge_datum_t const& edatum)
{
  return edatum.get<0>();
}

void
edge_datum_datum_set(vistk::edge_datum_t& edatum, vistk::datum_t const& dat)
{
  boost::get<0>(edatum) = dat;
}

vistk::stamp_t
edge_datum_stamp(vistk::edge_datum_t const& edatum)
{
  return edatum.get<1>();
}

void
edge_datum_stamp_set(vistk::edge_datum_t& edatum, vistk::stamp_t const& st)
{
  boost::get<1>(edatum) = st;
}

void
translator(vistk::edge_exception const& e)
{
  PyErr_SetString(PyExc_RuntimeError, e.what());
}
<commit_msg>Add docstrings to edge bindings<commit_after>/*ckwg +5
 * Copyright 2011 by Kitware, Inc. All Rights Reserved. Please refer to
 * KITWARE_LICENSE.TXT for licensing information, or contact General Counsel,
 * Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065.
 */

#include <vistk/pipeline/edge.h>
#include <vistk/pipeline/edge_exception.h>
#include <vistk/pipeline/stamp.h>

#include <boost/python.hpp>
#include <boost/python/suite/indexing/vector_indexing_suite.hpp>

/**
 * \file edge.cxx
 *
 * \brief Python bindings for \link vistk::edge\endlink.
 */

using namespace boost::python;

static vistk::datum_t edge_datum_datum(vistk::edge_datum_t const& edatum);
static void edge_datum_datum_set(vistk::edge_datum_t& edatum, vistk::datum_t const& dat);
static vistk::stamp_t edge_datum_stamp(vistk::edge_datum_t const& edatum);
static void edge_datum_stamp_set(vistk::edge_datum_t& edatum, vistk::stamp_t const& st);

static void translator(vistk::edge_exception const& e);

BOOST_PYTHON_MODULE(edge)
{
  register_exception_translator<
    vistk::edge_exception>(translator);

  class_<vistk::edge_datum_t>("EdgeDatum"
    , no_init)
    .def(init<vistk::datum_t, vistk::stamp_t>())
    .add_property("datum", &edge_datum_datum, &edge_datum_datum_set
      , "The datum in the packet.")
    .add_property("stamp", &edge_datum_stamp, &edge_datum_stamp_set
      , "The stamp of the packet.")
  ;
  class_<vistk::edge_data_t>("EdgeData"
    , "A collection of data packets that may be passed through an edge.")
    .def(vector_indexing_suite<vistk::edge_data_t>())
  ;
  class_<vistk::edges_t>("Edges"
    , "A collection of edges.")
    .def(vector_indexing_suite<vistk::edges_t>())
  ;

  class_<vistk::edge, vistk::edge_t, boost::noncopyable>("Edge"
    , "A communication channel between processes."
    , no_init)
    .def(init<vistk::config_t>())
    .def("makes_dependency", &vistk::edge::makes_dependency
      , "Returns True if the edge implies a dependency from downstream on upstream.")
    .def("has_data", &vistk::edge::has_data
      , "Returns True if the edge contains data, False otherwise.")
    .def("full_of_data", &vistk::edge::full_of_data
      , "Returns True if the edge cannot hold anymore data, False otherwise.")
    .def("datum_count", &vistk::edge::datum_count
      , "Returns the number of data packets within the edge.")
    .def("push_datum", &vistk::edge::push_datum
      , (arg("datum"))
      , "Pushes a datum packet into the edge.")
    .def("get_datum", &vistk::edge::get_datum
      , "Returns the next datum packet from the edge, removing it in the process.")
    .def("peek_datum", &vistk::edge::peek_datum
      , "Returns the next datum packet from the edge.")
    .def("pop_datum", &vistk::edge::pop_datum
      , "Remove the next datum packet from the edge.")
    .def("set_required_by_downstream", &vistk::edge::set_required_by_downstream
      , (arg("required"))
      , "Set whether the data within the edge is required by downstream to work.")
    .def("required_by_downstream", &vistk::edge::required_by_downstream
      , "Returns True if the downstream process needs the data in the edge.")
    .def("set_upstream_process", &vistk::edge::set_upstream_process
      , (arg("process"))
      , "Set the process which is feeding data into the edge.")
    .def("set_downstream_process", &vistk::edge::set_downstream_process
      , (arg("process"))
      , "Set the process which is reading data from the edge.")
  ;
}

vistk::datum_t
edge_datum_datum(vistk::edge_datum_t const& edatum)
{
  return edatum.get<0>();
}

void
edge_datum_datum_set(vistk::edge_datum_t& edatum, vistk::datum_t const& dat)
{
  boost::get<0>(edatum) = dat;
}

vistk::stamp_t
edge_datum_stamp(vistk::edge_datum_t const& edatum)
{
  return edatum.get<1>();
}

void
edge_datum_stamp_set(vistk::edge_datum_t& edatum, vistk::stamp_t const& st)
{
  boost::get<1>(edatum) = st;
}

void
translator(vistk::edge_exception const& e)
{
  PyErr_SetString(PyExc_RuntimeError, e.what());
}
<|endoftext|>


<commit_before>#include "Actor.h"
Actor::Actor(Model* model, Vector3f const position, Vector3f const rotation) :
	model(model),
	position(position),
	rotation(rotation)
{
	dPosition.elementArray[0]=0.0f;
	dPosition.elementArray[1]=0.0f;
	dPosition.elementArray[2]=0.0f;
	dRotation.elementArray[0]=0.0f;
	dRotation.elementArray[1]=0.0f;
	dRotation.elementArray[2]=0.0f;
}
Actor::Actor(Model* model, Vector3f const position, Vector3f const dPosition, Vector3f const rotation, Vector3f const dRotation) :
	model(model),
	position(position),
	dPosition(dPosition),
	rotation(rotation),
	dRotation(dRotation)
{
}
Actor::Actor(const Actor& actor) :
	model(actor.model),
	position(actor.position),
	dPosition(actor.dPosition),
	rotation(actor.rotation),
	dRotation(actor.dRotation)
{
}
Actor::~Actor()
{
}
const Model& Actor::getModel() const
{
	return *model;
}
const Vector3f& Actor::getPositionVector3f() const
{
	return position;
}
void Actor::tick(double dt)
{
	position[0] += dPosition[0] * dt;
	position[1] += dPosition[1] * dt;
	position[2] += dPosition[2] * dt;

	return;
}
<commit_msg>fixing build<commit_after>#include "Actor.h"
Actor::Actor(Model* model, Vector3f const position, Vector3f const rotation) :
	model(model),
	position(position),
	rotation(rotation)
{
	dPosition.elementArray[0]=0.0f;
	dPosition.elementArray[1]=0.0f;
	dPosition.elementArray[2]=0.0f;
	dRotation.elementArray[0]=0.0f;
	dRotation.elementArray[1]=0.0f;
	dRotation.elementArray[2]=0.0f;
}
Actor::Actor(Model* model, Vector3f const position, Vector3f const dPosition, Vector3f const rotation, Vector3f const dRotation) :
	model(model),
	position(position),
	dPosition(dPosition),
	rotation(rotation),
	dRotation(dRotation)
{
}
Actor::Actor(const Actor& actor) :
	model(actor.model),
	position(actor.position),
	dPosition(actor.dPosition),
	rotation(actor.rotation),
	dRotation(actor.dRotation)
{
}
Actor::~Actor()
{
}
const Model& Actor::getModel() const
{
	return *model;
}
const Vector3f& Actor::getPositionVector3f() const
{
	return position;
}
void Actor::tick(double dt)
{
	position[0] += dPosition[0] * (float)dt;
	position[1] += dPosition[1] * (float)dt;
	position[2] += dPosition[2] * (float)dt;

	return;
}
<|endoftext|>


<commit_before>
// Add this line to Tex: \newcommand{\wikilist}[1]{\iffalse #1 \fi}

//---------------------------Includes----------------------------------------------//
#include <stdio.h>
#include <string>
#include <list>
#include <iostream>
#include <fstream>
#include <sstream>
#include <cstring>
#include <functional>

//---------------------------Struct ItemDef----------------------------------------//
struct ItemDef {
   enum Type {
      ID_Item = 0,
      ID_Enum = 1
   };//end Enum

   int32_t     depth;
   Type        type[33];
   std::string options;
};//end Struct

//---------------------------Forward Declarations----------------------------------//
bool        addFilename        (std::list<std::string> &filenames, const std::string &name);
std::string trim               (const std::string& str);
bool        getLine            (std::istream &in, std::string &out);
ItemDef     getListDepth       (const std::string &s);
void        generateList       (std::list<std::string> &block, std::ostream &out);
bool        renameFile         (const std::string &oldName, const std::string &newName);
void        extendBlockComment (std::istream &in, std::ostream &out);
void        extendBlockCommand (std::istream &in, std::ostream &out);

//---------------------------Start Main--------------------------------------------//
int main (int argc, char *argv[]) {
   if (argc < 2) {
      printf ("WikiToTex <file> [<file> ...]\n");
      return 0;
   }

   std::list<std::string> filenames;
   bool                   recursive = false;

   std::function<void(const std::string&)> recursiveAddFilename = [&filenames,&recursiveAddFilename](const std::string &f) {
      std::ifstream file (f, std::ios::in);
      std::string   line;

      while (getLine (file, line) ) {
         std::string tline = trim (line);
         std::string name;
         size_t      pos;

         if ( (pos = tline.find ("\\input{") ) != std::string::npos)
            name = tline.substr (pos + 7, tline.size () - (pos+7) - 1);
         else if ( (pos = tline.find ("\\include{") ) != std::string::npos)
            name = tline.substr (pos + 9, tline.size () - (pos+9) - 1);

         if (name.size () && addFilename (filenames, name) )
            recursiveAddFilename (name);
      }//end while

      file.close ();
   };//end Lambda

   for (int32_t i = 1; i < argc; ++i) {
      std::string arg = argv[i];
      if (arg == "-r") {   //TODO extend
         recursive = true;
         continue;
      }

      bool ret = addFilename (filenames, argv[i]);

      if (ret && recursive)
         recursiveAddFilename (argv[i]);
   }//end for

   for (std::string &filename : filenames) {
      std::ifstream      file (filename, std::ios::in);
      std::ostringstream output;
      std::string        line;
      bool               modified = false;

      if (!file.is_open () ) {
         std::cerr << "file \"" << filename << "\" does not exist." << std::endl;
         continue;
      }

      while (getLine (file, line) ) {
         std::string tline = trim (line);
         if (line == "%!wikilist") {
            modified = true;
            extendBlockComment (file, output);
         } else if (tline == "\\wikilist{") {
            modified = true;
            extendBlockCommand (file, output);
         } else
            output << line << "\n";
      }

      file.close ();

      if (modified) {
         renameFile (filename, filename + ".bak");

         std::ofstream out (filename, std::ios::out);
         //std::ofstream out (filename + ".tmp", std::ios::out);

         std::string outS = output.str ();   // We want to remove the last linebreak (will summarize on multiple calls)

         out << outS.substr (0, outS.size () - 1);
      }
   }

   return 0;
}//end Main

//---------------------------Start addFilename-------------------------------------//
// Append Filename if exist, try combinations
static std::string addFilename_suffix[] = {"", ".tex"};

bool addFilename (std::list<std::string> &filenames, const std::string &name) {
//printf ("name: %s\n", name.c_str());
   std::string filename;

   for (std::string &a : addFilename_suffix) {
      std::string s = name + a;

      FILE *f = fopen (s.c_str (), "r");

      if (f) {
         fclose (f);
         filename = s;
         break;
      }
   }//end for

   if (filename.size () ) {
      filenames.push_back (filename);
      return true;
   } else
      return false;
}//end Fct

//---------------------------Start trim--------------------------------------------//
// http://stackoverflow.com/questions/25829143/c-trim-whitespace-from-a-string
std::string trim (const std::string& str) {
   if (!str.size()) return str;
   size_t first = str.find_first_not_of(' ');
   size_t last = str.find_last_not_of(' ');
   return str.substr(first, (last-first+1));
}//end Fct

//---------------------------Start getLine-----------------------------------------//
bool getLine (std::istream &in, std::string &out) {
   if (in.fail() || in.eof() ) {
      out = "";
      return false;
   }

   const int32_t maxLength = 8192;
   char          buffer[maxLength];

   in.getline (buffer, maxLength);

   out = buffer;

   return true;
}//end Fct

//---------------------------Start getListDepth------------------------------------//
ItemDef getListDepth (const std::string &s) {
   ItemDef ret = {0};

   for (int32_t i = 0; i < s.size (); ++i) {
      if (s.at(i) == '-') {
         ret.type[ret.depth] = ItemDef::ID_Item;
         ++ret.depth;
      } else if (s.at(i) == '#') {
         ret.type[ret.depth] = ItemDef::ID_Enum;
         ++ret.depth;
      } else
         break;
   }

   return ret;
}//end Fct

//---------------------------Start extendBlockComment------------------------------//
#ifdef __linux__
bool renameFile (const std::string &oldName, const std::string &newName) {
   return !rename (oldName.c_str (), newName.c_str () );
}//end Fct
#endif

//---------------------------Start generateList------------------------------------//
void generateList (std::list<std::string> &block, std::ostream &out) {
   std::string tline;
   int32_t     spaces = 3;
   int32_t     depth  = 0;
   char        buffer[100];
   ItemDef     defaults[33];
   std::string ItemOpt;

   out << "%begin wikilist\n";

   for (std::string &s : block) {
      tline      = trim (s);

      if (tline[0] == '%') {
         if (tline.find ("%option") == 0) {
            std::string opt = trim (tline.substr (7) );
            char num[3] = { opt[0], opt[1], 0 };
            if (num[0] < '0' || num[0] > '9') continue;
            if (num[1] < '0' || num[1] > '9') num[1] = 0;
            uint32_t n = std::stoi (num) - 1;
            if (n < 33) defaults[n].options = trim (opt.substr (1 + (num[1] != 0) ) );

         } else if (tline.find ("%item") == 0) {
            ItemOpt = trim (tline.substr (5) );
         }

         continue;
      }

      ItemDef id = getListDepth (tline);

      if (id.depth == 0) {
         out << tline << "\n";
         continue;
      }

      while (id.depth > depth) {
         memset (buffer, ' ', depth * spaces); buffer[depth * spaces] = 0;
         out << buffer << "\\begin{itemize}";
         if (defaults[depth].options.size () )
            out << "[" << defaults[depth].options << "]";
         out << "\n";
         ++depth;
      }

      while (id.depth < depth) {
         --depth;
         memset (buffer, ' ', depth * spaces); buffer[depth * spaces] = 0;
         out << buffer << "\\end{itemize}\n";
         ItemOpt.clear ();
      }

      memset (buffer, ' ', depth * spaces); buffer[depth * spaces] = 0;
      out << buffer << "\\item";
      if (ItemOpt.size () )
         out << "[" <<  ItemOpt << "]";
       out << " " << trim (tline.substr (id.depth) ) << "\n";
   }//end for

   while (0 < depth) {
      --depth;
      memset (buffer, ' ', depth * spaces); buffer[depth * spaces] = 0;
      out << buffer << "\\end{itemize}\n";
   }

   out << "%end wikilist\n";
}//end Fct

//---------------------------Start extendBlockComment------------------------------//
void extendBlockComment (std::istream &in, std::ostream &out) {
   std::string line;
   std::string eline;
   std::list<std::string> block;
   block.push_back ("%!wikilist");
   bool cleanup = false;

   while (getLine (in, line) ) {
      if (cleanup) {
         if (line == "%end wikilist")
            break;
      } else if (line.size () == 0) {
         break;
      } else if (line.at (0) == '%') {
         block.push_back (line);
      } else if (line == "%begin wikilist")
         cleanup = true;
      else {
         eline = line + "\n";
         break;
      }
   }//end while

   for (std::string &s : block)
      out << s << "\n";

   block.pop_front ();   // Remove initialzation line

   generateList (block, out);

   if (eline.size () )
      out << eline;
}//end Fct

//---------------------------Start extendBlockCommand------------------------------//
void extendBlockCommand (std::istream &in, std::ostream &out) {
   std::string line;
   std::string tline;
   std::string eline;
   std::list<std::string> block;
   block.push_back ("\\wikilist{");
   bool cleanup = false;
   bool append  = true;

   while (getLine (in, line) ) {
      tline = trim (line);

      if (cleanup) {
         if (line == "%end wikilist")
            break;
      } else if (append && !tline.size () ) {
      } else if (append && tline.at (0) == '}') {
         append = false;
      } else if (!append && line == "%begin wikilist") {
         cleanup = true;
      } else if (append) {
         block.push_back (line);
      } else {
         eline = line + "\n";
         break;
      }
   }//end while

   block.push_back ("}");

   for (std::string &s : block)
      out << s << "\n";

   block.pop_front ();   // Remove initialzation line
   block.pop_back ();    // Remove closing line

   generateList (block, out);

   if (eline.size () )
      out << eline;
}//end Fct
<commit_msg>Fix for commented form.<commit_after>
// Add this line to Tex: \newcommand{\wikilist}[1]{\iffalse #1 \fi}

//---------------------------Includes----------------------------------------------//
#include <stdio.h>
#include <string>
#include <list>
#include <iostream>
#include <fstream>
#include <sstream>
#include <cstring>
#include <functional>

//---------------------------Struct ItemDef----------------------------------------//
struct ItemDef {
   enum Type {
      ID_Item = 0,
      ID_Enum = 1
   };//end Enum

   int32_t     depth;
   Type        type[33];
   std::string options;
};//end Struct

//---------------------------Forward Declarations----------------------------------//
bool        addFilename        (std::list<std::string> &filenames, const std::string &name);
std::string trim               (const std::string& str);
bool        getLine            (std::istream &in, std::string &out);
ItemDef     getListDepth       (const std::string &s);
void        generateList       (std::list<std::string> &block, std::ostream &out);
bool        renameFile         (const std::string &oldName, const std::string &newName);
void        extendBlockComment (std::istream &in, std::ostream &out);
void        extendBlockCommand (std::istream &in, std::ostream &out);

//---------------------------Start Main--------------------------------------------//
int main (int argc, char *argv[]) {
   if (argc < 2) {
      printf ("WikiToTex <file> [<file> ...]\n");
      return 0;
   }

   std::list<std::string> filenames;
   bool                   recursive = false;

   std::function<void(const std::string&)> recursiveAddFilename = [&filenames,&recursiveAddFilename](const std::string &f) {
      std::ifstream file (f, std::ios::in);
      std::string   line;

      while (getLine (file, line) ) {
         std::string tline = trim (line);
         std::string name;
         size_t      pos;

         if ( (pos = tline.find ("\\input{") ) != std::string::npos)
            name = tline.substr (pos + 7, tline.size () - (pos+7) - 1);
         else if ( (pos = tline.find ("\\include{") ) != std::string::npos)
            name = tline.substr (pos + 9, tline.size () - (pos+9) - 1);

         if (name.size () && addFilename (filenames, name) )
            recursiveAddFilename (name);
      }//end while

      file.close ();
   };//end Lambda

   for (int32_t i = 1; i < argc; ++i) {
      std::string arg = argv[i];
      if (arg == "-r") {   //TODO extend
         recursive = true;
         continue;
      }

      bool ret = addFilename (filenames, argv[i]);

      if (ret && recursive)
         recursiveAddFilename (argv[i]);
   }//end for

   for (std::string &filename : filenames) {
      std::ifstream      file (filename, std::ios::in);
      std::ostringstream output;
      std::string        line;
      bool               modified = false;

      if (!file.is_open () ) {
         std::cerr << "file \"" << filename << "\" does not exist." << std::endl;
         continue;
      }

      while (getLine (file, line) ) {
         std::string tline = trim (line);
         if (line == "%!wikilist") {
            modified = true;
            extendBlockComment (file, output);
         } else if (tline == "\\wikilist{") {
            modified = true;
            extendBlockCommand (file, output);
         } else
            output << line << "\n";
      }

      file.close ();

      if (modified) {
         renameFile (filename, filename + ".bak");

         std::ofstream out (filename, std::ios::out);
         //std::ofstream out (filename + ".tmp", std::ios::out);

         std::string outS = output.str ();   // We want to remove the last linebreak (will summarize on multiple calls)

         out << outS.substr (0, outS.size () - 1);
      }
   }

   return 0;
}//end Main

//---------------------------Start addFilename-------------------------------------//
// Append Filename if exist, try combinations
static std::string addFilename_suffix[] = {"", ".tex"};

bool addFilename (std::list<std::string> &filenames, const std::string &name) {
//printf ("name: %s\n", name.c_str());
   std::string filename;

   for (std::string &a : addFilename_suffix) {
      std::string s = name + a;

      FILE *f = fopen (s.c_str (), "r");

      if (f) {
         fclose (f);
         filename = s;
         break;
      }
   }//end for

   if (filename.size () ) {
      filenames.push_back (filename);
      return true;
   } else
      return false;
}//end Fct

//---------------------------Start trim--------------------------------------------//
// http://stackoverflow.com/questions/25829143/c-trim-whitespace-from-a-string
std::string trim (const std::string& str) {
   if (!str.size()) return str;
   size_t first = str.find_first_not_of(' ');
   size_t last = str.find_last_not_of(' ');
   return str.substr(first, (last-first+1));
}//end Fct

//---------------------------Start getLine-----------------------------------------//
bool getLine (std::istream &in, std::string &out) {
   if (in.fail() || in.eof() ) {
      out = "";
      return false;
   }

   const int32_t maxLength = 8192;
   char          buffer[maxLength];

   in.getline (buffer, maxLength);

   out = buffer;

   return true;
}//end Fct

//---------------------------Start getListDepth------------------------------------//
ItemDef getListDepth (const std::string &s) {
   ItemDef ret = {0};

   for (int32_t i = 0; i < s.size (); ++i) {
      if (s.at(i) == '-') {
         ret.type[ret.depth] = ItemDef::ID_Item;
         ++ret.depth;
      } else if (s.at(i) == '#') {
         ret.type[ret.depth] = ItemDef::ID_Enum;
         ++ret.depth;
      } else
         break;
   }

   return ret;
}//end Fct

//---------------------------Start extendBlockComment------------------------------//
#ifdef __linux__
bool renameFile (const std::string &oldName, const std::string &newName) {
   return !rename (oldName.c_str (), newName.c_str () );
}//end Fct
#endif

//---------------------------Start generateList------------------------------------//
void generateList (std::list<std::string> &block, std::ostream &out) {
   std::string tline;
   int32_t     spaces = 3;
   int32_t     depth  = 0;
   char        buffer[100];
   ItemDef     defaults[33];
   std::string ItemOpt;

   out << "%begin wikilist\n";

   for (std::string &s : block) {
      tline      = trim (s);

      if (tline[0] == '%') {
         if (tline.find ("%option") == 0) {
            std::string opt = trim (tline.substr (7) );
            char num[3] = { opt[0], opt[1], 0 };
            if (num[0] < '0' || num[0] > '9') continue;
            if (num[1] < '0' || num[1] > '9') num[1] = 0;
            uint32_t n = std::stoi (num) - 1;
            if (n < 33) defaults[n].options = trim (opt.substr (1 + (num[1] != 0) ) );

         } else if (tline.find ("%item") == 0) {
            ItemOpt = trim (tline.substr (5) );
         }

         continue;
      }

      ItemDef id = getListDepth (tline);

      if (id.depth == 0) {
         out << tline << "\n";
         continue;
      }

      while (id.depth > depth) {
         memset (buffer, ' ', depth * spaces); buffer[depth * spaces] = 0;
         out << buffer << "\\begin{itemize}";
         if (defaults[depth].options.size () )
            out << "[" << defaults[depth].options << "]";
         out << "\n";
         ++depth;
      }

      while (id.depth < depth) {
         --depth;
         memset (buffer, ' ', depth * spaces); buffer[depth * spaces] = 0;
         out << buffer << "\\end{itemize}\n";
         ItemOpt.clear ();
      }

      memset (buffer, ' ', depth * spaces); buffer[depth * spaces] = 0;
      out << buffer << "\\item";
      if (ItemOpt.size () )
         out << "[" <<  ItemOpt << "]";
       out << " " << trim (tline.substr (id.depth) ) << "\n";
   }//end for

   while (0 < depth) {
      --depth;
      memset (buffer, ' ', depth * spaces); buffer[depth * spaces] = 0;
      out << buffer << "\\end{itemize}\n";
   }

   out << "%end wikilist\n";
}//end Fct

//---------------------------Start extendBlockComment------------------------------//
void extendBlockComment (std::istream &in, std::ostream &out) {
   std::string line;
   std::string eline;
   std::list<std::string> block;
   block.push_back ("%!wikilist");
   bool cleanup = false;

   while (getLine (in, line) ) {
      if (cleanup) {
         if (line == "%end wikilist")
            break;
      } else if (line.size () == 0) {
         break;
      } else if (line.at (0) == '%') {
         block.push_back (line.substr (1) );
      } else if (line == "%begin wikilist")
         cleanup = true;
      else {
         eline = line + "\n";
         break;
      }
   }//end while

   for (std::string &s : block)
      out << s << "\n";

   block.pop_front ();   // Remove initialzation line

   generateList (block, out);

   if (eline.size () )
      out << eline;
}//end Fct

//---------------------------Start extendBlockCommand------------------------------//
void extendBlockCommand (std::istream &in, std::ostream &out) {
   std::string line;
   std::string tline;
   std::string eline;
   std::list<std::string> block;
   block.push_back ("\\wikilist{");
   bool cleanup = false;
   bool append  = true;

   while (getLine (in, line) ) {
      tline = trim (line);

      if (cleanup) {
         if (line == "%end wikilist")
            break;
      } else if (append && !tline.size () ) {
      } else if (append && tline.at (0) == '}') {
         append = false;
      } else if (!append && line == "%begin wikilist") {
         cleanup = true;
      } else if (append) {
         block.push_back (line);
      } else {
         eline = line + "\n";
         break;
      }
   }//end while

   block.push_back ("}");

   for (std::string &s : block)
      out << s << "\n";

   block.pop_front ();   // Remove initialzation line
   block.pop_back ();    // Remove closing line

   generateList (block, out);

   if (eline.size () )
      out << eline;
}//end Fct
<|endoftext|>


<commit_before>/*
 * Copyright 2013 Facebook, 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.
 */

#include "folly/PackedSyncPtr.h"

#include <cinttypes>
#include <gtest/gtest.h>
#include <thread>
#include <unordered_map>
#include <utility>

using folly::PackedSyncPtr;

namespace {

// Compile time check for packability.  This requires that
// PackedSyncPtr is a POD struct on gcc.
struct ignore { PackedSyncPtr<int> foo; char c; } __attribute__((packed));
static_assert(sizeof(ignore) == 9, "PackedSyncPtr wasn't packable");

}

TEST(PackedSyncPtr, Basic) {
  PackedSyncPtr<std::pair<int,int>> sp;
  sp.init(new std::pair<int,int>[2]);
  EXPECT_EQ(sizeof(sp), 8);
  sp->first = 5;
  EXPECT_EQ(sp[0].first, 5);
  sp[1].second = 7;
  EXPECT_EQ(sp[1].second, 7);
  sp.lock();
  EXPECT_EQ(sp[1].second, 7);
  sp[0].first = 9;
  EXPECT_EQ(sp->first, 9);
  sp.unlock();
  EXPECT_EQ((sp.get() + 1)->second, 7);

  sp.lock();
  EXPECT_EQ(sp.extra(), 0);
  sp.setExtra(0x13);
  EXPECT_EQ(sp.extra(), 0x13);
  EXPECT_EQ((sp.get() + 1)->second, 7);
  delete sp.get();
  auto newP = new std::pair<int,int>();
  sp.set(newP);
  EXPECT_EQ(sp.extra(), 0x13);
  EXPECT_EQ(sp.get(), newP);
  sp.unlock();
}

// Here we use the PackedSyncPtr to lock the whole SyncVec (base, *base, and sz)
template<typename T>
struct SyncVec {
  PackedSyncPtr<T> base;
  SyncVec() { base.init(); }
  void push_back(const T& t) {
    base.set((T*) realloc(base.get(),
      (base.extra() + 1) * sizeof(T)));
    base[base.extra()] = t;
    base.setExtra(base.extra() + 1);
  }
  void lock() {
    base.lock();
  }
  void unlock() {
    base.unlock();
  }

  T* begin() const { return base.get(); }
  T* end() const { return base.get() + base.extra(); }
};
typedef SyncVec<intptr_t> VecT;
typedef std::unordered_map<int64_t, VecT> Map;
const int mapCap = 1317;
const int nthrs = 297;
static Map map(mapCap);

// Each app thread inserts it's ID into every vec in map
// map is read only, so doesn't need any additional locking
void appThread(intptr_t id) {
  for (auto& kv : map) {
    kv.second.lock();
    kv.second.push_back(id);
    kv.second.unlock();
  }
}

TEST(PackedSyncPtr, Application) {
  for (int64_t i = 0; i < mapCap / 2; ++i) {
    map.insert(std::make_pair(i, VecT()));
  }
  std::vector<std::thread> thrs;
  for (intptr_t i = 0; i < nthrs; i++) {
    thrs.push_back(std::thread(appThread, i));
  }
  for (auto& t : thrs) {
    t.join();
  }

  for (auto& kv : map) {
    // Make sure every thread successfully inserted it's ID into every vec
    std::set<intptr_t> idsFound;
    for (auto& elem : kv.second) {
      EXPECT_TRUE(idsFound.insert(elem).second);  // check for dups
    }
    EXPECT_EQ(idsFound.size(), nthrs); // check they are all there
  }
}

TEST(PackedSyncPtr, extraData) {
  PackedSyncPtr<int> p;
  p.init();
  int* unaligned = reinterpret_cast<int*>(0xf003);
  p.lock();
  p.set(unaligned);
  uintptr_t* bytes = reinterpret_cast<uintptr_t*>(&p);
  LOG(INFO) << "Bytes integer is: 0x" << std::hex << *bytes;
  EXPECT_EQ(p.get(), unaligned);
  p.unlock();
}
<commit_msg>folly: avoid ASAN-detected new[] vs "delete" mismatch<commit_after>/*
 * Copyright 2013 Facebook, 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.
 */

#include "folly/PackedSyncPtr.h"

#include <cinttypes>
#include <gtest/gtest.h>
#include <thread>
#include <unordered_map>
#include <utility>

using folly::PackedSyncPtr;

namespace {

// Compile time check for packability.  This requires that
// PackedSyncPtr is a POD struct on gcc.
struct ignore { PackedSyncPtr<int> foo; char c; } __attribute__((packed));
static_assert(sizeof(ignore) == 9, "PackedSyncPtr wasn't packable");

}

TEST(PackedSyncPtr, Basic) {
  PackedSyncPtr<std::pair<int,int>> sp;
  sp.init(new std::pair<int,int>[2]);
  EXPECT_EQ(sizeof(sp), 8);
  sp->first = 5;
  EXPECT_EQ(sp[0].first, 5);
  sp[1].second = 7;
  EXPECT_EQ(sp[1].second, 7);
  sp.lock();
  EXPECT_EQ(sp[1].second, 7);
  sp[0].first = 9;
  EXPECT_EQ(sp->first, 9);
  sp.unlock();
  EXPECT_EQ((sp.get() + 1)->second, 7);

  sp.lock();
  EXPECT_EQ(sp.extra(), 0);
  sp.setExtra(0x13);
  EXPECT_EQ(sp.extra(), 0x13);
  EXPECT_EQ((sp.get() + 1)->second, 7);
  delete[] sp.get();
  auto newP = new std::pair<int,int>();
  sp.set(newP);
  EXPECT_EQ(sp.extra(), 0x13);
  EXPECT_EQ(sp.get(), newP);
  sp.unlock();
}

// Here we use the PackedSyncPtr to lock the whole SyncVec (base, *base, and sz)
template<typename T>
struct SyncVec {
  PackedSyncPtr<T> base;
  SyncVec() { base.init(); }
  void push_back(const T& t) {
    base.set((T*) realloc(base.get(),
      (base.extra() + 1) * sizeof(T)));
    base[base.extra()] = t;
    base.setExtra(base.extra() + 1);
  }
  void lock() {
    base.lock();
  }
  void unlock() {
    base.unlock();
  }

  T* begin() const { return base.get(); }
  T* end() const { return base.get() + base.extra(); }
};
typedef SyncVec<intptr_t> VecT;
typedef std::unordered_map<int64_t, VecT> Map;
const int mapCap = 1317;
const int nthrs = 297;
static Map map(mapCap);

// Each app thread inserts it's ID into every vec in map
// map is read only, so doesn't need any additional locking
void appThread(intptr_t id) {
  for (auto& kv : map) {
    kv.second.lock();
    kv.second.push_back(id);
    kv.second.unlock();
  }
}

TEST(PackedSyncPtr, Application) {
  for (int64_t i = 0; i < mapCap / 2; ++i) {
    map.insert(std::make_pair(i, VecT()));
  }
  std::vector<std::thread> thrs;
  for (intptr_t i = 0; i < nthrs; i++) {
    thrs.push_back(std::thread(appThread, i));
  }
  for (auto& t : thrs) {
    t.join();
  }

  for (auto& kv : map) {
    // Make sure every thread successfully inserted it's ID into every vec
    std::set<intptr_t> idsFound;
    for (auto& elem : kv.second) {
      EXPECT_TRUE(idsFound.insert(elem).second);  // check for dups
    }
    EXPECT_EQ(idsFound.size(), nthrs); // check they are all there
  }
}

TEST(PackedSyncPtr, extraData) {
  PackedSyncPtr<int> p;
  p.init();
  int* unaligned = reinterpret_cast<int*>(0xf003);
  p.lock();
  p.set(unaligned);
  uintptr_t* bytes = reinterpret_cast<uintptr_t*>(&p);
  LOG(INFO) << "Bytes integer is: 0x" << std::hex << *bytes;
  EXPECT_EQ(p.get(), unaligned);
  p.unlock();
}
<|endoftext|>


<commit_before>// SciTE - Scintilla based Text Editor
/** @file GUIWin.cxx
 ** Interface to platform GUI facilities.
 ** Split off from Scintilla's Platform.h to avoid SciTE depending on implementation of Scintilla.
 **/
// Copyright 1998-2010 by Neil Hodgson <neilh@scintilla.org>
// The License.txt file describes the conditions under which this software may be distributed.

#include <stdio.h>
#include <time.h>

#include <string>
#include <vector>

#ifdef __MINGW_H
#define _WIN32_IE	0x0400
#endif

#undef _WIN32_WINNT
#define _WIN32_WINNT  0x0500
#ifdef _MSC_VER
// windows.h, et al, use a lot of nameless struct/unions - can't fix it, so allow it
#pragma warning(disable: 4201)
#endif
#include <windows.h>
#ifdef _MSC_VER
// okay, that's done, don't allow it in our code
#pragma warning(default: 4201)
#pragma warning(disable: 4244)
#endif

#include "Scintilla.h"
#include "GUI.h"

namespace GUI {

enum { SURROGATE_LEAD_FIRST = 0xD800 };
enum { SURROGATE_TRAIL_FIRST = 0xDC00 };
enum { SURROGATE_TRAIL_LAST = 0xDFFF };

static unsigned int UTF8Length(const wchar_t *uptr, size_t tlen) {
	unsigned int len = 0;
	for (size_t i = 0; i < tlen && uptr[i];) {
		unsigned int uch = uptr[i];
		if (uch < 0x80) {
			len++;
		} else if (uch < 0x800) {
			len += 2;
		} else if ((uch >= SURROGATE_LEAD_FIRST) &&
			(uch <= SURROGATE_TRAIL_LAST)) {
			len += 4;
			i++;
		} else {
			len += 3;
		}
		i++;
	}
	return len;
}

static void UTF8FromUTF16(const wchar_t *uptr, size_t tlen, char *putf, size_t len) {
	int k = 0;
	for (size_t i = 0; i < tlen && uptr[i];) {
		unsigned int uch = uptr[i];
		if (uch < 0x80) {
			putf[k++] = static_cast<char>(uch);
		} else if (uch < 0x800) {
			putf[k++] = static_cast<char>(0xC0 | (uch >> 6));
			putf[k++] = static_cast<char>(0x80 | (uch & 0x3f));
		} else if ((uch >= SURROGATE_LEAD_FIRST) &&
			(uch <= SURROGATE_TRAIL_LAST)) {
			// Half a surrogate pair
			i++;
			unsigned int xch = 0x10000 + ((uch & 0x3ff) << 10) + (uptr[i] & 0x3ff);
			putf[k++] = static_cast<char>(0xF0 | (xch >> 18));
			putf[k++] = static_cast<char>(0x80 | ((xch >> 12) & 0x3f));
			putf[k++] = static_cast<char>(0x80 | ((xch >> 6) & 0x3f));
			putf[k++] = static_cast<char>(0x80 | (xch & 0x3f));
		} else {
			putf[k++] = static_cast<char>(0xE0 | (uch >> 12));
			putf[k++] = static_cast<char>(0x80 | ((uch >> 6) & 0x3f));
			putf[k++] = static_cast<char>(0x80 | (uch & 0x3f));
		}
		i++;
	}
	putf[len] = '\0';
}

static size_t UTF16Length(const char *s, unsigned int len) {
	size_t ulen = 0;
	size_t charLen;
	for (size_t i=0; i<len;) {
		unsigned char ch = static_cast<unsigned char>(s[i]);
		if (ch < 0x80) {
			charLen = 1;
		} else if (ch < 0x80 + 0x40 + 0x20) {
			charLen = 2;
		} else if (ch < 0x80 + 0x40 + 0x20 + 0x10) {
			charLen = 3;
		} else {
			charLen = 4;
			ulen++;
		}
		i += charLen;
		ulen++;
	}
	return ulen;
}

static size_t UTF16FromUTF8(const char *s, size_t len, gui_char *tbuf, size_t tlen) {
	size_t ui=0;
	const unsigned char *us = reinterpret_cast<const unsigned char *>(s);
	size_t i=0;
	while ((i<len) && (ui<tlen)) {
		unsigned char ch = us[i++];
		if (ch < 0x80) {
			tbuf[ui] = ch;
		} else if (ch < 0x80 + 0x40 + 0x20) {
			tbuf[ui] = static_cast<wchar_t>((ch & 0x1F) << 6);
			ch = us[i++];
			tbuf[ui] = static_cast<wchar_t>(tbuf[ui] + (ch & 0x7F));
		} else if (ch < 0x80 + 0x40 + 0x20 + 0x10) {
			tbuf[ui] = static_cast<wchar_t>((ch & 0xF) << 12);
			ch = us[i++];
			tbuf[ui] = static_cast<wchar_t>(tbuf[ui] + ((ch & 0x7F) << 6));
			ch = us[i++];
			tbuf[ui] = static_cast<wchar_t>(tbuf[ui] + (ch & 0x7F));
		} else {
			// Outside the BMP so need two surrogates
			int val = (ch & 0x7) << 18;
			ch = us[i++];
			val += (ch & 0x3F) << 12;
			ch = us[i++];
			val += (ch & 0x3F) << 6;
			ch = us[i++];
			val += (ch & 0x3F);
			tbuf[ui] = static_cast<wchar_t>(((val - 0x10000) >> 10) + SURROGATE_LEAD_FIRST);
			ui++;
			tbuf[ui] = static_cast<wchar_t>((val & 0x3ff) + SURROGATE_TRAIL_FIRST);
		}
		ui++;
	}
	return ui;
}

gui_string StringFromUTF8(const char *s) {
	size_t sLen = s ? strlen(s) : 0;
	size_t wideLen = UTF16Length(s, static_cast<int>(sLen));
	std::vector<gui_char> vgc(wideLen + 1);
	size_t outLen = UTF16FromUTF8(s, sLen, &vgc[0], wideLen);
	vgc[outLen] = 0;
	return gui_string(&vgc[0], outLen);
}

std::string UTF8FromString(const gui_string &s) {
	size_t sLen = s.size();
	size_t narrowLen = UTF8Length(s.c_str(), sLen);
	std::vector<char> vc(narrowLen + 1);
	UTF8FromUTF16(s.c_str(), sLen, &vc[0], narrowLen);
	return std::string(&vc[0], narrowLen);
}

gui_string StringFromInteger(int i) {
	char number[32];
	sprintf(number, "%0d", i);
	gui_char gnumber[32];
	size_t n=0;
	while (number[n]) {
		gnumber[n] = static_cast<gui_char>(number[n]);
		n++;
	}
	gnumber[n] = 0;
	return gui_string(gnumber);
}

void Window::Destroy() {
	if (wid)
		::DestroyWindow(reinterpret_cast<HWND>(wid));
	wid = 0;
}

bool Window::HasFocus() {
	return ::GetFocus() == wid;
}

Rectangle Window::GetPosition() {
	RECT rc;
	::GetWindowRect(reinterpret_cast<HWND>(wid), &rc);
	return Rectangle(rc.left, rc.top, rc.right, rc.bottom);
}

void Window::SetPosition(Rectangle rc) {
	::SetWindowPos(reinterpret_cast<HWND>(wid),
		0, rc.left, rc.top, rc.Width(), rc.Height(), SWP_NOZORDER|SWP_NOACTIVATE);
}

Rectangle Window::GetClientPosition() {
	RECT rc={0,0,0,0};
	if (wid)
		::GetClientRect(reinterpret_cast<HWND>(wid), &rc);
	return  Rectangle(rc.left, rc.top, rc.right, rc.bottom);
}

void Window::Show(bool show) {
	if (show)
		::ShowWindow(reinterpret_cast<HWND>(wid), SW_SHOWNOACTIVATE);
	else
		::ShowWindow(reinterpret_cast<HWND>(wid), SW_HIDE);
}

void Window::InvalidateAll() {
	::InvalidateRect(reinterpret_cast<HWND>(wid), NULL, FALSE);
}

void Window::SetTitle(const gui_char *s) {
	::SetWindowTextW(reinterpret_cast<HWND>(wid), s);
}

void Menu::CreatePopUp() {
	Destroy();
	mid = ::CreatePopupMenu();
}

void Menu::Destroy() {
	if (mid)
		::DestroyMenu(reinterpret_cast<HMENU>(mid));
	mid = 0;
}

void Menu::Show(Point pt, Window &w) {
	::TrackPopupMenu(reinterpret_cast<HMENU>(mid),
		0, pt.x - 4, pt.y, 0,
		reinterpret_cast<HWND>(w.GetID()), NULL);
	Destroy();
}

static bool initialisedET = false;
static bool usePerformanceCounter = false;
static LARGE_INTEGER frequency;

ElapsedTime::ElapsedTime() {
	if (!initialisedET) {
		usePerformanceCounter = ::QueryPerformanceFrequency(&frequency) != 0;
		initialisedET = true;
	}
	if (usePerformanceCounter) {
		LARGE_INTEGER timeVal;
		::QueryPerformanceCounter(&timeVal);
		bigBit = timeVal.HighPart;
		littleBit = timeVal.LowPart;
	} else {
		bigBit = clock();
	}
}

double ElapsedTime::Duration(bool reset) {
	double result;
	long endBigBit;
	long endLittleBit;

	if (usePerformanceCounter) {
		LARGE_INTEGER lEnd;
		::QueryPerformanceCounter(&lEnd);
		endBigBit = lEnd.HighPart;
		endLittleBit = lEnd.LowPart;
		LARGE_INTEGER lBegin;
		lBegin.HighPart = bigBit;
		lBegin.LowPart = littleBit;
		double elapsed = lEnd.QuadPart - lBegin.QuadPart;
		result = elapsed / static_cast<double>(frequency.QuadPart);
	} else {
		endBigBit = clock();
		endLittleBit = 0;
		double elapsed = endBigBit - bigBit;
		result = elapsed / CLOCKS_PER_SEC;
	}
	if (reset) {
		bigBit = endBigBit;
		littleBit = endLittleBit;
	}
	return result;
}

sptr_t ScintillaWindow::Send(unsigned int msg, uptr_t wParam, sptr_t lParam) {
	return ::SendMessage(reinterpret_cast<HWND>(GetID()), msg, wParam, lParam);
}

sptr_t ScintillaWindow::SendPointer(unsigned int msg, uptr_t wParam, void *lParam) {
	return ::SendMessage(reinterpret_cast<HWND>(GetID()), msg, wParam, reinterpret_cast<LPARAM>(lParam));
}

bool IsDBCSLeadByte(int codePage, char ch) {
	if (SC_CP_UTF8 == codePage)
		// For lexing, all characters >= 0x80 are treated the
		// same so none is considered a lead byte.
		return false;
	else
		return ::IsDBCSLeadByteEx(codePage, ch) != 0;
}

}
<commit_msg>Ensure fully initialized. From Coverity warnings.<commit_after>// SciTE - Scintilla based Text Editor
/** @file GUIWin.cxx
 ** Interface to platform GUI facilities.
 ** Split off from Scintilla's Platform.h to avoid SciTE depending on implementation of Scintilla.
 **/
// Copyright 1998-2010 by Neil Hodgson <neilh@scintilla.org>
// The License.txt file describes the conditions under which this software may be distributed.

#include <stdio.h>
#include <time.h>

#include <string>
#include <vector>

#ifdef __MINGW_H
#define _WIN32_IE	0x0400
#endif

#undef _WIN32_WINNT
#define _WIN32_WINNT  0x0500
#ifdef _MSC_VER
// windows.h, et al, use a lot of nameless struct/unions - can't fix it, so allow it
#pragma warning(disable: 4201)
#endif
#include <windows.h>
#ifdef _MSC_VER
// okay, that's done, don't allow it in our code
#pragma warning(default: 4201)
#pragma warning(disable: 4244)
#endif

#include "Scintilla.h"
#include "GUI.h"

namespace GUI {

enum { SURROGATE_LEAD_FIRST = 0xD800 };
enum { SURROGATE_TRAIL_FIRST = 0xDC00 };
enum { SURROGATE_TRAIL_LAST = 0xDFFF };

static unsigned int UTF8Length(const wchar_t *uptr, size_t tlen) {
	unsigned int len = 0;
	for (size_t i = 0; i < tlen && uptr[i];) {
		unsigned int uch = uptr[i];
		if (uch < 0x80) {
			len++;
		} else if (uch < 0x800) {
			len += 2;
		} else if ((uch >= SURROGATE_LEAD_FIRST) &&
			(uch <= SURROGATE_TRAIL_LAST)) {
			len += 4;
			i++;
		} else {
			len += 3;
		}
		i++;
	}
	return len;
}

static void UTF8FromUTF16(const wchar_t *uptr, size_t tlen, char *putf, size_t len) {
	int k = 0;
	for (size_t i = 0; i < tlen && uptr[i];) {
		unsigned int uch = uptr[i];
		if (uch < 0x80) {
			putf[k++] = static_cast<char>(uch);
		} else if (uch < 0x800) {
			putf[k++] = static_cast<char>(0xC0 | (uch >> 6));
			putf[k++] = static_cast<char>(0x80 | (uch & 0x3f));
		} else if ((uch >= SURROGATE_LEAD_FIRST) &&
			(uch <= SURROGATE_TRAIL_LAST)) {
			// Half a surrogate pair
			i++;
			unsigned int xch = 0x10000 + ((uch & 0x3ff) << 10) + (uptr[i] & 0x3ff);
			putf[k++] = static_cast<char>(0xF0 | (xch >> 18));
			putf[k++] = static_cast<char>(0x80 | ((xch >> 12) & 0x3f));
			putf[k++] = static_cast<char>(0x80 | ((xch >> 6) & 0x3f));
			putf[k++] = static_cast<char>(0x80 | (xch & 0x3f));
		} else {
			putf[k++] = static_cast<char>(0xE0 | (uch >> 12));
			putf[k++] = static_cast<char>(0x80 | ((uch >> 6) & 0x3f));
			putf[k++] = static_cast<char>(0x80 | (uch & 0x3f));
		}
		i++;
	}
	putf[len] = '\0';
}

static size_t UTF16Length(const char *s, unsigned int len) {
	size_t ulen = 0;
	size_t charLen;
	for (size_t i=0; i<len;) {
		unsigned char ch = static_cast<unsigned char>(s[i]);
		if (ch < 0x80) {
			charLen = 1;
		} else if (ch < 0x80 + 0x40 + 0x20) {
			charLen = 2;
		} else if (ch < 0x80 + 0x40 + 0x20 + 0x10) {
			charLen = 3;
		} else {
			charLen = 4;
			ulen++;
		}
		i += charLen;
		ulen++;
	}
	return ulen;
}

static size_t UTF16FromUTF8(const char *s, size_t len, gui_char *tbuf, size_t tlen) {
	size_t ui=0;
	const unsigned char *us = reinterpret_cast<const unsigned char *>(s);
	size_t i=0;
	while ((i<len) && (ui<tlen)) {
		unsigned char ch = us[i++];
		if (ch < 0x80) {
			tbuf[ui] = ch;
		} else if (ch < 0x80 + 0x40 + 0x20) {
			tbuf[ui] = static_cast<wchar_t>((ch & 0x1F) << 6);
			ch = us[i++];
			tbuf[ui] = static_cast<wchar_t>(tbuf[ui] + (ch & 0x7F));
		} else if (ch < 0x80 + 0x40 + 0x20 + 0x10) {
			tbuf[ui] = static_cast<wchar_t>((ch & 0xF) << 12);
			ch = us[i++];
			tbuf[ui] = static_cast<wchar_t>(tbuf[ui] + ((ch & 0x7F) << 6));
			ch = us[i++];
			tbuf[ui] = static_cast<wchar_t>(tbuf[ui] + (ch & 0x7F));
		} else {
			// Outside the BMP so need two surrogates
			int val = (ch & 0x7) << 18;
			ch = us[i++];
			val += (ch & 0x3F) << 12;
			ch = us[i++];
			val += (ch & 0x3F) << 6;
			ch = us[i++];
			val += (ch & 0x3F);
			tbuf[ui] = static_cast<wchar_t>(((val - 0x10000) >> 10) + SURROGATE_LEAD_FIRST);
			ui++;
			tbuf[ui] = static_cast<wchar_t>((val & 0x3ff) + SURROGATE_TRAIL_FIRST);
		}
		ui++;
	}
	return ui;
}

gui_string StringFromUTF8(const char *s) {
	size_t sLen = s ? strlen(s) : 0;
	size_t wideLen = UTF16Length(s, static_cast<int>(sLen));
	std::vector<gui_char> vgc(wideLen + 1);
	size_t outLen = UTF16FromUTF8(s, sLen, &vgc[0], wideLen);
	vgc[outLen] = 0;
	return gui_string(&vgc[0], outLen);
}

std::string UTF8FromString(const gui_string &s) {
	size_t sLen = s.size();
	size_t narrowLen = UTF8Length(s.c_str(), sLen);
	std::vector<char> vc(narrowLen + 1);
	UTF8FromUTF16(s.c_str(), sLen, &vc[0], narrowLen);
	return std::string(&vc[0], narrowLen);
}

gui_string StringFromInteger(int i) {
	char number[32];
	sprintf(number, "%0d", i);
	gui_char gnumber[32];
	size_t n=0;
	while (number[n]) {
		gnumber[n] = static_cast<gui_char>(number[n]);
		n++;
	}
	gnumber[n] = 0;
	return gui_string(gnumber);
}

void Window::Destroy() {
	if (wid)
		::DestroyWindow(reinterpret_cast<HWND>(wid));
	wid = 0;
}

bool Window::HasFocus() {
	return ::GetFocus() == wid;
}

Rectangle Window::GetPosition() {
	RECT rc;
	::GetWindowRect(reinterpret_cast<HWND>(wid), &rc);
	return Rectangle(rc.left, rc.top, rc.right, rc.bottom);
}

void Window::SetPosition(Rectangle rc) {
	::SetWindowPos(reinterpret_cast<HWND>(wid),
		0, rc.left, rc.top, rc.Width(), rc.Height(), SWP_NOZORDER|SWP_NOACTIVATE);
}

Rectangle Window::GetClientPosition() {
	RECT rc={0,0,0,0};
	if (wid)
		::GetClientRect(reinterpret_cast<HWND>(wid), &rc);
	return  Rectangle(rc.left, rc.top, rc.right, rc.bottom);
}

void Window::Show(bool show) {
	if (show)
		::ShowWindow(reinterpret_cast<HWND>(wid), SW_SHOWNOACTIVATE);
	else
		::ShowWindow(reinterpret_cast<HWND>(wid), SW_HIDE);
}

void Window::InvalidateAll() {
	::InvalidateRect(reinterpret_cast<HWND>(wid), NULL, FALSE);
}

void Window::SetTitle(const gui_char *s) {
	::SetWindowTextW(reinterpret_cast<HWND>(wid), s);
}

void Menu::CreatePopUp() {
	Destroy();
	mid = ::CreatePopupMenu();
}

void Menu::Destroy() {
	if (mid)
		::DestroyMenu(reinterpret_cast<HMENU>(mid));
	mid = 0;
}

void Menu::Show(Point pt, Window &w) {
	::TrackPopupMenu(reinterpret_cast<HMENU>(mid),
		0, pt.x - 4, pt.y, 0,
		reinterpret_cast<HWND>(w.GetID()), NULL);
	Destroy();
}

static bool initialisedET = false;
static bool usePerformanceCounter = false;
static LARGE_INTEGER frequency;

ElapsedTime::ElapsedTime() {
	if (!initialisedET) {
		usePerformanceCounter = ::QueryPerformanceFrequency(&frequency) != 0;
		initialisedET = true;
	}
	if (usePerformanceCounter) {
		LARGE_INTEGER timeVal;
		::QueryPerformanceCounter(&timeVal);
		bigBit = timeVal.HighPart;
		littleBit = timeVal.LowPart;
	} else {
		bigBit = clock();
		littleBit = 0;
	}
}

double ElapsedTime::Duration(bool reset) {
	double result;
	long endBigBit;
	long endLittleBit;

	if (usePerformanceCounter) {
		LARGE_INTEGER lEnd;
		::QueryPerformanceCounter(&lEnd);
		endBigBit = lEnd.HighPart;
		endLittleBit = lEnd.LowPart;
		LARGE_INTEGER lBegin;
		lBegin.HighPart = bigBit;
		lBegin.LowPart = littleBit;
		double elapsed = lEnd.QuadPart - lBegin.QuadPart;
		result = elapsed / static_cast<double>(frequency.QuadPart);
	} else {
		endBigBit = clock();
		endLittleBit = 0;
		double elapsed = endBigBit - bigBit;
		result = elapsed / CLOCKS_PER_SEC;
	}
	if (reset) {
		bigBit = endBigBit;
		littleBit = endLittleBit;
	}
	return result;
}

sptr_t ScintillaWindow::Send(unsigned int msg, uptr_t wParam, sptr_t lParam) {
	return ::SendMessage(reinterpret_cast<HWND>(GetID()), msg, wParam, lParam);
}

sptr_t ScintillaWindow::SendPointer(unsigned int msg, uptr_t wParam, void *lParam) {
	return ::SendMessage(reinterpret_cast<HWND>(GetID()), msg, wParam, reinterpret_cast<LPARAM>(lParam));
}

bool IsDBCSLeadByte(int codePage, char ch) {
	if (SC_CP_UTF8 == codePage)
		// For lexing, all characters >= 0x80 are treated the
		// same so none is considered a lead byte.
		return false;
	else
		return ::IsDBCSLeadByteEx(codePage, ch) != 0;
}

}
<|endoftext|>


<commit_before>//=======================================================================
// Copyright Baptiste Wicht 2011-2014.
// Distributed under the MIT License.
// (See accompanying file LICENSE or copy at
//  http://opensource.org/licenses/MIT)
//=======================================================================

#include "Variable.hpp"

#include "mtac/cse.hpp"
#include "mtac/Utils.hpp"

using namespace eddic;

bool mtac::are_equivalent(mtac::Quadruple& quadruple, const expression& exp){
    if(exp.op == quadruple.op && exp.type == quadruple.result->type()){
        if(exp.arg1 == *quadruple.arg1 && exp.arg2 == *quadruple.arg2){
            return true;
        } else if(mtac::is_commutative(quadruple.op) && exp.arg1 == *quadruple.arg2 && exp.arg2 == *quadruple.arg1){
            return true;
        }
    }

    return false;
}

bool mtac::is_interesting(mtac::Quadruple& quadruple){
    if(boost::get<std::shared_ptr<Variable>>(&*quadruple.arg1)){
        return true;
    }

    if(boost::get<std::shared_ptr<Variable>>(&*quadruple.arg2)){
        return true;
    }

    return false;
}

bool mtac::is_valid(mtac::Quadruple& quadruple, const mtac::escaped_variables& escaped){
    if(quadruple.op == mtac::Operator::DOT){
        if(auto* ptr = boost::get<std::shared_ptr<Variable>>(&*quadruple.arg1)){
            if((*ptr)->type()->is_pointer()){
                return false;
            }
        }
    }

    if(auto* ptr = boost::get<std::shared_ptr<Variable>>(&*quadruple.arg1)){
        if(escaped.find(*ptr) != escaped.end()){
            return false;
        }
    }

    if(auto* ptr = boost::get<std::shared_ptr<Variable>>(&*quadruple.arg2)){
        if(escaped.find(*ptr) != escaped.end()){
            return false;
        }
    }

    return true;
}

bool mtac::is_commutative(mtac::Operator op){
    return op == mtac::Operator::ADD || op == mtac::Operator::FADD || op == mtac::Operator::MUL || op == mtac::Operator::FMUL;
}

bool mtac::is_expression(mtac::Operator op){
    return (op >= mtac::Operator::ADD && op <= mtac::Operator::FDIV) || op == mtac::Operator::DOT;
}

bool mtac::is_killing(mtac::Quadruple& quadruple, const mtac::expression& expression){
    eddic_assert(quadruple.result, "is_killing should only be called on quadruple erasing the result, thus having a result");

    if(auto* ptr = boost::get<std::shared_ptr<Variable>>(&expression.arg1)){
        if(quadruple.result == *ptr){
            return true;
        }
    }

    if(auto* ptr = boost::get<std::shared_ptr<Variable>>(&expression.arg2)){
        if(quadruple.result == *ptr){
            return true;
        }
    }

    return false;
}

std::ostream& mtac::operator<<(std::ostream& stream, const expression& expression){
    return stream << "{" << expression.arg1 << " " << static_cast<unsigned int>(expression.op) << " " << expression.arg2 << "}";
}

mtac::Operator mtac::assign_op(mtac::Operator op){
    if(op == mtac::Operator::DOT){
        return mtac::Operator::ASSIGN;
    } else if(op <= mtac::Operator::ADD && op <= mtac::Operator::MOD){
        return mtac::Operator::ASSIGN;
    } else if(op <= mtac::Operator::FADD && op <= mtac::Operator::FDIV){
        return mtac::Operator::FASSIGN;
    }

    eddic_unreachable("This is not an expression operator");
}
<commit_msg>Fix operators conversion<commit_after>//=======================================================================
// Copyright Baptiste Wicht 2011-2014.
// Distributed under the MIT License.
// (See accompanying file LICENSE or copy at
//  http://opensource.org/licenses/MIT)
//=======================================================================

#include "Variable.hpp"

#include "mtac/cse.hpp"
#include "mtac/Utils.hpp"

using namespace eddic;

bool mtac::are_equivalent(mtac::Quadruple& quadruple, const expression& exp){
    if(exp.op == quadruple.op && exp.type == quadruple.result->type()){
        if(exp.arg1 == *quadruple.arg1 && exp.arg2 == *quadruple.arg2){
            return true;
        } else if(mtac::is_commutative(quadruple.op) && exp.arg1 == *quadruple.arg2 && exp.arg2 == *quadruple.arg1){
            return true;
        }
    }

    return false;
}

bool mtac::is_interesting(mtac::Quadruple& quadruple){
    if(boost::get<std::shared_ptr<Variable>>(&*quadruple.arg1)){
        return true;
    }

    if(boost::get<std::shared_ptr<Variable>>(&*quadruple.arg2)){
        return true;
    }

    return false;
}

bool mtac::is_valid(mtac::Quadruple& quadruple, const mtac::escaped_variables& escaped){
    if(quadruple.op == mtac::Operator::DOT){
        if(auto* ptr = boost::get<std::shared_ptr<Variable>>(&*quadruple.arg1)){
            if((*ptr)->type()->is_pointer()){
                return false;
            }
        }
    }

    if(auto* ptr = boost::get<std::shared_ptr<Variable>>(&*quadruple.arg1)){
        if(escaped.find(*ptr) != escaped.end()){
            return false;
        }
    }

    if(auto* ptr = boost::get<std::shared_ptr<Variable>>(&*quadruple.arg2)){
        if(escaped.find(*ptr) != escaped.end()){
            return false;
        }
    }

    return true;
}

bool mtac::is_commutative(mtac::Operator op){
    return op == mtac::Operator::ADD || op == mtac::Operator::FADD || op == mtac::Operator::MUL || op == mtac::Operator::FMUL;
}

bool mtac::is_expression(mtac::Operator op){
    return (op >= mtac::Operator::ADD && op <= mtac::Operator::FDIV) || op == mtac::Operator::DOT;
}

bool mtac::is_killing(mtac::Quadruple& quadruple, const mtac::expression& expression){
    eddic_assert(quadruple.result, "is_killing should only be called on quadruple erasing the result, thus having a result");

    if(auto* ptr = boost::get<std::shared_ptr<Variable>>(&expression.arg1)){
        if(quadruple.result == *ptr){
            return true;
        }
    }

    if(auto* ptr = boost::get<std::shared_ptr<Variable>>(&expression.arg2)){
        if(quadruple.result == *ptr){
            return true;
        }
    }

    return false;
}

std::ostream& mtac::operator<<(std::ostream& stream, const expression& expression){
    return stream << "{" << expression.arg1 << " " << static_cast<unsigned int>(expression.op) << " " << expression.arg2 << "}";
}

mtac::Operator mtac::assign_op(mtac::Operator op){
    if(op == mtac::Operator::DOT){
        return mtac::Operator::ASSIGN;
    } else if(op >= mtac::Operator::ADD && op <= mtac::Operator::MOD){
        return mtac::Operator::ASSIGN;
    } else if(op >= mtac::Operator::FADD && op <= mtac::Operator::FDIV){
        return mtac::Operator::FASSIGN;
    }

    eddic_unreachable("This is not an expression operator");
}
<|endoftext|>


<commit_before>#include "console.h"
#include <iostream>
#include <string>
#include "person.h"
#include "data.h"

using namespace std;

Console::Console()
{

}
void Console::getInfo()
{
    string command;
<<<<<<< HEAD

    do
    {

=======
    do
    {
>>>>>>> 888c7ccfc49884cc4dfb3f9426f21de5655fac63
    cout << "Please enter one of the following commands: " << endl;
    cout << "Add - for adding scientist to the list" << endl;
    cout << "View - for viewing the whole list" << endl;
    cout << "Search - for searching for names in the list" << endl;
    cout << "Exit - quits" << endl;

    cin >> command;

<<<<<<< HEAD

=======
>>>>>>> 888c7ccfc49884cc4dfb3f9426f21de5655fac63
    if (command == "Add" || command == "add")
    {
        string name;
        char gender;
        int birth;
        int death;

        cout << "Enter name of scientist: ";
        cin >> name;
        do{
            cout << "Gender (f/m): ";
            cin >> gender;
            if(!(gender == 'm') && !(gender == 'f'))
                cout << "Invalid input!" <<endl;
        }
        while((gender != 'f') && (gender != 'm'));

        cout << "Enter year of birth: ";
        cin >> birth;
        cout << "Enter year of death, unless N/A: ";
        cin >> death;

        Person newData(name, gender, birth, death);
        dat.writeData(newData);

    }
    else if (command == "View" || command == "view")
    {

    }
    else if (command == "Search" || command == "search")
    {

    }

    }while((command != "Exit") && (command != "exit"));
}

void Console::getSort()
{
    int sort;

    cout << "Please enter one of the following commands: " << endl;
    cout << "1 - for alphabetical order" << endl;
    cout << "2 - sort by gender" << endl;
    cout << "3 - sort by age (youngest to oldest)" << endl;
    cin >> sort;

    if(sort == 1)
    {

    }
    else if(sort == 2)
    {

    }
    else if(sort == 3)
    {

    }
}
<commit_msg>línur og drasl<commit_after>#include "console.h"
#include <iostream>
#include <string>
#include "person.h"
#include "data.h"

using namespace std;

Console::Console()
{

}
void Console::getInfo()
{
    string command;

    do
    {

    cout << "--------------------------------------------" << endl;
    cout << "Please enter one of the following commands: " << endl;
    cout << "Add - for adding scientist to the list" << endl;
    cout << "View - for viewing the whole list" << endl;
    cout << "Search - for searching for names in the list" << endl;
    cout << "Exit - quits" << endl;
    cout << "--------------------------------------------" << endl;

    cin >> command;

    if (command == "Add" || command == "add")
    {
        string name;
        char gender;
        int birth;
        int death;

        cout << "Enter name of scientist: ";
        cin >> name;
        do{
            cout << "Gender (f/m): ";
            cin >> gender;
            if(!(gender == 'm') && !(gender == 'f'))
                cout << "Invalid input!" <<endl;
        }
        while((gender != 'f') && (gender != 'm'));

        cout << "Enter year of birth: ";
        cin >> birth;
        cout << "Enter year of death, unless N/A: ";
        cin >> death;
        cout << endl;

        Person newData(name, gender, birth, death);
        dat.writeData(newData);

    }
    else if (command == "View" || command == "view")
    {

    }
    else if (command == "Search" || command == "search")
    {

    }

    }while((command != "Exit") && (command != "exit"));
}

void Console::getSort()
{
    int sort;

    cout << "Please enter one of the following commands: " << endl;
    cout << "1 - for alphabetical order" << endl;
    cout << "2 - sort by gender" << endl;
    cout << "3 - sort by age (youngest to oldest)" << endl;
    cin >> sort;

    if(sort == 1)
    {

    }
    else if(sort == 2)
    {

    }
    else if(sort == 3)
    {

    }
}
<|endoftext|>