<commit_before>// RSHELL.CPP
// Main source code for rshell

// enable debug messages
#define RSHELL_DEBUG
// prepend "[RSHELL]" to prompt, helps to differ from bash
#define RSHELL_PREPEND

#define COL_DEFAULT "\033[39m"
#define COL_PREPEND "\033[32m"

#include "unistd.h"
#include "sys/wait.h"
#include "stdio.h"
#include "errno.h"

#include <iostream>
#include <string>
#include <vector>

#include <boost/algorithm/string.hpp>
#include <boost/algorithm/string/regex.hpp>
#include <boost/regex.hpp>

#include "rshell.h"

const char* CONN_AMP = "&&";
const char* CONN_PIPE = "||";
const char* CONN_SEMIC = ";";
const char* TOKN_COMMENT = "#";

const char* RDIR_PIPE_SYM = "|";
const char* RDIR_INPUT_SYM = "<";
const char* RDIR_OUTPUT_SYM = ">";

enum RDIR_TYPE {
    RDIR_PIPE = 0x001,
    RDIR_INPUT = 0x002,
    RDIR_OUTPUT = 0x004,
    RDIR_OUTPUT_APP = 0x008
};

struct pipe {
    pipe(int t) : type(t) {}
    pipe(int r, int l, int t) : type(t) { files[0] = r; files[1] = t; }
    int type;
    int pipefd[2] = { 0, 1 };
    int files[2];
};

/* Initialize environment */
void init() {}

/* Main loop - controls command line, parsing, and execution logic */
int run() {

    std::vector<std::string> tokens_spc;
    std::vector<std::string> tokens_pipe;
    std::vector<std::string> tokens_word;
    std::string usr_input;
    int prev_exit_code = 0;

    while(true) {

        bool skip_cmd = false;
        std::string prev_spc = "";
        usr_input = prompt();

        tokens_spc = tokenize(usr_input, "(\\|\\||\\&\\&|;|#)");
        for(unsigned int i = 0; i < tokens_spc.size(); i++) {
//            std::cout << prev_exit_code << std::endl;

            std::string spc = tokens_spc.at(i);

            boost::trim(spc);

#ifdef RSHELL_DEBUG
            std::cout << "<" << spc << ">" << std::endl;
#endif

            if(spc == "") continue;

            // assumption: a connector token has no whitespace
            if(         spc == std::string(CONN_AMP)) {
                if(i == 0 || prev_spc != "") {
                    std::cout << "syntax error: bad token \"" << CONN_AMP << "\"\n";
                    break;
                } else if(prev_exit_code != 0  && i != 0) {
                    skip_cmd = true;
                    continue;
                }

                prev_spc = spc;
                continue;

            } else if(  spc == std::string(CONN_PIPE)) {
                if(i == 0 || prev_spc != "") {
                    std::cout << "syntax error: bad token \"" << CONN_PIPE << "\"\n";
                    break;
                } else if(prev_exit_code == 0 && i != 0) {
                    skip_cmd = true;
                    continue;
                }

                prev_spc = spc;
                continue;

            } else if(  spc == std::string(CONN_SEMIC)) {
                if(i == 0 || prev_spc != "")  {
                    std::cout << "syntax error: bad token \"" << CONN_SEMIC << "\"\n";
                    break;
                } else {
                    prev_exit_code = 0;
                    skip_cmd = false;
                    prev_spc = spc;
                    continue;
                }
            } else if(  spc == std::string(TOKN_COMMENT)) {
                break;
            }

            prev_spc = "";
            if(skip_cmd) continue;

            tokens_pipe = tokenize(spc, "\\||<|>"); // regex '|', '<', or '>'
            int syntax_err = 0;

            std::vector<std::string> cmd_set;
            std::vector<struct pipe> pipe_set;

            std::string cur_rdir = "";

            // syntax pass
            for(unsigned int pipe_i = 0; pipe_i < tokens_pipe.size(); pipe_i++) {

                std::string cmd = tokens_pipe.at(pipe_i);

                if(cmd == "") {
                    tokens_pipe.erase(tokens_pipe.begin() + pipe_i);
                    break;
                }
                boost::trim(cmd);

                if(cmd == RDIR_PIPE_SYM) {
                    if(pipe_i == 0) {
                        syntax_err = 1;
                        std::cout << "syntax error: token \"|\" at start of command\n";
                        break;
                    } else if(cur_rdir != "") {
                        syntax_err = 1;
                        std::cout << "syntax error: bad token near \"|\"\n";
                        break;
                    }

                    cur_rdir.append(RDIR_PIPE_SYM);

                    continue;

                } else if(cmd == RDIR_INPUT_SYM) {
                    if(pipe_i == tokens_pipe.size() - 1) {
                        syntax_err = 1;
                        std::cout << "syntax error: expected file for input \"<\"\n";
                        break;
                    }

                    continue;

                } else if(cmd == RDIR_OUTPUT_SYM) {
                    if(pipe_i == tokens_pipe.size() - 1) {
                        syntax_err = 1;
                        std::cout << "syntax error: expected file for output \">\"\n";
                        break;
                    }

                    // skip to next consecutive output redir symbol
                    if(tokens_pipe.at(pipe_i + 1) == RDIR_OUTPUT_SYM) {
                        pipe_i++;
                        continue;
                    }

                } else {
                    cmd_set.push_back(cmd);
                }
            }

            if(syntax_err == 1) break;

            // command running pass
            for(unsigned int cmd_i = 0; cmd_i < cmd_set.size(); cmd_i++) {

                auto cmd = cmd_set.at(cmd_i);

                tokens_word = toksplit(cmd, " ");
                for(unsigned int j = 0; j < tokens_word.size(); j++) {

                    std::string word = tokens_word.at(j);

                    // using boost for convenience - this can be implemented manually
                    boost::trim(word);

                    // kill empty words
                    if(word == "") tokens_word.erase(tokens_word.begin() + j);
                }

                std::vector<char*> cmd_argv(tokens_word.size() + 1);
                for(unsigned int k = 0; k < tokens_word.size(); k++) {
                    cmd_argv[k] = &tokens_word[k][0];
#ifdef RSHELL_DEBUG
                    std::cout << "\t" << "<" << tokens_word.at(k) << ">" << std::endl;
#endif
                }

                // exit only if first word is "exit", after formatting
                if(tokens_word.at(0) == "exit") return 0;

                prev_exit_code = execute(cmd_argv[0], cmd_argv.data());

                // if execvp returned and had error, stop the process
                //  if(err_num == 1) return 1;
            }
        }
    }

    return 0;
}

/* Prints prompt text and takes in raw command line input */
std::string prompt() {

    char hostname[HOST_NAME_MAX];
    if(gethostname(hostname, HOST_NAME_MAX) == -1)
        perror("gethostname");

#ifdef RSHELL_PREPEND
    std::cout << COL_PREPEND << "[RSHELL] ";
#endif

    std::cout << COL_DEFAULT;

    std::cout << getlogin() << "@" << hostname;
    std::cout << "$ " << std::flush;

    std::string input_raw;
    std::getline(std::cin, input_raw);

    return input_raw;
}

/* fork and exec a program, complete error checking */
int execute(const char* path, char* const argv[]) {

#ifdef RSHELL_DEBUG
    std::cout << "executing " << path << std::endl;
#endif

    int pid = fork();

#ifdef RSHELL_DEBUG
    std::cout << "created process with id " << pid << std::endl;
#endif

    if(pid == -1) {
        perror("fork");
        return -1;
    } else if(pid == 0) {
        execvp(path, argv);
        perror(path);
        exit(1);
    } else {

        int exit_code;

        // pass exit code along
        if(waitpid(pid, &exit_code, 0) == -1) perror("waitpid");
        return exit_code;
    }

    return 0;
}

/* Overload to tokenize by whitespace */
std::vector<std::string> tokenize(std::string s) {
    return tokenize(s, "\\s");
}

/* Tokenize a string using boost regex */
std::vector<std::string> tokenize(std::string s, std::string r) {

    std::vector<std::string> token_vec;

//    boost::algorithm::split_regex(token_vec, s, boost::regex(r));

    std::string::const_iterator s_start, s_end;
    s_start = s.begin();
    s_end = s.end();

    boost::match_results<std::string::const_iterator> results;
    boost::match_flag_type flags = boost::match_default;
    while(boost::regex_search(s_start, s_end, results, boost::regex(r), flags)) {

        token_vec.push_back(std::string(s_start, results[0].first));
        token_vec.push_back(results[0]);

        s_start = results[0].second;
        flags |= boost::match_prev_avail;
        flags |= boost::match_not_bob;
    }

    token_vec.push_back(std::string(s_start, s_end));

    // scrub vector of empty fields

    for(unsigned int i = 0; i < token_vec.size(); i++) {
#ifdef RSHELL_DEBUG
//        std::cout << "[" << token_vec.at(i) << "]" << std::endl;
#endif
        if(token_vec.at(i) == "") token_vec.erase(token_vec.begin() + i);
    }

    return token_vec;
}

/* Tokenize a string using boost split */
std::vector<std::string> toksplit(std::string s, std::string toks) {

    std::vector<std::string> token_vec;
    boost::split(token_vec, s, boost::is_any_of(toks), boost::token_compress_on);
    return token_vec;
}
<commit_msg>minor connector error fixes<commit_after>// RSHELL.CPP
// Main source code for rshell

// enable debug messages
//#define RSHELL_DEBUG
// prepend "[RSHELL]" to prompt, helps to differ from bash
#define RSHELL_PREPEND

#define COL_DEFAULT "\033[39m"
#define COL_PREPEND "\033[32m"

#include "unistd.h"
#include "sys/wait.h"
#include "stdio.h"
#include "errno.h"

#include <iostream>
#include <string>
#include <vector>

#include <boost/algorithm/string.hpp>
#include <boost/algorithm/string/regex.hpp>
#include <boost/regex.hpp>

#include "rshell.h"

const char* CONN_AMP = "&&";
const char* CONN_PIPE = "||";
const char* CONN_SEMIC = ";";
const char* TOKN_COMMENT = "#";

const char* RDIR_PIPE_SYM = "|";
const char* RDIR_INPUT_SYM = "<";
const char* RDIR_OUTPUT_SYM = ">";

enum RDIR_TYPE {
    RDIR_PIPE = 0x001,
    RDIR_INPUT = 0x002,
    RDIR_OUTPUT = 0x004,
    RDIR_OUTPUT_APP = 0x008
};

struct pipe {
    pipe(int t) : type(t) {}
    pipe(int r, int l, int t) : type(t) { files[0] = r; files[1] = t; }
    int type;
    int pipefd[2] = { 0, 1 };
    int files[2];
};

/* Initialize environment */
void init() {}

/* Main loop - controls command line, parsing, and execution logic */
int run() {

    std::vector<std::string> tokens_spc;
    std::vector<std::string> tokens_pipe;
    std::vector<std::string> tokens_word;
    std::string usr_input;
    int prev_exit_code = 0;

    while(true) {

        bool skip_cmd = false;
        std::string prev_spc = "";
        usr_input = prompt();

        // regex '||', '&&', ';', or '#'
        tokens_spc = tokenize(usr_input, "(\\|\\||\\&\\&|;|#)");

        for(unsigned int i = 0; i < tokens_spc.size(); i++) {

            std::string spc = tokens_spc.at(i);

            boost::trim(spc);

#ifdef RSHELL_DEBUG
            std::cout << "<" << spc << ">" << std::endl;
#endif

            if(spc == "") continue;

            // assumption: a connector token has no whitespace
            if(         spc == std::string(CONN_AMP)) {
                if(i == 0 || prev_spc != "") {
                    std::cout << "syntax error: bad token \"" << CONN_AMP << "\"\n";
                    break;
                } else if(prev_exit_code != 0  && i != 0) {
                    skip_cmd = true;
                    continue;
                }

                prev_spc = spc;
                continue;

            } else if(  spc == std::string(CONN_PIPE)) {
                if(i == 0 || prev_spc != "") {
                    std::cout << "syntax error: bad token \"" << CONN_PIPE << "\"\n";
                    break;
                } else if(prev_exit_code == 0 && i != 0) {
                    skip_cmd = true;
                    continue;
                }

                prev_spc = spc;
                continue;

            } else if(  spc == std::string(CONN_SEMIC)) {
                if(i == 0)  {
                    std::cout << "syntax error: bad token \"" << CONN_SEMIC << "\"\n";
                    break;
                } else {
                    prev_exit_code = 0;
                    skip_cmd = false;
                    prev_spc = spc;
                    continue;
                }
            } else if(  spc == std::string(TOKN_COMMENT)) {
                break;
            }

            prev_spc = "";
            if(skip_cmd) continue;

            tokens_pipe = tokenize(spc, "\\||<|>"); // regex '|', '<', or '>'
            int syntax_err = 0;

            std::vector<std::string> cmd_set;
            std::vector<struct pipe> pipe_set;

            std::string cur_rdir = "";

            // syntax pass
            for(unsigned int pipe_i = 0; pipe_i < tokens_pipe.size(); pipe_i++) {

                std::string cmd = tokens_pipe.at(pipe_i);

                if(cmd == "") {
                    tokens_pipe.erase(tokens_pipe.begin() + pipe_i);
                    break;
                }
                boost::trim(cmd);

                if(cmd == RDIR_PIPE_SYM) {
                    if(pipe_i == 0) {
                        syntax_err = 1;
                        std::cout << "syntax error: token \"|\" at start of command\n";
                        break;
                    } else if(cur_rdir != "") {
                        syntax_err = 1;
                        std::cout << "syntax error: bad token near \"|\"\n";
                        break;
                    }

                    cur_rdir.append(RDIR_PIPE_SYM);

                    continue;

                } else if(cmd == RDIR_INPUT_SYM) {
                    if(pipe_i == tokens_pipe.size() - 1) {
                        syntax_err = 1;
                        std::cout << "syntax error: expected file for input \"<\"\n";
                        break;
                    }

                    continue;

                } else if(cmd == RDIR_OUTPUT_SYM) {
                    if(pipe_i == tokens_pipe.size() - 1) {
                        syntax_err = 1;
                        std::cout << "syntax error: expected file for output \">\"\n";
                        break;
                    }

                    // skip to next consecutive output redir symbol
                    if(tokens_pipe.at(pipe_i + 1) == RDIR_OUTPUT_SYM) {
                        pipe_i++;
                        continue;
                    }

                } else {
                    cmd_set.push_back(cmd);
                }
            }

            if(syntax_err == 1) break;

            // command running pass
            for(unsigned int cmd_i = 0; cmd_i < cmd_set.size(); cmd_i++) {

                auto cmd = cmd_set.at(cmd_i);

                tokens_word = toksplit(cmd, " ");
                for(unsigned int j = 0; j < tokens_word.size(); j++) {

                    std::string word = tokens_word.at(j);

                    // using boost for convenience - this can be implemented manually
                    boost::trim(word);

                    // kill empty words
                    if(word == "") tokens_word.erase(tokens_word.begin() + j);
                }

                std::vector<char*> cmd_argv(tokens_word.size() + 1);
                for(unsigned int k = 0; k < tokens_word.size(); k++) {
                    cmd_argv[k] = &tokens_word[k][0];
#ifdef RSHELL_DEBUG
                    std::cout << "\t" << "<" << tokens_word.at(k) << ">" << std::endl;
#endif
                }

                // exit only if first word is "exit", after formatting
                if(tokens_word.at(0) == "exit") return 0;

                prev_exit_code = execute(cmd_argv[0], cmd_argv.data());

                // if execvp returned and had error, stop the process
                //  if(err_num == 1) return 1;
            }
        }
    }

    return 0;
}

/* Prints prompt text and takes in raw command line input */
std::string prompt() {

    char hostname[HOST_NAME_MAX];
    if(gethostname(hostname, HOST_NAME_MAX) == -1)
        perror("gethostname");

#ifdef RSHELL_PREPEND
    std::cout << COL_PREPEND << "[RSHELL] ";
#endif

    std::cout << COL_DEFAULT;

    std::cout << getlogin() << "@" << hostname;
    std::cout << "$ " << std::flush;

    std::string input_raw;
    std::getline(std::cin, input_raw);

    return input_raw;
}

/* fork and exec a program, complete error checking */
int execute(const char* path, char* const argv[]) {

#ifdef RSHELL_DEBUG
    std::cout << "executing " << path << std::endl;
#endif

    int pid = fork();

#ifdef RSHELL_DEBUG
    std::cout << "created process with id " << pid << std::endl;
#endif

    if(pid == -1) {
        perror("fork");
        return -1;
    } else if(pid == 0) {
        execvp(path, argv);
        perror(path);
        exit(1);
    } else {

        int exit_code;

        // pass exit code along
        if(waitpid(pid, &exit_code, 0) == -1) perror("waitpid");
        return exit_code;
    }

    return 0;
}

/* Overload to tokenize by whitespace */
std::vector<std::string> tokenize(std::string s) {
    return tokenize(s, "\\s");
}

/* Tokenize a string using boost regex */
std::vector<std::string> tokenize(std::string s, std::string r) {

    std::vector<std::string> token_vec;

//    boost::algorithm::split_regex(token_vec, s, boost::regex(r));

    std::string::const_iterator s_start, s_end;
    s_start = s.begin();
    s_end = s.end();

    boost::match_results<std::string::const_iterator> results;
    boost::match_flag_type flags = boost::match_default;
    while(boost::regex_search(s_start, s_end, results, boost::regex(r), flags)) {

        token_vec.push_back(std::string(s_start, results[0].first));
        token_vec.push_back(results[0]);

        s_start = results[0].second;
        flags |= boost::match_prev_avail;
        flags |= boost::match_not_bob;
    }

    token_vec.push_back(std::string(s_start, s_end));

    // scrub vector of empty fields

    for(unsigned int i = 0; i < token_vec.size(); i++) {
#ifdef RSHELL_DEBUG
//        std::cout << "[" << token_vec.at(i) << "]" << std::endl;
#endif
        if(token_vec.at(i) == "") token_vec.erase(token_vec.begin() + i);
    }

    return token_vec;
}

/* Tokenize a string using boost split */
std::vector<std::string> toksplit(std::string s, std::string toks) {

    std::vector<std::string> token_vec;
    boost::split(token_vec, s, boost::is_any_of(toks), boost::token_compress_on);
    return token_vec;
}
<|endoftext|>


<commit_before>/*-------------------------------------------------------------------------
 *
 *   FILE
 *	binarystring.cxx
 *
 *   DESCRIPTION
 *      implementation of bytea (binary string) conversions
 *
 * Copyright (c) 2003-2010, Jeroen T. Vermeulen <jtv@xs4all.nl>
 *
 * See COPYING for copyright license.  If you did not receive a file called
 * COPYING with this source code, please notify the distributor of this mistake,
 * or contact the author.
 *
 *-------------------------------------------------------------------------
 */
#include "pqxx/compiler-internal.hxx"

#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <new>
#include <stdexcept>

#include "libpq-fe.h"

#include "pqxx/binarystring"

using namespace PGSTD;
using namespace pqxx::internal;

namespace
{
typedef unsigned char unsigned_char;

// Convert textual digit to value
inline unsigned char DV(unsigned char d)
{
  return unsigned_char(digit_to_number(char(d)));
}
}

pqxx::binarystring::binarystring(const result::field &F) :
  super(),
  m_size(0)
{
  const unsigned char *const b(reinterpret_cast<const_iterator>(F.c_str()));

#ifdef PQXX_HAVE_PQUNESCAPEBYTEA
  unsigned char *const p = const_cast<unsigned char *>(b);

  size_t sz = 0;
  super::operator=(super(PQunescapeBytea(p, &sz)));
  if (!get()) throw bad_alloc();
  m_size = sz;

#else
  string s;
  const string::size_type len = F.size();
  s.reserve(len);

  if (len >= 2 && b[0] == '\\' && b[1] == 'x')
  {
    bool in_pair = false;
    int last_nibble = 0;
    for (result::field::size_type i=2; i<len; ++i)
    {
      const unsigned char c = b[i];
      if (isspace(c))
      {
        if (in_pair) throw out_of_range("Escaped binary data is malformed.");
      }
      else if (!isxdigit(c))
      {
	  throw out_of_range("Escaped binary data is malformed.");
      }
      else
      {
        const int nibble = (isdigit(c) ? DV(c) : (10 + tolower(c) - 'a'));
        if (in_pair) s += char((last_nibble<<4) | nibble);
        else last_nibble = nibble;
        in_pair = !in_pair;
      }
    }
    if (in_pair) throw out_of_range("Escaped binary data appears truncated.");
  }
  else
  {
    for (result::field::size_type i=0; i<len; ++i)
    {
      unsigned char c = b[i];
      if (c == '\\')
      {
	c = b[++i];
	if (isdigit(c) && isdigit(b[i+1]) && isdigit(b[i+2]))
	{
	  c = unsigned_char((DV(c)<<6) | (DV(b[i+1])<<3) | DV(b[i+2]));
	  i += 2;
	}
      }
      s += char(c);
    }
  }

  m_size = s.size();
  void *buf = malloc(m_size+1);
  if (!buf) throw bad_alloc();
  super::operator=(super(static_cast<unsigned char *>(buf)));
  memcpy(static_cast<char *>(buf), s.c_str(), m_size);

#endif
}

bool pqxx::binarystring::operator==(const binarystring &rhs) const throw ()
{
  if (rhs.size() != size()) return false;
  for (size_type i=0; i<size(); ++i) if (rhs[i] != data()[i]) return false;
  return true;
}

pqxx::binarystring::const_reference pqxx::binarystring::at(size_type n) const
{
  if (n >= m_size)
  {
    if (!m_size)
      throw out_of_range("Accessing empty binarystring");
    throw out_of_range("binarystring index out of range: " +
	to_string(n) + " (should be below " + to_string(m_size) + ")");
  }
  return data()[n];
}

void pqxx::binarystring::swap(binarystring &rhs)
{
  // PQAlloc<>::swap() is nothrow
  super::swap(rhs);

  // This part very obviously can't go wrong, so do it last
  const size_type s(m_size);
  m_size = rhs.m_size;
  rhs.m_size = s;
}

string pqxx::binarystring::str() const
{
  return string(get(), m_size);
}

string pqxx::escape_binary(const unsigned char bin[], size_t len)
{
#ifdef PQXX_HAVE_PQESCAPEBYTEA
  size_t escapedlen = 0;
  unsigned char *p = const_cast<unsigned char *>(bin);
  PQAlloc<unsigned char> A(PQescapeBytea(p, len, &escapedlen));
  const char *cstr = reinterpret_cast<const char *>(A.get());
  if (!cstr) throw bad_alloc();
  return string(cstr, escapedlen-1);
#else
  /* Very basic workaround for missing PQescapeBytea() in antique versions of
   * libpq.  Clients that use BYTEA are much better off upgrading their libpq,
   * but this might just provide usable service in cases where that is not an
   * option.
   */
  string result;
  result.reserve(len);
  for (size_t i=0; i<len; ++i)
  {
    if (bin[i] >= 0x80 || bin[i] < 0x20)
    {
      char buf[8];
      sprintf(buf, "\\\\%03o", unsigned(bin[i]));
      result += buf;
    }
    else switch (bin[i])
    {
    case '\'':
      result += "\\'";
      break;

    case '\\':
      result += "\\\\\\\\";
      break;

    default:
      result += char(bin[i]);
    }
  }
  return result;
#endif
}

string pqxx::escape_binary(const unsigned char bin[])
{
  return escape_binary(bin, strlen(reinterpret_cast<const char *>(bin)));
}

string pqxx::escape_binary(const char bin[], size_t len)
{
  return escape_binary(reinterpret_cast<const unsigned char *>(bin), len);
}

string pqxx::escape_binary(const char bin[])
{
  return escape_binary(bin, strlen(bin));
}

string pqxx::escape_binary(const string &bin)
{
  return escape_binary(bin.c_str(), bin.size());
}

<commit_msg>Comments.<commit_after>/*-------------------------------------------------------------------------
 *
 *   FILE
 *	binarystring.cxx
 *
 *   DESCRIPTION
 *      implementation of bytea (binary string) conversions
 *
 * Copyright (c) 2003-2010, Jeroen T. Vermeulen <jtv@xs4all.nl>
 *
 * See COPYING for copyright license.  If you did not receive a file called
 * COPYING with this source code, please notify the distributor of this mistake,
 * or contact the author.
 *
 *-------------------------------------------------------------------------
 */
#include "pqxx/compiler-internal.hxx"

#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <new>
#include <stdexcept>

#include "libpq-fe.h"

#include "pqxx/binarystring"

using namespace PGSTD;
using namespace pqxx::internal;

namespace
{
typedef unsigned char unsigned_char;

// Convert textual digit to value
inline unsigned char DV(unsigned char d)
{
  return unsigned_char(digit_to_number(char(d)));
}
}

pqxx::binarystring::binarystring(const result::field &F) :
  super(),
  m_size(0)
{
  const unsigned char *const b(reinterpret_cast<const_iterator>(F.c_str()));

#ifdef PQXX_HAVE_PQUNESCAPEBYTEA
  unsigned char *const p = const_cast<unsigned char *>(b);

  size_t sz = 0;
  super::operator=(super(PQunescapeBytea(p, &sz)));
  if (!get()) throw bad_alloc();
  m_size = sz;

#else
  string s;
  const string::size_type len = F.size();
  s.reserve(len);

  if (len >= 2 && b[0] == '\\' && b[1] == 'x')
  {
    // Hex escape format (9.0+): \x3a20
    bool in_pair = false;
    int last_nibble = 0;
    for (result::field::size_type i=2; i<len; ++i)
    {
      const unsigned char c = b[i];
      if (isspace(c))
      {
        if (in_pair) throw out_of_range("Escaped binary data is malformed.");
      }
      else if (!isxdigit(c))
      {
	  throw out_of_range("Escaped binary data is malformed.");
      }
      else
      {
        const int nibble = (isdigit(c) ? DV(c) : (10 + tolower(c) - 'a'));
        if (in_pair) s += char((last_nibble<<4) | nibble);
        else last_nibble = nibble;
        in_pair = !in_pair;
      }
    }
    if (in_pair) throw out_of_range("Escaped binary data appears truncated.");
  }
  else
  {
    // Octal escape format (pre-9.0): a\123b
    for (result::field::size_type i=0; i<len; ++i)
    {
      unsigned char c = b[i];
      if (c == '\\')
      {
	c = b[++i];
	if (isdigit(c) && isdigit(b[i+1]) && isdigit(b[i+2]))
	{
	  c = unsigned_char((DV(c)<<6) | (DV(b[i+1])<<3) | DV(b[i+2]));
	  i += 2;
	}
      }
      s += char(c);
    }
  }

  m_size = s.size();
  void *buf = malloc(m_size+1);
  if (!buf) throw bad_alloc();
  super::operator=(super(static_cast<unsigned char *>(buf)));
  memcpy(static_cast<char *>(buf), s.c_str(), m_size);

#endif
}

bool pqxx::binarystring::operator==(const binarystring &rhs) const throw ()
{
  if (rhs.size() != size()) return false;
  for (size_type i=0; i<size(); ++i) if (rhs[i] != data()[i]) return false;
  return true;
}

pqxx::binarystring::const_reference pqxx::binarystring::at(size_type n) const
{
  if (n >= m_size)
  {
    if (!m_size)
      throw out_of_range("Accessing empty binarystring");
    throw out_of_range("binarystring index out of range: " +
	to_string(n) + " (should be below " + to_string(m_size) + ")");
  }
  return data()[n];
}

void pqxx::binarystring::swap(binarystring &rhs)
{
  // PQAlloc<>::swap() is nothrow
  super::swap(rhs);

  // This part very obviously can't go wrong, so do it last
  const size_type s(m_size);
  m_size = rhs.m_size;
  rhs.m_size = s;
}

string pqxx::binarystring::str() const
{
  return string(get(), m_size);
}

string pqxx::escape_binary(const unsigned char bin[], size_t len)
{
#ifdef PQXX_HAVE_PQESCAPEBYTEA
  size_t escapedlen = 0;
  unsigned char *p = const_cast<unsigned char *>(bin);
  PQAlloc<unsigned char> A(PQescapeBytea(p, len, &escapedlen));
  const char *cstr = reinterpret_cast<const char *>(A.get());
  if (!cstr) throw bad_alloc();
  return string(cstr, escapedlen-1);
#else
  /* Very basic workaround for missing PQescapeBytea() in antique versions of
   * libpq.  Clients that use BYTEA are much better off upgrading their libpq,
   * but this might just provide usable service in cases where that is not an
   * option.
   */
  string result;
  result.reserve(len);
  for (size_t i=0; i<len; ++i)
  {
    if (bin[i] >= 0x80 || bin[i] < 0x20)
    {
      char buf[8];
      sprintf(buf, "\\\\%03o", unsigned(bin[i]));
      result += buf;
    }
    else switch (bin[i])
    {
    case '\'':
      result += "\\'";
      break;

    case '\\':
      result += "\\\\\\\\";
      break;

    default:
      result += char(bin[i]);
    }
  }
  return result;
#endif
}

string pqxx::escape_binary(const unsigned char bin[])
{
  return escape_binary(bin, strlen(reinterpret_cast<const char *>(bin)));
}

string pqxx::escape_binary(const char bin[], size_t len)
{
  return escape_binary(reinterpret_cast<const unsigned char *>(bin), len);
}

string pqxx::escape_binary(const char bin[])
{
  return escape_binary(bin, strlen(bin));
}

string pqxx::escape_binary(const string &bin)
{
  return escape_binary(bin.c_str(), bin.size());
}

<|endoftext|>


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

#ifndef _SOLAR_H
#include <solar.h>
#endif

#ifndef _RTTI_HXX
#include <rtti.hxx>
#endif

#if _SOLAR__PRIVATE
#include "poolitem.hxx"
#else
#include <sfxipool.hxx>
#endif

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

class SfxRequestItem: public SfxSetItem

/** [Description]

    Represents a function call with optional arguments.
*/

{
public:
                                TYPEINFO();
                                SfxRequestItem();
                                SfxRequestItem( USHORT nWhich, SvStream & );
                                SfxRequestItem( const SfxRequestItem& );
                                ~SfxRequestItem();

    virtual int                 operator==( const SfxPoolItem& ) const;
    virtual
    virtual SfxPoolItem*        Clone( SfxItemPool *pPool = 0 ) const;
    virtual SfxPoolItem*        Create(SvStream &, USHORT nItemVersion) const;
    virtual SvStream&           Store(SvStream &, USHORT nItemVersion ) const;
};

#endif

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

#ifndef _SOLAR_H
#include <solar.h>
#endif

#ifndef _RTTI_HXX
#include <rtti.hxx>
#endif

#if _SOLAR__PRIVATE
#include <svtools/poolitem.hxx>
#else
#include <sfxipool.hxx>
#endif

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

class SfxRequestItem: public SfxSetItem

/** [Description]

    Represents a function call with optional arguments.
*/

{
public:
                                TYPEINFO();
                                SfxRequestItem();
                                SfxRequestItem( USHORT nWhich, SvStream & );
                                SfxRequestItem( const SfxRequestItem& );
                                ~SfxRequestItem();

    virtual int                 operator==( const SfxPoolItem& ) const;
    virtual
    virtual SfxPoolItem*        Clone( SfxItemPool *pPool = 0 ) const;
    virtual SfxPoolItem*        Create(SvStream &, USHORT nItemVersion) const;
    virtual SvStream&           Store(SvStream &, USHORT nItemVersion ) const;
};

#endif

<|endoftext|>


<commit_before>/*
   Copyright (c) 2011, The Mineserver Project
   All rights reserved.

  Redistribution and use in source and binary forms, with or without
  modification, are permitted provided that the following conditions are met:
  * Redistributions of source code must retain the above copyright
    notice, this list of conditions and the following disclaimer.
  * Redistributions in binary form must reproduce the above copyright
    notice, this list of conditions and the following disclaimer in the
    documentation and/or other materials provided with the distribution.
  * Neither the name of the The Mineserver Project nor the
    names of its contributors may be used to endorse or promote products
    derived from this software without specific prior written permission.

  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
  ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY
  DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "mineserver.h"
#include "map.h"
#include "redstoneSimulation.h"
#include "vec.h"

#include "torch.h"

void BlockTorch::onStartedDigging(User* user, int8_t status, int32_t x, int16_t y, int32_t z, int map, int8_t direction)
{

}

void BlockTorch::onDigging(User* user, int8_t status, int32_t x, int16_t y, int32_t z, int map, int8_t direction)
{

}

void BlockTorch::onStoppedDigging(User* user, int8_t status, int32_t x, int16_t y, int32_t z, int map, int8_t direction)
{

}

bool BlockTorch::onBroken(User* user, int8_t status, int32_t x, int16_t y, int32_t z, int map, int8_t direction)
{
  uint8_t block, meta;
  ServerInstance->map(map)->getBlock(x, y, z, &block, &meta);

  ServerInstance->map(map)->setBlock(x, y, z, BLOCK_AIR, 0);
  ServerInstance->map(map)->sendBlockChange(x, y, z, BLOCK_AIR, 0);

  this->spawnBlockItem(x, y, z, map, block, 0);

  if(block == BLOCK_REDSTONE_TORCH_OFF || block == BLOCK_REDSTONE_TORCH_ON)
  {
    ServerInstance->redstone(map)->addSimulation(vec(x,y,z));
  }

  return false;
}

void BlockTorch::onNeighbourBroken(User* user, int16_t oldblock, int32_t x, int16_t y, int32_t z, int map, int8_t direction)
{
  uint8_t block;
  uint8_t meta;
  bool destroy = false;

  if (!ServerInstance->map(map)->getBlock(x, y, z, &block, &meta))
  {
    return;
  }

  if (direction == BLOCK_TOP && meta == BLOCK_TOP && this->isBlockEmpty(x, y - 1, z, map))
  {
    destroy = true;
    // Crude fix for weird sign destruction
    uint8_t tempblock;
    uint8_t tempmeta;
    if (ServerInstance->map(map)->getBlock(x, y, z, &tempblock, &tempmeta) && tempblock == BLOCK_WALL_SIGN)
    {
      destroy = false;
    }
  }
  else if (direction == BLOCK_NORTH && meta == BLOCK_SOUTH && this->isBlockEmpty(x + 1, y, z, map))
  {
    destroy = true;
  }
  else if (direction == BLOCK_SOUTH && meta == BLOCK_NORTH && this->isBlockEmpty(x - 1, y, z, map))
  {
    destroy = true;
  }
  else if (direction == BLOCK_EAST && meta == BLOCK_WEST && this->isBlockEmpty(x, y, z + 1, map))
  {
    destroy = true;
  }
  else if (direction == BLOCK_WEST && meta == BLOCK_EAST && this->isBlockEmpty(x, y, z - 1, map))
  {
    destroy = true;
  }

  if (destroy)
  {
    // Break torch and spawn torch item
    ServerInstance->map(map)->sendBlockChange(x, y, z, BLOCK_AIR, 0);
    ServerInstance->map(map)->setBlock(x, y, z, BLOCK_AIR, 0);
    this->spawnBlockItem(x, y, z, map, block);
  }
}

bool BlockTorch::onPlace(User* user, int16_t newblock, int32_t x, int16_t y, int32_t z, int map, int8_t direction)
{
  uint8_t oldblock;
  uint8_t oldmeta;

  if (!ServerInstance->map(map)->getBlock(x, y, z, &oldblock, &oldmeta))
  {
    revertBlock(user, x, y, z, map);
    return true;
  }

  /* Check block below allows blocks placed on top */
  if (!this->isBlockStackable(oldblock))
  {
    revertBlock(user, x, y, z, map);
    return true;
  }

  /* move the x,y,z coords dependent upon placement direction */
  if (!this->translateDirection(&x, &y, &z, map, direction))
  {
    revertBlock(user, x, y, z, map);
    return true;
  }

  if (!this->isBlockEmpty(x, y, z, map))
  {
    revertBlock(user, x, y, z, map);
    return true;
  }

  ServerInstance->map(map)->setBlock(x, y, z, (char)newblock, direction);
  ServerInstance->map(map)->sendBlockChange(x, y, z, (char)newblock, direction);

  if(newblock == BLOCK_REDSTONE_TORCH_OFF || newblock == BLOCK_REDSTONE_TORCH_ON)
  {
    ServerInstance->redstone(map)->addSimulation(vec(x,y,z));
  }

  return false;
}

void BlockTorch::onNeighbourPlace(User* user, int16_t newblock, int32_t x, int16_t y, int32_t z, int map, int8_t direction)
{
}

void BlockTorch::onReplace(User* user, int16_t newblock, int32_t x, int16_t y, int32_t z, int map, int8_t direction)
{
  uint8_t oldblock;
  uint8_t oldmeta;

  switch (newblock)
  {
  case BLOCK_WATER:
  case BLOCK_STATIONARY_WATER:
  {
    if (ServerInstance->map(map)->getBlock(x, y, z, &oldblock, &oldmeta))
    {
      // spawn item
      ServerInstance->map(map)->sendBlockChange(x, y, z, 0, 0);
      ServerInstance->map(map)->setBlock(x, y, z, 0, 0);
      this->spawnBlockItem(x, y, z, map, oldblock);
    }
  }
  break;
  case BLOCK_LAVA:
  case BLOCK_STATIONARY_LAVA:
  {
    if (ServerInstance->map(map)->getBlock(x, y, z, &oldblock, &oldmeta))
    {
      // destroy
      ServerInstance->map(map)->sendBlockChange(x, y, z, 0, 0);
      ServerInstance->map(map)->setBlock(x, y, z, 0, 0);
    }
  }
  break;
  default:
    return;
    break;
  }
}

void BlockTorch::onNeighbourMove(User* user, int16_t oldblock, int32_t x, int16_t y, int32_t z, int map, int8_t direction)
{
  this->onNeighbourBroken(user, oldblock, x, y, z, map, direction);
}
<commit_msg>Handle torch placement on the bottom of the block<commit_after>/*
   Copyright (c) 2011, The Mineserver Project
   All rights reserved.

  Redistribution and use in source and binary forms, with or without
  modification, are permitted provided that the following conditions are met:
  * Redistributions of source code must retain the above copyright
    notice, this list of conditions and the following disclaimer.
  * Redistributions in binary form must reproduce the above copyright
    notice, this list of conditions and the following disclaimer in the
    documentation and/or other materials provided with the distribution.
  * Neither the name of the The Mineserver Project nor the
    names of its contributors may be used to endorse or promote products
    derived from this software without specific prior written permission.

  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
  ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY
  DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "mineserver.h"
#include "map.h"
#include "redstoneSimulation.h"
#include "vec.h"

#include "torch.h"

void BlockTorch::onStartedDigging(User* user, int8_t status, int32_t x, int16_t y, int32_t z, int map, int8_t direction)
{

}

void BlockTorch::onDigging(User* user, int8_t status, int32_t x, int16_t y, int32_t z, int map, int8_t direction)
{

}

void BlockTorch::onStoppedDigging(User* user, int8_t status, int32_t x, int16_t y, int32_t z, int map, int8_t direction)
{

}

bool BlockTorch::onBroken(User* user, int8_t status, int32_t x, int16_t y, int32_t z, int map, int8_t direction)
{
  uint8_t block, meta;
  ServerInstance->map(map)->getBlock(x, y, z, &block, &meta);

  ServerInstance->map(map)->setBlock(x, y, z, BLOCK_AIR, 0);
  ServerInstance->map(map)->sendBlockChange(x, y, z, BLOCK_AIR, 0);

  this->spawnBlockItem(x, y, z, map, block, 0);

  if(block == BLOCK_REDSTONE_TORCH_OFF || block == BLOCK_REDSTONE_TORCH_ON)
  {
    ServerInstance->redstone(map)->addSimulation(vec(x,y,z));
  }

  return false;
}

void BlockTorch::onNeighbourBroken(User* user, int16_t oldblock, int32_t x, int16_t y, int32_t z, int map, int8_t direction)
{
  uint8_t block;
  uint8_t meta;
  bool destroy = false;

  if (!ServerInstance->map(map)->getBlock(x, y, z, &block, &meta))
  {
    return;
  }

  if (direction == BLOCK_TOP && meta == BLOCK_TOP && this->isBlockEmpty(x, y - 1, z, map))
  {
    destroy = true;
    // Crude fix for weird sign destruction
    uint8_t tempblock;
    uint8_t tempmeta;
    if (ServerInstance->map(map)->getBlock(x, y, z, &tempblock, &tempmeta) && tempblock == BLOCK_WALL_SIGN)
    {
      destroy = false;
    }
  }
  else if (direction == BLOCK_NORTH && meta == BLOCK_SOUTH && this->isBlockEmpty(x + 1, y, z, map))
  {
    destroy = true;
  }
  else if (direction == BLOCK_SOUTH && meta == BLOCK_NORTH && this->isBlockEmpty(x - 1, y, z, map))
  {
    destroy = true;
  }
  else if (direction == BLOCK_EAST && meta == BLOCK_WEST && this->isBlockEmpty(x, y, z + 1, map))
  {
    destroy = true;
  }
  else if (direction == BLOCK_WEST && meta == BLOCK_EAST && this->isBlockEmpty(x, y, z - 1, map))
  {
    destroy = true;
  }

  if (destroy)
  {
    // Break torch and spawn torch item
    ServerInstance->map(map)->sendBlockChange(x, y, z, BLOCK_AIR, 0);
    ServerInstance->map(map)->setBlock(x, y, z, BLOCK_AIR, 0);
    this->spawnBlockItem(x, y, z, map, block);
  }
}

bool BlockTorch::onPlace(User* user, int16_t newblock, int32_t x, int16_t y, int32_t z, int map, int8_t direction)
{
  uint8_t oldblock;
  uint8_t oldmeta;

  if (!ServerInstance->map(map)->getBlock(x, y, z, &oldblock, &oldmeta))
  {
    revertBlock(user, x, y, z, map);
    return true;
  }

  /* Check block below allows blocks placed on top */
  if (!this->isBlockStackable(oldblock))
  {
    revertBlock(user, x, y, z, map);
    return true;
  }

  /* move the x,y,z coords dependent upon placement direction */
  if (!this->translateDirection(&x, &y, &z, map, direction))
  {
    revertBlock(user, x, y, z, map);
    return true;
  }

  if (!this->isBlockEmpty(x, y, z, map))
  {
    revertBlock(user, x, y, z, map);
    return true;
  }
  if (direction == 0)
  {
    if (ServerInstance->map(map)->getBlock(x+1, y, z, &oldblock, &oldmeta) && oldblock != BLOCK_AIR)
    {
      direction = 2;
    }
    else if (ServerInstance->map(map)->getBlock(x, y, z+1, &oldblock, &oldmeta) && oldblock != BLOCK_AIR)
    {
      direction = 4;
    }
    else if (ServerInstance->map(map)->getBlock(x-1, y, z, &oldblock, &oldmeta) && oldblock != BLOCK_AIR)
    {
      direction = 1;
    }
    else if (ServerInstance->map(map)->getBlock(x, y, z-1, &oldblock, &oldmeta) && oldblock != BLOCK_AIR)
    {
      direction = 3;
    }
    else
    {
      direction = 5;
    }
   }

  ServerInstance->map(map)->setBlock(x, y, z, (char)newblock, direction);
  ServerInstance->map(map)->sendBlockChange(x, y, z, (char)newblock, direction);

  if(newblock == BLOCK_REDSTONE_TORCH_OFF || newblock == BLOCK_REDSTONE_TORCH_ON)
  {
    ServerInstance->redstone(map)->addSimulation(vec(x,y,z));
  }

  return false;
}

void BlockTorch::onNeighbourPlace(User* user, int16_t newblock, int32_t x, int16_t y, int32_t z, int map, int8_t direction)
{
}

void BlockTorch::onReplace(User* user, int16_t newblock, int32_t x, int16_t y, int32_t z, int map, int8_t direction)
{
  uint8_t oldblock;
  uint8_t oldmeta;

  switch (newblock)
  {
  case BLOCK_WATER:
  case BLOCK_STATIONARY_WATER:
  {
    if (ServerInstance->map(map)->getBlock(x, y, z, &oldblock, &oldmeta))
    {
      // spawn item
      ServerInstance->map(map)->sendBlockChange(x, y, z, 0, 0);
      ServerInstance->map(map)->setBlock(x, y, z, 0, 0);
      this->spawnBlockItem(x, y, z, map, oldblock);
    }
  }
  break;
  case BLOCK_LAVA:
  case BLOCK_STATIONARY_LAVA:
  {
    if (ServerInstance->map(map)->getBlock(x, y, z, &oldblock, &oldmeta))
    {
      // destroy
      ServerInstance->map(map)->sendBlockChange(x, y, z, 0, 0);
      ServerInstance->map(map)->setBlock(x, y, z, 0, 0);
    }
  }
  break;
  default:
    return;
    break;
  }
}

void BlockTorch::onNeighbourMove(User* user, int16_t oldblock, int32_t x, int16_t y, int32_t z, int map, int8_t direction)
{
  this->onNeighbourBroken(user, oldblock, x, y, z, map, direction);
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: svdpagv.hxx,v $
 * $Revision: 1.4 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#ifndef _SVDPAGV_HXX
#define _SVDPAGV_HXX

#include <com/sun/star/awt/XControlContainer.hpp>
#include <svtools/lstner.hxx>
#include <svx/svdhlpln.hxx>
#include <cppuhelper/implbase4.hxx>
#include <svx/svdsob.hxx>
#include <svx/svdtypes.hxx>
#include "svx/svxdllapi.h"

#include <cppuhelper/implbase3.hxx>
#include <vector>
#include <basegfx/polygon/b2dpolypolygon.hxx>

////////////////////////////////////////////////////////////////////////////////////////////////////

class Region;
class SdrObjList;
class SdrObject;
class SdrPage;
class SdrUnoObj;
class SdrPaintWindow;
class SdrView;
class SdrPageObj;
class B2dIAOManager;
class SdrPageView;

// #110094#
namespace sdr
{
    namespace contact
    {
        class ViewObjectContactRedirector;
        class DisplayInfo;
        class ViewObjectContactRedirector;
    } // end of namespace contact
} // end of namespace sdr

// typedefs for a list of SdrPageWindow
class SdrPageWindow;
typedef ::std::vector< SdrPageWindow* > SdrPageWindowVector;

////////////////////////////////////////////////////////////////////////////////////////////////////

class SVX_DLLPUBLIC SdrPageView : public SfxListener
{
    const ::sdr::contact::DisplayInfo*                              mpDisplayInfo;

protected:
    SdrView&                                                        mrView;
    SdrPage*                                                        mpPage;
    Point         aPgOrg;   // Nullpunkt der Page

    Rectangle     aMarkBound; // wird
    Rectangle     aMarkSnap;  // von
    basegfx::B2DPolyPolygon     maDragPoly0; // SdrView
    basegfx::B2DPolyPolygon     maDragPoly;  //
    sal_Bool                                                        mbHasMarked;
    sal_Bool                                                        mbVisible;

    SetOfByte    aLayerVisi;   // Menge der sichtbaren Layer
    SetOfByte    aLayerLock;   // Menge der nicht editierbaren Layer
    SetOfByte    aLayerPrn;    // Menge der druckbaren Layer

    SdrObjList*  pAktList;     // Aktuelle Liste, in der Regel die Page.
    SdrObject*   pAktGroup;    // Aktuelle Gruppe. NULL=Keine.

    SdrHelpLineList aHelpLines; // Hilfslinien und -punkte

    // #103911# Use one reserved slot (bReserveBool2) for the document color
    Color         maDocumentColor;

    // #103834# Use one reserved slot (bReserveBool1) for the background color
    Color         maBackgroundColor;

    SdrPageWindowVector                                         maPageWindows;

    // #i72752# member to remember with which SdrPageWindow the BeginDrawLayer
    // was done
    SdrPageWindow*                                              mpPreparedPageWindow;

    // interface to SdrPageWindow
protected:
    void ClearPageWindows();
    void AppendPageWindow(SdrPageWindow& rNew);
    SdrPageWindow* RemovePageWindow(sal_uInt32 nPos);
    SdrPageWindow* RemovePageWindow(SdrPageWindow& rOld);
public:
    sal_uInt32 PageWindowCount() const { return maPageWindows.size(); }
    SdrPageWindow* FindPageWindow( SdrPaintWindow& rPaintWindow ) const;
    SdrPageWindow* FindPageWindow( const OutputDevice& rOutDev ) const;
    SdrPageWindow* GetPageWindow(sal_uInt32 nIndex) const;

    /** finds the page window whose PaintWindow belongs to the given output device

        In opposite to FindPageWindow, this method also cares possibly patched PaintWindow instances.
        That is, a SdrPageWindow might have an original, and a patched SdrPaintWindow instance - if
        this is the case, then the original SdrPaintWindow is examined before the patched one.
    */
    const SdrPageWindow* FindPatchedPageWindow( const OutputDevice& rOutDev ) const;

    void PaintOutlinerView(OutputDevice* pOut, const Rectangle& rRect) const;
private:
    SVX_DLLPRIVATE SdrPageWindow& CreateNewPageWindowEntry(SdrPaintWindow& rPaintWindow);

protected:
    void ImpInvalidateHelpLineArea(USHORT nNum) const;

protected:
    void SetLayer(const String& rName, SetOfByte& rBS, sal_Bool bJa);
    sal_Bool IsLayer(const String& rName, const SetOfByte& rBS) const;
    void SetAllLayers(SetOfByte& rB, sal_Bool bJa);

    virtual void SFX_NOTIFY(SfxBroadcaster& rBC, const TypeId& rBCType, const SfxHint& rHint, const TypeId& rHintType);

    // Nachsehen, ob AktGroup noch Inserted ist.
    void CheckAktGroup();

    void AdjHdl();

public:
    TYPEINFO();
    SdrPageView(SdrPage* pPage1, SdrView& rNewView);
    ~SdrPageView();

    // Wird von der PaintView gerufen, wenn Modelaenderungen abgeschlossen sind
    void ModelHasChanged();

    void Show();
    void Hide();

    void AddPaintWindowToPageView(SdrPaintWindow& rPaintWindow);
    void RemovePaintWindowFromPageView(SdrPaintWindow& rPaintWindow);

    SdrView& GetView() { return mrView; }
    const SdrView& GetView() const { return mrView; }

    /** looks up the control container belonging to given output device

        @return
            If the given output device belongs to one of the SdrPageViewWinRecs associated with this
            SdrPageView instance, the XControlContainer for this output device is returned, <NULL/>
            otherwise.
    */
    ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControlContainer >
        GetControlContainer( const OutputDevice& _rDevice ) const;

    /** sets all elements in the view which support a design and a alive mode into the given mode
    */
    void    SetDesignMode( bool _bDesignMode ) const;

    sal_Bool IsVisible() const { return mbVisible; }

    // Invalidiert den gesamten Bereich der Page
    void InvalidateAllWin();

    // rRect bezieht sich auf die Page
    void InvalidateAllWin(const Rectangle& rRect, sal_Bool bPlus1Pix=FALSE);

    // rReg bezieht sich auf's OutDev, nicht auf die Page
    void CompleteRedraw(
        SdrPaintWindow& rPaintWindow, const Region& rReg, sal_uInt16 nPaintMode,
        ::sdr::contact::ViewObjectContactRedirector* pRedirector = 0L) const;

    // write access to mpPreparedPageWindow
    void setPreparedPageWindow(SdrPageWindow* pKnownTarget);

    void DrawLayer(SdrLayerID nID, OutputDevice* pGivenTarget = 0L, sal_uInt16 nPaintMode = 0, ::sdr::contact::ViewObjectContactRedirector* pRedirector = 0L) const;
    void DrawPageViewGrid(OutputDevice& rOut, const Rectangle& rRect, Color aColor = Color( COL_BLACK ) );

    Rectangle GetPageRect() const;
    SdrPage* GetPage() const { return mpPage; }

    // Betretene Liste rausreichen
    SdrObjList* GetObjList() const { return pAktList; }

    // Betretene Gruppe rausreichen
    SdrObject* GetAktGroup() const { return pAktGroup; }

    // Betretene Gruppe und Liste setzen
    void SetAktGroupAndList(SdrObject* pNewGroup, SdrObjList* pNewList);

    sal_Bool HasMarkedObjPageView() const { return mbHasMarked; }
    void SetHasMarkedObj(sal_Bool bOn) { mbHasMarked = bOn; }

    const Rectangle& MarkBound() const { return aMarkBound; }
    const Rectangle& MarkSnap() const { return aMarkSnap; }
    Rectangle& MarkBound() { return aMarkBound; }
    Rectangle& MarkSnap() { return aMarkSnap; }

    void SetLayerVisible(const String& rName, sal_Bool bShow = sal_True) { SetLayer(rName, aLayerVisi, bShow); if(!bShow) AdjHdl(); InvalidateAllWin(); }
    sal_Bool IsLayerVisible(const String& rName) const { return IsLayer(rName, aLayerVisi); }
    void SetAllLayersVisible(sal_Bool bShow = sal_True) { SetAllLayers(aLayerVisi, bShow); if(!bShow) AdjHdl(); InvalidateAllWin(); }

    void SetLayerLocked(const String& rName, sal_Bool bLock = sal_True) { SetLayer(rName, aLayerLock, bLock); if(bLock) AdjHdl(); }
    sal_Bool IsLayerLocked(const String& rName) const { return IsLayer(rName,aLayerLock); }
    void SetAllLayersLocked(sal_Bool bLock = sal_True) { SetAllLayers(aLayerLock, bLock); if(bLock) AdjHdl(); }

    void SetLayerPrintable(const String& rName, sal_Bool bPrn = sal_True) { SetLayer(rName, aLayerPrn, bPrn); }
    sal_Bool IsLayerPrintable(const String& rName) const { return IsLayer(rName, aLayerPrn); }
    void SetAllLayersPrintable(sal_Bool bPrn = sal_True) { SetAllLayers(aLayerPrn, bPrn); }

    // PV stellt eine RefPage oder eine SubList eines RefObj dar oder Model ist ReadOnly
    sal_Bool IsReadOnly() const;

    // der Origin bezieht sich immer auf die obere linke Ecke der Page
    const Point& GetPageOrigin() const { return aPgOrg; }
    void SetPageOrigin(const Point& rOrg);

    void LogicToPagePos(Point& rPnt) const { rPnt-=aPgOrg; }
    void LogicToPagePos(Rectangle& rRect) const { rRect.Move(-aPgOrg.X(),-aPgOrg.Y()); }
    void PagePosToLogic(Point& rPnt) const { rPnt+=aPgOrg; }
    void PagePosToLogic(Rectangle& rRect) const { rRect.Move(aPgOrg.X(),aPgOrg.Y()); }

    void SetVisibleLayers(const SetOfByte& rSet) { aLayerVisi=rSet; InvalidateAllWin(); }
    const SetOfByte& GetVisibleLayers() const { return aLayerVisi; }
    void SetPrintableLayers(const SetOfByte& rSet) { aLayerPrn=rSet; }
    const SetOfByte& GetPrintableLayers() const { return aLayerPrn;  }
    void SetLockedLayers(const SetOfByte& rSet) { aLayerLock=rSet; }
    const SetOfByte& GetLockedLayers() const { return aLayerLock; }

    const SdrHelpLineList& GetHelpLines() const { return aHelpLines; }
    void SetHelpLines(const SdrHelpLineList& rHLL);
    //void SetHelpLinePos(USHORT nNum, const Point& rNewPos);
    void SetHelpLine(USHORT nNum, const SdrHelpLine& rNewHelpLine);
    void DeleteHelpLine(USHORT nNum);
    void InsertHelpLine(const SdrHelpLine& rHL, USHORT nNum=0xFFFF);
    void MoveHelpLine(USHORT nNum, USHORT nNewNum) { aHelpLines.Move(nNum,nNewNum); }

    // Liefert TRUE, wenn Layer des Obj sichtbar und nicht gesperrt.
    // Beim Gruppenobjekt muss wenigstens ein Member sichtbar sein,
    // gesperrt sein darf keiner.
    sal_Bool IsObjMarkable(SdrObject* pObj) const;

    // Betreten (Editieren) einer Objektgruppe. Anschliessend liegen alle
    // Memberobjekte der Gruppe im direkten Zugriff. Alle anderen Objekte
    // koennen waerendessen nicht bearbeitet werden (bis zum naechsten
    // LeaveGroup()). (wie MsDos chdir bla).
    sal_Bool EnterGroup(SdrObject* pObj);

    // Verlassen einer betretenen Objektgruppe. (wie MsDos chdir ..)
    void LeaveOneGroup();

    // Verlassen aller betretenen Objektgruppen. (wie MsDos chdir \)
    void LeaveAllGroup();

    // Feststellen, wie weit hinabgestiegen wurde (0=Root(Page))
    USHORT GetEnteredLevel() const;

    // Name der aktuellen Objektgruppe
    String GetActualGroupName() const;

    // Die Namen aller z.Zt. betretenen Gruppen
    String GetActualPathName(sal_Unicode cSep = sal_Unicode('|')) const;

    const basegfx::B2DPolyPolygon& getDragPoly0() const { return maDragPoly0; }
    const basegfx::B2DPolyPolygon& getDragPoly() const { return maDragPoly;  }
    void setDragPoly0(const basegfx::B2DPolyPolygon& rNew) { maDragPoly0 = rNew; }
    void setDragPoly(const basegfx::B2DPolyPolygon& rNew) { maDragPoly = rNew;  }

    // #103834# Set background color for svx at SdrPageViews
    void SetApplicationBackgroundColor(Color aBackgroundColor);

    // #109585#
    Color GetApplicationBackgroundColor() const;

    // #103911# Set/Get document color for svx at SdrPageViews
    void SetApplicationDocumentColor(Color aDocumentColor);
    Color GetApplicationDocumentColor() const;

    void SetCurrentPaintingDisplayInfo(const ::sdr::contact::DisplayInfo* pDisplayInfo)
    {
        if(pDisplayInfo != mpDisplayInfo)
        {
            mpDisplayInfo = pDisplayInfo;
        }
    }

    const ::sdr::contact::DisplayInfo* GetCurrentPaintingDisplayInfo() const
    {
        return mpDisplayInfo;
    }
};

////////////////////////////////////////////////////////////////////////////////////////////////////

#endif //_SVDPAGV_HXX
<commit_msg>INTEGRATION: CWS aw033 (1.3.84); FILE MERGED 2008/07/10 12:58:57 aw 1.3.84.4: #i39532# XOutputDevice removed, PrepareDelete removed 2008/05/14 13:56:26 aw 1.3.84.3: RESYNC: (1.3-1.4); FILE MERGED 2008/02/26 08:40:21 aw 1.3.84.2: removals, OLE, optimizations for primitives 2008/01/29 10:27:14 aw 1.3.84.1: updated refresh for ActionChanged(), diverse removals<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: svdpagv.hxx,v $
 * $Revision: 1.5 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#ifndef _SVDPAGV_HXX
#define _SVDPAGV_HXX

#include <com/sun/star/awt/XControlContainer.hpp>
#include <svtools/lstner.hxx>
#include <svx/svdhlpln.hxx>
#include <cppuhelper/implbase4.hxx>
#include <svx/svdsob.hxx>
#include <svx/svdtypes.hxx>
#include "svx/svxdllapi.h"

#include <cppuhelper/implbase3.hxx>
#include <vector>
#include <basegfx/polygon/b2dpolypolygon.hxx>

////////////////////////////////////////////////////////////////////////////////////////////////////

class Region;
class SdrObjList;
class SdrObject;
class SdrPage;
class SdrUnoObj;
class SdrPaintWindow;
class SdrView;
class SdrPageObj;
class B2dIAOManager;
class SdrPageView;

// #110094#
namespace sdr
{
    namespace contact
    {
        class ViewObjectContactRedirector;
        class DisplayInfo;
        class ViewObjectContactRedirector;
    } // end of namespace contact
} // end of namespace sdr

// typedefs for a list of SdrPageWindow
class SdrPageWindow;
typedef ::std::vector< SdrPageWindow* > SdrPageWindowVector;

////////////////////////////////////////////////////////////////////////////////////////////////////

class SVX_DLLPUBLIC SdrPageView : public SfxListener
{
protected:
    SdrView&                                                        mrView;
    SdrPage*                                                        mpPage;
    Point         aPgOrg;   // Nullpunkt der Page

    Rectangle     aMarkBound; // wird
    Rectangle     aMarkSnap;  // von
    basegfx::B2DPolyPolygon     maDragPoly0; // SdrView
    basegfx::B2DPolyPolygon     maDragPoly;  //
    sal_Bool                                                        mbHasMarked;
    sal_Bool                                                        mbVisible;

    SetOfByte    aLayerVisi;   // Menge der sichtbaren Layer
    SetOfByte    aLayerLock;   // Menge der nicht editierbaren Layer
    SetOfByte    aLayerPrn;    // Menge der druckbaren Layer

    SdrObjList*  pAktList;     // Aktuelle Liste, in der Regel die Page.
    SdrObject*   pAktGroup;    // Aktuelle Gruppe. NULL=Keine.

    SdrHelpLineList aHelpLines; // Hilfslinien und -punkte

    // #103911# Use one reserved slot (bReserveBool2) for the document color
    Color         maDocumentColor;

    // #103834# Use one reserved slot (bReserveBool1) for the background color
    Color         maBackgroundColor;

    SdrPageWindowVector                                         maPageWindows;

    // #i72752# member to remember with which SdrPageWindow the BeginDrawLayer
    // was done
    SdrPageWindow*                                              mpPreparedPageWindow;

    // interface to SdrPageWindow
protected:
    void ClearPageWindows();
    void AppendPageWindow(SdrPageWindow& rNew);
    SdrPageWindow* RemovePageWindow(sal_uInt32 nPos);
    SdrPageWindow* RemovePageWindow(SdrPageWindow& rOld);
public:
    sal_uInt32 PageWindowCount() const { return maPageWindows.size(); }
    SdrPageWindow* FindPageWindow( SdrPaintWindow& rPaintWindow ) const;
    SdrPageWindow* FindPageWindow( const OutputDevice& rOutDev ) const;
    SdrPageWindow* GetPageWindow(sal_uInt32 nIndex) const;

    /** finds the page window whose PaintWindow belongs to the given output device

        In opposite to FindPageWindow, this method also cares possibly patched PaintWindow instances.
        That is, a SdrPageWindow might have an original, and a patched SdrPaintWindow instance - if
        this is the case, then the original SdrPaintWindow is examined before the patched one.
    */
    const SdrPageWindow* FindPatchedPageWindow( const OutputDevice& rOutDev ) const;

    void PaintOutlinerView(OutputDevice* pOut, const Rectangle& rRect) const;
private:
    SVX_DLLPRIVATE SdrPageWindow& CreateNewPageWindowEntry(SdrPaintWindow& rPaintWindow);

protected:
    void ImpInvalidateHelpLineArea(USHORT nNum) const;

protected:
    void SetLayer(const String& rName, SetOfByte& rBS, sal_Bool bJa);
    sal_Bool IsLayer(const String& rName, const SetOfByte& rBS) const;
    void SetAllLayers(SetOfByte& rB, sal_Bool bJa);

    virtual void SFX_NOTIFY(SfxBroadcaster& rBC, const TypeId& rBCType, const SfxHint& rHint, const TypeId& rHintType);

    // Nachsehen, ob AktGroup noch Inserted ist.
    void CheckAktGroup();

    void AdjHdl();

public:
    TYPEINFO();
    SdrPageView(SdrPage* pPage1, SdrView& rNewView);
    ~SdrPageView();

    // Wird von der PaintView gerufen, wenn Modelaenderungen abgeschlossen sind
    void ModelHasChanged();

    void Show();
    void Hide();

    void AddPaintWindowToPageView(SdrPaintWindow& rPaintWindow);
    void RemovePaintWindowFromPageView(SdrPaintWindow& rPaintWindow);

    SdrView& GetView() { return mrView; }
    const SdrView& GetView() const { return mrView; }

    /** looks up the control container belonging to given output device

        @return
            If the given output device belongs to one of the SdrPageViewWinRecs associated with this
            SdrPageView instance, the XControlContainer for this output device is returned, <NULL/>
            otherwise.
    */
    ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControlContainer >
        GetControlContainer( const OutputDevice& _rDevice ) const;

    /** sets all elements in the view which support a design and a alive mode into the given mode
    */
    void    SetDesignMode( bool _bDesignMode ) const;

    sal_Bool IsVisible() const { return mbVisible; }

    // Invalidiert den gesamten Bereich der Page
    void InvalidateAllWin();

    // rRect bezieht sich auf die Page
    void InvalidateAllWin(const Rectangle& rRect, sal_Bool bPlus1Pix=FALSE);

    // PrePaint call forwarded from app windows
    void PrePaint();

    // rReg bezieht sich auf's OutDev, nicht auf die Page
    void CompleteRedraw(SdrPaintWindow& rPaintWindow, const Region& rReg, sdr::contact::ViewObjectContactRedirector* pRedirector = 0L) const;

    // write access to mpPreparedPageWindow
    void setPreparedPageWindow(SdrPageWindow* pKnownTarget);

    void DrawLayer(SdrLayerID nID, OutputDevice* pGivenTarget = 0, sdr::contact::ViewObjectContactRedirector* pRedirector = 0L) const;
    void DrawPageViewGrid(OutputDevice& rOut, const Rectangle& rRect, Color aColor = Color( COL_BLACK ) );

    Rectangle GetPageRect() const;
    SdrPage* GetPage() const { return mpPage; }

    // Betretene Liste rausreichen
    SdrObjList* GetObjList() const { return pAktList; }

    // Betretene Gruppe rausreichen
    SdrObject* GetAktGroup() const { return pAktGroup; }

    // Betretene Gruppe und Liste setzen
    void SetAktGroupAndList(SdrObject* pNewGroup, SdrObjList* pNewList);

    sal_Bool HasMarkedObjPageView() const { return mbHasMarked; }
    void SetHasMarkedObj(sal_Bool bOn) { mbHasMarked = bOn; }

    const Rectangle& MarkBound() const { return aMarkBound; }
    const Rectangle& MarkSnap() const { return aMarkSnap; }
    Rectangle& MarkBound() { return aMarkBound; }
    Rectangle& MarkSnap() { return aMarkSnap; }

    void SetLayerVisible(const String& rName, sal_Bool bShow = sal_True) { SetLayer(rName, aLayerVisi, bShow); if(!bShow) AdjHdl(); InvalidateAllWin(); }
    sal_Bool IsLayerVisible(const String& rName) const { return IsLayer(rName, aLayerVisi); }
    void SetAllLayersVisible(sal_Bool bShow = sal_True) { SetAllLayers(aLayerVisi, bShow); if(!bShow) AdjHdl(); InvalidateAllWin(); }

    void SetLayerLocked(const String& rName, sal_Bool bLock = sal_True) { SetLayer(rName, aLayerLock, bLock); if(bLock) AdjHdl(); }
    sal_Bool IsLayerLocked(const String& rName) const { return IsLayer(rName,aLayerLock); }
    void SetAllLayersLocked(sal_Bool bLock = sal_True) { SetAllLayers(aLayerLock, bLock); if(bLock) AdjHdl(); }

    void SetLayerPrintable(const String& rName, sal_Bool bPrn = sal_True) { SetLayer(rName, aLayerPrn, bPrn); }
    sal_Bool IsLayerPrintable(const String& rName) const { return IsLayer(rName, aLayerPrn); }
    void SetAllLayersPrintable(sal_Bool bPrn = sal_True) { SetAllLayers(aLayerPrn, bPrn); }

    // PV stellt eine RefPage oder eine SubList eines RefObj dar oder Model ist ReadOnly
    sal_Bool IsReadOnly() const;

    // der Origin bezieht sich immer auf die obere linke Ecke der Page
    const Point& GetPageOrigin() const { return aPgOrg; }
    void SetPageOrigin(const Point& rOrg);

    void LogicToPagePos(Point& rPnt) const { rPnt-=aPgOrg; }
    void LogicToPagePos(Rectangle& rRect) const { rRect.Move(-aPgOrg.X(),-aPgOrg.Y()); }
    void PagePosToLogic(Point& rPnt) const { rPnt+=aPgOrg; }
    void PagePosToLogic(Rectangle& rRect) const { rRect.Move(aPgOrg.X(),aPgOrg.Y()); }

    void SetVisibleLayers(const SetOfByte& rSet) { aLayerVisi=rSet; InvalidateAllWin(); }
    const SetOfByte& GetVisibleLayers() const { return aLayerVisi; }
    void SetPrintableLayers(const SetOfByte& rSet) { aLayerPrn=rSet; }
    const SetOfByte& GetPrintableLayers() const { return aLayerPrn;  }
    void SetLockedLayers(const SetOfByte& rSet) { aLayerLock=rSet; }
    const SetOfByte& GetLockedLayers() const { return aLayerLock; }

    const SdrHelpLineList& GetHelpLines() const { return aHelpLines; }
    void SetHelpLines(const SdrHelpLineList& rHLL);
    //void SetHelpLinePos(USHORT nNum, const Point& rNewPos);
    void SetHelpLine(USHORT nNum, const SdrHelpLine& rNewHelpLine);
    void DeleteHelpLine(USHORT nNum);
    void InsertHelpLine(const SdrHelpLine& rHL, USHORT nNum=0xFFFF);
    void MoveHelpLine(USHORT nNum, USHORT nNewNum) { aHelpLines.Move(nNum,nNewNum); }

    // Liefert TRUE, wenn Layer des Obj sichtbar und nicht gesperrt.
    // Beim Gruppenobjekt muss wenigstens ein Member sichtbar sein,
    // gesperrt sein darf keiner.
    sal_Bool IsObjMarkable(SdrObject* pObj) const;

    // Betreten (Editieren) einer Objektgruppe. Anschliessend liegen alle
    // Memberobjekte der Gruppe im direkten Zugriff. Alle anderen Objekte
    // koennen waerendessen nicht bearbeitet werden (bis zum naechsten
    // LeaveGroup()). (wie MsDos chdir bla).
    sal_Bool EnterGroup(SdrObject* pObj);

    // Verlassen einer betretenen Objektgruppe. (wie MsDos chdir ..)
    void LeaveOneGroup();

    // Verlassen aller betretenen Objektgruppen. (wie MsDos chdir \)
    void LeaveAllGroup();

    // Feststellen, wie weit hinabgestiegen wurde (0=Root(Page))
    USHORT GetEnteredLevel() const;

    // Name der aktuellen Objektgruppe
    String GetActualGroupName() const;

    // Die Namen aller z.Zt. betretenen Gruppen
    String GetActualPathName(sal_Unicode cSep = sal_Unicode('|')) const;

    const basegfx::B2DPolyPolygon& getDragPoly0() const { return maDragPoly0; }
    const basegfx::B2DPolyPolygon& getDragPoly() const { return maDragPoly;  }
    void setDragPoly0(const basegfx::B2DPolyPolygon& rNew) { maDragPoly0 = rNew; }
    void setDragPoly(const basegfx::B2DPolyPolygon& rNew) { maDragPoly = rNew;  }

    // #103834# Set background color for svx at SdrPageViews
    void SetApplicationBackgroundColor(Color aBackgroundColor);

    // #109585#
    Color GetApplicationBackgroundColor() const;

    // #103911# Set/Get document color for svx at SdrPageViews
    void SetApplicationDocumentColor(Color aDocumentColor);
    Color GetApplicationDocumentColor() const;
};

////////////////////////////////////////////////////////////////////////////////////////////////////

#endif //_SVDPAGV_HXX
<|endoftext|>


<commit_before>#pragma once

#include <QTimer>
#include <QSettings>
#include <QUrl>
#include "dvenums.hpp"

class QWindow;

class DVQmlCommunication : public QObject {
    Q_OBJECT

    /* Can only be read. */
    Q_PROPERTY(bool isLeft READ isLeft NOTIFY isLeftChanged)

    /* Can be read, written, and notifies when changed. */
    Q_PROPERTY(DVDrawMode::Type drawMode MEMBER m_drawMode READ drawMode WRITE setDrawMode NOTIFY drawModeChanged)
    Q_PROPERTY(bool anamorphicDualView MEMBER m_anamorphicDualView READ anamorphicDualView WRITE setAnamorphicDualView NOTIFY anamorphicDualViewChanged)

    Q_PROPERTY(bool mirrorLeft READ mirrorLeft WRITE setMirrorLeft NOTIFY mirrorLeftChanged)
    Q_PROPERTY(bool mirrorRight READ mirrorRight WRITE setMirrorRight NOTIFY mirrorRightChanged)

    Q_PROPERTY(qreal greyFac READ greyFac WRITE setGreyFac NOTIFY greyFacChanged)

    Q_PROPERTY(bool fullscreen READ fullscreen WRITE setFullscreen NOTIFY fullscreenChanged)

    Q_PROPERTY(QString pluginMode READ pluginMode WRITE setPluginMode NOTIFY pluginModeChanged)

    /* There is no WRITE function because you add or remove via addBookmark() and deleteBookmark(). */
    Q_PROPERTY(QStringList bookmarks READ bookmarks NOTIFY bookmarksChanged)

    /* By making this a property we can emit a signal when the list needs to be updated. */
    Q_PROPERTY(QStringList storageDevicePaths READ getStorageDevicePaths NOTIFY storageDevicePathsChanged)

    Q_PROPERTY(bool canGoBack READ canGoBack NOTIFY historyChanged)
    Q_PROPERTY(bool canGoForward READ canGoForward NOTIFY historyChanged)

public:
    /* Settings can be set from DVWindow. */
    QSettings settings;

    explicit DVQmlCommunication(QWindow* parent);

    /* Where QML reads the value of the current eye. */
    bool isLeft() const;

    /* Set the current eye. */
    void leftImage() { isLeftChanged(m_isLeft = true);  }
    void rightImage() { isLeftChanged(m_isLeft = false); }

    /* The current draw mode. */
    DVDrawMode::Type drawMode() const;
    void setDrawMode(DVDrawMode::Type mode);

    bool anamorphicDualView() const;
    void setAnamorphicDualView(bool anamorphic);

    bool mirrorLeft() const;
    void setMirrorLeft(bool mirror);

    bool mirrorRight() const;
    void setMirrorRight(bool mirror);

    qreal greyFac() const;
    void setGreyFac(qreal fac);

    bool fullscreen() const;
    void setFullscreen(bool fullscreen);

    QString pluginMode() const;
    void setPluginMode(QString mode);

    void addPluginModes(const QStringList& modes);
    Q_INVOKABLE QStringList getPluginModes() const;

    Q_INVOKABLE void addBookmark(QString bookmark);
    Q_INVOKABLE void deleteBookmark(QString bookmark);

    QStringList bookmarks() const;

    QStringList getStorageDevicePaths() const;

    Q_INVOKABLE bool fileExists(QString file) const;
    Q_INVOKABLE bool dirExists(QString dir) const;

    Q_INVOKABLE QUrl encodeURL(QString url) const;
    Q_INVOKABLE QString decodeURL(QUrl url) const;

    Q_INVOKABLE QString goBack();
    Q_INVOKABLE QString goForward();
    Q_INVOKABLE void pushHistory(QString value);
    bool canGoBack() const;
    bool canGoForward() const;

signals:
    void isLeftChanged(bool isLeft);
    void drawModeChanged(DVDrawMode::Type mode);
    void anamorphicDualViewChanged(bool anamorphicDualView);

    void mirrorLeftChanged(bool mirror);
    void mirrorRightChanged(bool mirror);

    void greyFacChanged(qreal fac);

    void fullscreenChanged(bool fullscreen);

    void pluginModeChanged(QString mode);

    void bookmarksChanged(QStringList bookmarks);

    void storageDevicePathsChanged();

    void historyChanged();

    /* Used for setting the cursor position. */
    void mouseMoved(const QPointF& pos);

    /* Used to show/hide ui based on touchscreen input. */
    /* TODO - Mabe some args would be useful? */
    void touchEvent();

public slots:
    void ownerWindowStateChanged(Qt::WindowState windowState);

private:
    bool m_mirrorLeft;
    bool m_mirrorRight;

    qreal m_greyFac;

    bool m_isLeft;
    DVDrawMode::Type m_drawMode;
    bool m_anamorphicDualView;

    QWindow* owner;

    QString m_pluginMode;
    QStringList pluginModes;

    QStringList m_bookmarks;

    QStringList browserHistory;
    int currentHistory;

    QTimer driveTimer;
};
<commit_msg>Add descriptions to some DVQmlCommunication members.<commit_after>#pragma once

#include <QTimer>
#include <QSettings>
#include <QUrl>
#include "dvenums.hpp"

class QWindow;

class DVQmlCommunication : public QObject {
    Q_OBJECT

    /* Can only be read. */
    Q_PROPERTY(bool isLeft READ isLeft NOTIFY isLeftChanged)

    /* Can be read, written, and notifies when changed. */
    Q_PROPERTY(DVDrawMode::Type drawMode MEMBER m_drawMode READ drawMode WRITE setDrawMode NOTIFY drawModeChanged)
    Q_PROPERTY(bool anamorphicDualView MEMBER m_anamorphicDualView READ anamorphicDualView WRITE setAnamorphicDualView NOTIFY anamorphicDualViewChanged)

    Q_PROPERTY(bool mirrorLeft READ mirrorLeft WRITE setMirrorLeft NOTIFY mirrorLeftChanged)
    Q_PROPERTY(bool mirrorRight READ mirrorRight WRITE setMirrorRight NOTIFY mirrorRightChanged)

    Q_PROPERTY(qreal greyFac READ greyFac WRITE setGreyFac NOTIFY greyFacChanged)

    Q_PROPERTY(bool fullscreen READ fullscreen WRITE setFullscreen NOTIFY fullscreenChanged)

    Q_PROPERTY(QString pluginMode READ pluginMode WRITE setPluginMode NOTIFY pluginModeChanged)

    /* There is no WRITE function because you add or remove via addBookmark() and deleteBookmark(). */
    Q_PROPERTY(QStringList bookmarks READ bookmarks NOTIFY bookmarksChanged)

    /* By making this a property we can emit a signal when the list needs to be updated. */
    Q_PROPERTY(QStringList storageDevicePaths READ getStorageDevicePaths NOTIFY storageDevicePathsChanged)

    Q_PROPERTY(bool canGoBack READ canGoBack NOTIFY historyChanged)
    Q_PROPERTY(bool canGoForward READ canGoForward NOTIFY historyChanged)

public:
    /* Settings can be set from DVWindow. */
    QSettings settings;

    explicit DVQmlCommunication(QWindow* parent);

    /* Where QML reads the value of the current eye. */
    bool isLeft() const;

    /* Set the current eye. */
    void leftImage() { isLeftChanged(m_isLeft = true);  }
    void rightImage() { isLeftChanged(m_isLeft = false); }

    /* The current draw mode. */
    DVDrawMode::Type drawMode() const;
    void setDrawMode(DVDrawMode::Type mode);

    bool anamorphicDualView() const;
    void setAnamorphicDualView(bool anamorphic);

    bool mirrorLeft() const;
    void setMirrorLeft(bool mirror);

    bool mirrorRight() const;
    void setMirrorRight(bool mirror);

    qreal greyFac() const;
    void setGreyFac(qreal fac);

    bool fullscreen() const;
    void setFullscreen(bool fullscreen);

    QString pluginMode() const;
    void setPluginMode(QString mode);

    void addPluginModes(const QStringList& modes);
    Q_INVOKABLE QStringList getPluginModes() const;

    Q_INVOKABLE void addBookmark(QString bookmark);
    Q_INVOKABLE void deleteBookmark(QString bookmark);

    QStringList bookmarks() const;

    /* Returns a list of strings describing mounted drives in the format: "mount path;display name". */
    QStringList getStorageDevicePaths() const;

    /* Seriously, why doesn't QML have these capabilities somewhere? */
    Q_INVOKABLE bool fileExists(QString file) const;
    Q_INVOKABLE bool dirExists(QString dir) const;

    /* Used by QML to convert local file strings to URLs and visa versa. */
    Q_INVOKABLE QUrl encodeURL(QString url) const;
    Q_INVOKABLE QString decodeURL(QUrl url) const;

    /* Decrement the current history item and return its value. Only call when canGoBack is true. */
    Q_INVOKABLE QString goBack();
    /* Increment the current history item and return its value. Only call when canGoBack is true. */
    Q_INVOKABLE QString goForward();

    /* Called whenever the file browser changes directories. If value is empty or the current history item nothing happens.
     * If it's the next one we go forward. If it's the previous one we go back. Otherwise we clear any forward history and add it at the end of the list. */
    Q_INVOKABLE void pushHistory(QString value);

    /* Is there a value to go back to? */
    bool canGoBack() const;
    /* Is there a value to go forward to? */
    bool canGoForward() const;

signals:
    void isLeftChanged(bool isLeft);
    void drawModeChanged(DVDrawMode::Type mode);
    void anamorphicDualViewChanged(bool anamorphicDualView);

    void mirrorLeftChanged(bool mirror);
    void mirrorRightChanged(bool mirror);

    void greyFacChanged(qreal fac);

    void fullscreenChanged(bool fullscreen);

    void pluginModeChanged(QString mode);

    void bookmarksChanged(QStringList bookmarks);

    void storageDevicePathsChanged();

    void historyChanged();

    /* Used for setting the cursor position. */
    void mouseMoved(const QPointF& pos);

    /* Used to show/hide ui based on touchscreen input. */
    /* TODO - Mabe some args would be useful? */
    void touchEvent();

public slots:
    void ownerWindowStateChanged(Qt::WindowState windowState);

private:
    bool m_mirrorLeft;
    bool m_mirrorRight;

    qreal m_greyFac;

    bool m_isLeft;
    DVDrawMode::Type m_drawMode;
    bool m_anamorphicDualView;

    QWindow* owner;

    QString m_pluginMode;
    QStringList pluginModes;

    QStringList m_bookmarks;

    QStringList browserHistory;
    int currentHistory;

    QTimer driveTimer;
};
<|endoftext|>


<commit_before>/**
 * @file llurlaction.cpp
 * @author Martin Reddy
 * @brief A set of actions that can performed on Urls
 *
 * $LicenseInfo:firstyear=2009&license=viewerlgpl$
 * Second Life Viewer Source Code
 * Copyright (C) 2010, Linden Research, Inc.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation;
 * version 2.1 of the License only.
 *
 * 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., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 *
 * Linden Research, Inc., 945 Battery Street, San Francisco, CA  94111  USA
 * $/LicenseInfo$
 */
#include "linden_common.h"

#include "llurlaction.h"
#include "llview.h"
#include "llwindow.h"
#include "llurlregistry.h"

// global state for the callback functions
LLUrlAction::url_callback_t 		LLUrlAction::sOpenURLCallback;
LLUrlAction::url_callback_t 		LLUrlAction::sOpenURLInternalCallback;
LLUrlAction::url_callback_t 		LLUrlAction::sOpenURLExternalCallback;
LLUrlAction::execute_url_callback_t LLUrlAction::sExecuteSLURLCallback;

void LLUrlAction::setOpenURLCallback(url_callback_t cb)
{
	sOpenURLCallback = cb;
}

void LLUrlAction::setOpenURLInternalCallback(url_callback_t cb)
{
	sOpenURLInternalCallback = cb;
}

void LLUrlAction::setOpenURLExternalCallback(url_callback_t cb)
{
	sOpenURLExternalCallback = cb;
}

void LLUrlAction::setExecuteSLURLCallback(execute_url_callback_t cb)
{
	sExecuteSLURLCallback = cb;
}

void LLUrlAction::openURL(std::string url)
{
	if (sOpenURLCallback)
	{
		sOpenURLCallback(url);
	}
}

void LLUrlAction::openURLInternal(std::string url)
{
	if (sOpenURLInternalCallback)
	{
		sOpenURLInternalCallback(url);
	}
}

void LLUrlAction::openURLExternal(std::string url)
{
	if (sOpenURLExternalCallback)
	{
		sOpenURLExternalCallback(url);
	}
}

void LLUrlAction::executeSLURL(std::string url)
{
	if (sExecuteSLURLCallback)
	{
		sExecuteSLURLCallback(url);
	}
}

void LLUrlAction::clickAction(std::string url)
{
	// Try to handle as SLURL first, then http Url
	if ( (sExecuteSLURLCallback) && !sExecuteSLURLCallback(url) )
	{
		if (sOpenURLCallback)
		{
			sOpenURLCallback(url);
		}
	}
}

void LLUrlAction::teleportToLocation(std::string url)
{
	LLUrlMatch match;
	if (LLUrlRegistry::instance().findUrl(url, match))
	{
		if (! match.getLocation().empty())
		{
			executeSLURL("secondlife:///app/teleport/" + match.getLocation());
		}
	}
}

void LLUrlAction::showLocationOnMap(std::string url)
{
	LLUrlMatch match;
	if (LLUrlRegistry::instance().findUrl(url, match))
	{
		if (! match.getLocation().empty())
		{
			executeSLURL("secondlife:///app/worldmap/" + match.getLocation());
		}
	}
}

void LLUrlAction::copyURLToClipboard(std::string url)
{
	LLView::getWindow()->copyTextToClipboard(utf8str_to_wstring(url));
}

void LLUrlAction::copyLabelToClipboard(std::string url)
{
	LLUrlMatch match;
	if (LLUrlRegistry::instance().findUrl(url, match))
	{
		LLView::getWindow()->copyTextToClipboard(utf8str_to_wstring(match.getLabel()));
	}
}

void LLUrlAction::showProfile(std::string url)
{
	// Get id from 'secondlife:///app/{cmd}/{id}/{action}'
	// and show its profile
	LLURI uri(url);
	LLSD path_array = uri.pathArray();
	if (path_array.size() == 4)
	{
		std::string id_str = path_array.get(2).asString();
		if (LLUUID::validate(id_str))
		{
			std::string cmd_str = path_array.get(1).asString();
			executeSLURL("secondlife:///app/" + cmd_str + "/" + id_str + "/about");
		}
	}
}

std::string LLUrlAction::getUserID(std::string url)
{
	LLURI uri(url);
	LLSD path_array = uri.pathArray();
	std::string id_str;
	if (path_array.size() == 4)
	{
		id_str = path_array.get(2).asString();
	}
	return id_str;
}

std::string LLUrlAction::getObjectId(std::string url)
{
	LLURI uri(url);
	LLSD path_array = uri.pathArray();
	std::string id_str;
	if (path_array.size() >= 3)
	{
		id_str = path_array.get(2).asString();
	}
	return id_str;
}

std::string LLUrlAction::getObjectName(std::string url)
{
	LLURI uri(url);
	LLSD query_map = uri.queryMap();
	std::string name;
	if (query_map.has("name"))
	{
		name = query_map["name"];
	}
	return name;
}

void LLUrlAction::sendIM(std::string url)
{
	std::string id_str = getUserID(url);
	if (LLUUID::validate(id_str))
	{
		executeSLURL("secondlife:///app/agent/" + id_str + "/im");
	}
}

void LLUrlAction::addFriend(std::string url)
{
	std::string id_str = getUserID(url);
	if (LLUUID::validate(id_str))
	{
		executeSLURL("secondlife:///app/agent/" + id_str + "/requestfriend");
	}
}

void LLUrlAction::removeFriend(std::string url)
{
	std::string id_str = getUserID(url);
	if (LLUUID::validate(id_str))
	{
		executeSLURL("secondlife:///app/agent/" + id_str + "/removefriend");
	}
}

void LLUrlAction::blockObject(std::string url)
{
	std::string object_id = getObjectId(url);
	std::string object_name = getObjectName(url);
	if (LLUUID::validate(object_id))
	{
		executeSLURL("secondlife:///app/agent/" + object_id + "/block/" + object_name);
	}
}
<commit_msg>build fix<commit_after>/**
 * @file llurlaction.cpp
 * @author Martin Reddy
 * @brief A set of actions that can performed on Urls
 *
 * $LicenseInfo:firstyear=2009&license=viewerlgpl$
 * Second Life Viewer Source Code
 * Copyright (C) 2010, Linden Research, Inc.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation;
 * version 2.1 of the License only.
 *
 * 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., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 *
 * Linden Research, Inc., 945 Battery Street, San Francisco, CA  94111  USA
 * $/LicenseInfo$
 */
#include "linden_common.h"

#include "llurlaction.h"
#include "llview.h"
#include "llwindow.h"
#include "llurlregistry.h"

// global state for the callback functions
LLUrlAction::url_callback_t 		LLUrlAction::sOpenURLCallback;
LLUrlAction::url_callback_t 		LLUrlAction::sOpenURLInternalCallback;
LLUrlAction::url_callback_t 		LLUrlAction::sOpenURLExternalCallback;
LLUrlAction::execute_url_callback_t LLUrlAction::sExecuteSLURLCallback;

void LLUrlAction::setOpenURLCallback(url_callback_t cb)
{
	sOpenURLCallback = cb;
}

void LLUrlAction::setOpenURLInternalCallback(url_callback_t cb)
{
	sOpenURLInternalCallback = cb;
}

void LLUrlAction::setOpenURLExternalCallback(url_callback_t cb)
{
	sOpenURLExternalCallback = cb;
}

void LLUrlAction::setExecuteSLURLCallback(execute_url_callback_t cb)
{
	sExecuteSLURLCallback = cb;
}

void LLUrlAction::openURL(std::string url)
{
	if (sOpenURLCallback)
	{
		sOpenURLCallback(url);
	}
}

void LLUrlAction::openURLInternal(std::string url)
{
	if (sOpenURLInternalCallback)
	{
		sOpenURLInternalCallback(url);
	}
}

void LLUrlAction::openURLExternal(std::string url)
{
	if (sOpenURLExternalCallback)
	{
		sOpenURLExternalCallback(url);
	}
}

void LLUrlAction::executeSLURL(std::string url)
{
	if (sExecuteSLURLCallback)
	{
		sExecuteSLURLCallback(url);
	}
}

void LLUrlAction::clickAction(std::string url)
{
	// Try to handle as SLURL first, then http Url
	if ( (sExecuteSLURLCallback) && !sExecuteSLURLCallback(url) )
	{
		if (sOpenURLCallback)
		{
			sOpenURLCallback(url);
		}
	}
}

void LLUrlAction::teleportToLocation(std::string url)
{
	LLUrlMatch match;
	if (LLUrlRegistry::instance().findUrl(url, match))
	{
		if (! match.getLocation().empty())
		{
			executeSLURL("secondlife:///app/teleport/" + match.getLocation());
		}
	}
}

void LLUrlAction::showLocationOnMap(std::string url)
{
	LLUrlMatch match;
	if (LLUrlRegistry::instance().findUrl(url, match))
	{
		if (! match.getLocation().empty())
		{
			executeSLURL("secondlife:///app/worldmap/" + match.getLocation());
		}
	}
}

void LLUrlAction::copyURLToClipboard(std::string url)
{
	LLView::getWindow()->copyTextToClipboard(utf8str_to_wstring(url));
}

void LLUrlAction::copyLabelToClipboard(std::string url)
{
	LLUrlMatch match;
	if (LLUrlRegistry::instance().findUrl(url, match))
	{
		LLView::getWindow()->copyTextToClipboard(utf8str_to_wstring(match.getLabel()));
	}
}

void LLUrlAction::showProfile(std::string url)
{
	// Get id from 'secondlife:///app/{cmd}/{id}/{action}'
	// and show its profile
	LLURI uri(url);
	LLSD path_array = uri.pathArray();
	if (path_array.size() == 4)
	{
		std::string id_str = path_array.get(2).asString();
		if (LLUUID::validate(id_str))
		{
			std::string cmd_str = path_array.get(1).asString();
			executeSLURL("secondlife:///app/" + cmd_str + "/" + id_str + "/about");
		}
	}
}

std::string LLUrlAction::getUserID(std::string url)
{
	LLURI uri(url);
	LLSD path_array = uri.pathArray();
	std::string id_str;
	if (path_array.size() == 4)
	{
		id_str = path_array.get(2).asString();
	}
	return id_str;
}

std::string LLUrlAction::getObjectId(std::string url)
{
	LLURI uri(url);
	LLSD path_array = uri.pathArray();
	std::string id_str;
	if (path_array.size() >= 3)
	{
		id_str = path_array.get(2).asString();
	}
	return id_str;
}

std::string LLUrlAction::getObjectName(std::string url)
{
	LLURI uri(url);
	LLSD query_map = uri.queryMap();
	std::string name;
	if (query_map.has("name"))
	{
		name = query_map["name"].asString();
	}
	return name;
}

void LLUrlAction::sendIM(std::string url)
{
	std::string id_str = getUserID(url);
	if (LLUUID::validate(id_str))
	{
		executeSLURL("secondlife:///app/agent/" + id_str + "/im");
	}
}

void LLUrlAction::addFriend(std::string url)
{
	std::string id_str = getUserID(url);
	if (LLUUID::validate(id_str))
	{
		executeSLURL("secondlife:///app/agent/" + id_str + "/requestfriend");
	}
}

void LLUrlAction::removeFriend(std::string url)
{
	std::string id_str = getUserID(url);
	if (LLUUID::validate(id_str))
	{
		executeSLURL("secondlife:///app/agent/" + id_str + "/removefriend");
	}
}

void LLUrlAction::blockObject(std::string url)
{
	std::string object_id = getObjectId(url);
	std::string object_name = getObjectName(url);
	if (LLUUID::validate(object_id))
	{
		executeSLURL("secondlife:///app/agent/" + object_id + "/block/" + object_name);
	}
}
<|endoftext|>