<commit_before>/*ibnu.yahya@toroo.org*/
#include <QtWidgets/QApplication>
#include "ign.h"
#include <QtWebKitWidgets/QWebView>
#include <QFileDialog>
#include <iostream>
#include <getopt.h>
using namespace std;
int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    ign w;
    static int verbose_flag;
    char *url = NULL;
    char *optional = NULL;
    bool dev = false;
    bool file = false;
    int index;
    int c;
    bool version = false;
    char help[] = "Usage: ignsdk -p [PROJECT DIRECTORY]\n\nGeneral Options :\n--version\toutput version information and exit\n--dev\t\tWeb Inspector Enable\n\nWindow options :\n--transparent\tTransparent Mode\n--noFrame\tFrame Disable\n";
    opterr = 0;
    static struct option long_options[] =
                 {
                   {"verbose", no_argument,       &verbose_flag, 1},
                   {"brief",   no_argument,       &verbose_flag, 0},
                   {"dev",     no_argument,       0, 'd'},
                   {"file",     required_argument,       0, 'f'},
                   {"transparent",  no_argument,       0, 't'},
                   {"noFrame",  no_argument,       0, 'n'},
                   {"help",  no_argument,       0, 'h'},
                   {"project",      required_argument, 0, 'p'},
                   {"version",  no_argument,       0, 'v'},
                   {0, 0, 0, 0}
                 };

               int option_index = 0;

           while ((c = getopt_long (argc, argv, "vdnhf:tp:",long_options,&option_index)) != -1){
             switch (c)
               {
               case 'p':
                 url = optarg;
                 break;
               case 'd':
                 dev = true;
                  w.setDev(dev);
                 break;
               case 'f':
                file = true;
                optional = optarg;
               break;
               case 'n':
                 w.widgetNoFrame();
               break;
               case 't':
                 w.widgetTransparent();
               break;
               case 'v':
                 version = true;
               break;
               case 'h':
                 printf("%s\n",help);
                 exit(0);
               break;
               case '?':
                 if (optopt == 'c')
                   fprintf (stderr, "Option -%c requires an argument.\n", optopt);
                 else if (isprint (optopt))
                   fprintf (stderr, "Unknown option `-%c'.\n\nUsage: ignsdk -p [PROJECT DIRECTORY]\n\nGeneral Options :\n--version\toutput version information and exit\n--dev\t\tWeb Inspector Enable\n\nWindow options :\n--transparent\tTransparent Mode\n--noFrame\tFrame Disable\n", optopt);
                 else
                   fprintf (stderr,
                            "Unknown option character `\\x%x'.\n",
                            optopt);
                 return 1;
               default:
                 abort ();
               }
           }

    for (index = optind; index < argc; index++){
       printf ("Non-option argument %s\n", argv[index]);
    }

    if(version){
        qDebug() << "IGNSDK Version : "<< w.sdkVersion();
        exit(0);
    }

    QString opt = url;
    QString path = url;
    if(!opt.isEmpty()){
        w.pathApp = opt;
        /*icon set*/
        a.setWindowIcon(QIcon(path+"icons/app.png"));

        if(file){
            opt += "/";
            opt += optional;
        }
        else {
            opt += "/index.html";
        }

        w.render(opt);
        w.config(url);
        w.show();

    }
    else{
        QFileDialog *fd = new QFileDialog;
        QTreeView *tree = fd->findChild <QTreeView*>();
        tree->setRootIsDecorated(true);
        tree->setItemsExpandable(true);
        fd->setFileMode(QFileDialog::Directory);
        fd->setOption(QFileDialog::ShowDirsOnly);
        fd->setViewMode(QFileDialog::Detail);
        int result = fd->exec();
        QString directory;
        if (result)
        {
            directory = fd->selectedFiles()[0];
            w.render(directory+"/index.html");
            w.config(directory);
            w.show();
        }
        else {
            w.render("http://www.igos-nusantara.or.id");
            w.show();
        }
    }

    return a.exec();
}
<commit_msg>ADD: option for remote debugging<commit_after>/*ibnu.yahya@toroo.org*/
#include <QtWidgets/QApplication>
#include "ign.h"
#include <QtWebKitWidgets/QWebView>
#include <QFileDialog>
#include <iostream>
#include <getopt.h>
using namespace std;
int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    ign w;
    static int verbose_flag;
    char *url = NULL;
    char *optional = NULL;
    bool dev = false;
    bool file = false;
    int index;
    int c;
    int r;
    bool version = false;
    char help[] = "Usage: ignsdk -p [PROJECT DIRECTORY]\n\nGeneral Options :\n-v\t--version\t\toutput version information and exit\n-d\t--dev\t\t\tWeb Inspector Enable\n-r\t--dev-remote [port]\tRemote debugging\n\nWindow options :\n--transparent\tTransparent Mode\n--noFrame\tFrame Disable\n";
    opterr = 0;
    static struct option long_options[] =
                 {
                   {"verbose", no_argument,       &verbose_flag, 1},
                   {"brief",   no_argument,       &verbose_flag, 0},
                   {"dev",     no_argument,       0, 'd'},
                   {"file",     required_argument,       0, 'f'},
                   {"transparent",  no_argument,       0, 't'},
                   {"noFrame",  no_argument,       0, 'n'},
                   {"help",  no_argument,       0, 'h'},
                   {"project",      required_argument, 0, 'p'},
                   {"dev-remote",      required_argument, 0, 'r'},
                   {"version",  no_argument,       0, 'v'},
                   {0, 0, 0, 0}
                 };

               int option_index = 0;

           while ((c = getopt_long (argc, argv, "vdnhf:tp:r:",long_options,&option_index)) != -1){
             switch (c)
               {
               case 'p':
                 url = optarg;
                 break;
               case 'd':
                 dev = true;
                  w.setDev(dev);
                 break;
               case 'f':
                file = true;
                optional = optarg;
               break;
               case 'r':
                r = atoi(optarg);
                w.setDevRemote(r);
               break;
               case 'n':
                 w.widgetNoFrame();
               break;
               case 't':
                 w.widgetTransparent();
               break;
               case 'v':
                 version = true;
               break;
               case 'h':
                 printf("%s\n",help);
                 exit(0);
               break;
               case '?':
                 if (optopt == 'c')
                   fprintf (stderr, "Option -%c requires an argument.\n", optopt);
                 else if (isprint (optopt))
                   fprintf (stderr, "Unknown option `-%c'.\n\nUsage: ignsdk -p [PROJECT DIRECTORY]\n\nGeneral Options :\n-v\t--version\t\toutput version information and exit\n-d\t--dev\t\t\tWeb Inspector Enable\n-r\t--dev-remote [port]\tRemote debugging\n\nWindow options :\n--transparent\tTransparent Mode\n--noFrame\tFrame Disable\n", optopt);
                 else
                   fprintf (stderr,
                            "Unknown option character `\\x%x'.\n",
                            optopt);
                 return 1;
               default:
                 abort ();
               }
           }

    for (index = optind; index < argc; index++){
       printf ("Non-option argument %s\n", argv[index]);
    }

    if(version){
        qDebug() << "IGNSDK Version : "<< w.sdkVersion();
        exit(0);
    }

    QString opt = url;
    QString path = url;
    if(!opt.isEmpty()){
        w.pathApp = opt;
        /*icon set*/
        a.setWindowIcon(QIcon(path+"icons/app.png"));

        if(file){
            opt += "/";
            opt += optional;
        }
        else {
            opt += "/index.html";
        }

        w.render(opt);
        w.config(url);
        w.show();

    }
    else{
        QFileDialog *fd = new QFileDialog;
        QTreeView *tree = fd->findChild <QTreeView*>();
        tree->setRootIsDecorated(true);
        tree->setItemsExpandable(true);
        fd->setFileMode(QFileDialog::Directory);
        fd->setOption(QFileDialog::ShowDirsOnly);
        fd->setViewMode(QFileDialog::Detail);
        int result = fd->exec();
        QString directory;
        if (result)
        {
            directory = fd->selectedFiles()[0];
            w.render(directory+"/index.html");
            w.config(directory);
            w.show();
        }
        else {
            w.render("http://www.igos-nusantara.or.id");
            w.show();
        }
    }

    return a.exec();
}
<|endoftext|>


<commit_before>bbc9cfe1-2747-11e6-9079-e0f84713e7b8<commit_msg>NO CHANGES<commit_after>bbf0080c-2747-11e6-813a-e0f84713e7b8<|endoftext|>


<commit_before>9cb3fd6e-4b02-11e5-94c5-28cfe9171a43<commit_msg>oh my, I hate charles<commit_after>9cc2517a-4b02-11e5-9a48-28cfe9171a43<|endoftext|>


<commit_before>6f62d4ae-2749-11e6-a1a4-e0f84713e7b8<commit_msg>compiles now<commit_after>6fa0ff57-2749-11e6-a315-e0f84713e7b8<|endoftext|>


<commit_before>d4361c8c-2747-11e6-ac20-e0f84713e7b8<commit_msg>Did ANOTHER thing<commit_after>d44136ee-2747-11e6-9db2-e0f84713e7b8<|endoftext|>


<commit_before>// main.cpp

#include <iostream>
#include <iomanip>
#include <fstream>
#include <vector>
#include <string>
#include <map>
#include <ctime>
#include <chrono>
#include <cstdlib>
#include <cassert>

typedef long myint;

// this definition does not work properly for tabs, newlines etc.
//#define isspace_fast(x) ((x) == ' ')

// "C" locale compatible definition
#define isspace_fast(x) ((x) == ' ' || (x) == '\t' || (x) == '\n' || (x) == '\v' || (x) == '\f' || (x) == '\r')

myint atoisimple(const char *b)
{
    myint res = 0; // Initialize result
    int sgn = 1;

    // Skip whitespace
    for (; isspace_fast(*b); ++b);

    if (*b == '-')
    {
        sgn = -1;
        ++b;
    }
    else if (*b == '+')
    {
        ++b;
    }

    // Iterate through all characters of input string and update result
    for (; *b != 0; ++b)
    {
        if (*b < '0' || *b > '9')
        {
            return sgn * res;
        }
        res = res * 10 + *b - '0';
    }

    // return result.
    return sgn * res;
}

myint fastatoi(const char *b)
{
    myint res = 0; // Initialize result
    int sgn = 1;

    // Skip whitespace
    for (; isspace_fast(*b); ++b);

    if (*b == '-')
    {
        sgn = -1;
        ++b;
    }
    else if (*b == '+')
    {
        ++b;
    }

    // Iterate through all characters of input string and update result
    for (; *b != 0; ++b)
    {
        unsigned d = static_cast<unsigned>(*b) - '0';
        if (d > 9)
        {
            return sgn * res;
        }
        res = res * 10 + d;
    }

    // return result.
    return sgn * res;
}

myint fastatoiadd(const char *b)
{
    myint res = 0; // Initialize result

    // Skip whitespace
    for (; isspace_fast(*b); ++b);

    if (*b == '-')
    {
        ++b;
        // Iterate through all characters of input string and update result
        for (; ; ++b)
        {
            unsigned d = static_cast<unsigned>(*b) - '0';
            if (d > 9)
            {
                return res;
            }
            res = res * 10 - d;
        }

    }
    else if (*b == '+')
    {
        ++b;
    }

    // Iterate through all characters of input string and update result
    for (; ; ++b)
    {
        unsigned d = static_cast<unsigned>(*b) - '0';
        if (d > 9)
        {
            return res;
        }
        res = res * 10 + d;
    }

    //  unreachable
    return res;
}

myint fastatoiaddunr(const char *b)
{
    myint res = 0; // Initialize result

    // Skip whitespace
    for (; isspace_fast(*b); ++b);

    if (*b == '-')
    {
        ++b;
        unsigned d = static_cast<unsigned>(*b) - '0';
        if (d > 9)
        {
            return 0;
        }
        res = -static_cast<myint>(d);
        ++b;

        // Iterate through all characters of input string and update result
        for (; ; ++b)
        {
            unsigned d = static_cast<unsigned>(*b) - '0';
            if (d > 9)
            {
                return res;
            }
            res = res * 10 - d;
        }

    }
    else if (*b == '+')
    {
        ++b;
    }

    unsigned d = static_cast<unsigned>(*b) - '0';
    if (d > 9)
    {
        return 0;
    }
    res = d;
    ++b;

    // Iterate through all characters of input string and update result
    for (; ; ++b)
    {
        unsigned d = static_cast<unsigned>(*b) - '0';
        if (d > 9)
        {
            return res;
        }
        res = res * 10 + d;
    }

    //  unreachable
    return res;
}

myint zero(const char *b)
{
    volatile myint res = (*b == 0); // Initialize result

    // return result.
    return res;
}

typedef std::map<std::string, unsigned long long> Name2Time;

template <typename F>
void test(unsigned long rep,
          F f,
          const std::vector<std::string>& v,
          Name2Time& best,
          const std::string& name)
{
    try
    {
        const char* b = 0;

        myint r = 0;
        auto et0 = std::chrono::system_clock::now();
        std::clock_t t0 = std::clock();
        for (unsigned int i = 0; i < rep; ++i)
        {
            unsigned int ii = i % v.size();
            b = v[ii].c_str();
            r += f(b);
        }
        std::clock_t t = std::clock();
        auto et = std::chrono::system_clock::now() - et0;

        std::cout << name << ":" << std::setw(18) << r << "," <<
                     std::setw(10) << t - t0 << ", " <<
                     std::setw(10) << et.count() << std::endl;
        if (name.length() > 0)
        {
          std::string ename = "e." + name;
          std::string cname = "c." + name;
          auto bt = best[ename];
          if (bt == 0 || bt > et.count()) { best[ename] = et.count(); }
          bt = best[cname];
          if (bt == 0 || bt > t - t0) { best[cname] = t - t0; }
        }
    }
    catch(std::exception& exc)
    {
        std::cout << "ERROR" << std::endl;
    }
}

void unit_test()
{
    std::vector<myint (*)(const char *)> v = { atoisimple, fastatoi, fastatoiadd, fastatoiaddunr };
    std::vector<std::string> sv = { "0", " 1", " 2", "\t 3", "4x", "5%",
                                    "  10  ", " 99.", "100", "12345", "999999",
                                    "-1", " -2x", "   +123456+", " -345", "\n\v8I",
                                    " fake", "values", " +", "    zero  "};
    for (auto pf : v)
    {
       for (const auto s: sv)
       {
           assert((*pf)(s.c_str()) == atoi(s.c_str()));
       }
    }
}

void generate_add(std::vector<std::string>& v, int count, int length, bool digits_only)
{
    for (unsigned i = 0; i < count; ++i)
    {
        std::string s;
        for (unsigned j = 0; j < length; ++j)
        {
            s += '0' + (i + j * 7) % 10;
        }

        int mode = digits_only ? 0 : (i % 5);

        switch (mode)
        {
          case 0:
             v.push_back(s);
             break;
          case 1:
             v.push_back('-' + s);
             break;
          case 2:
              v.push_back('+' + s);
             break;
          case 3:
             v.push_back("    -" + s + ")))");
             break;
          case 4:
             v.push_back("    +" + s + ".12");
             break;
        }

    }
}

int main(int argc, char* argv[])
{
    unsigned MAX_WORD_LEN = 8;
    unsigned long N = 10000000UL;
    unsigned WORD_COUNT = 10000;
    bool digits_only = false;
    std::string out_filename = "";

    std::vector<std::string> args(argv, argv + argc);
    int i = 1;
    while (i < args.size())
    {
        if (args[i] == "-t" || args[i] == "--unittest")
        {
            unit_test();
            return 0;
        }
        if (args[i] == "-d" || args[i] == "--digitsonly")
        {
            digits_only = true;
        }
        if ((args[i] == "-l" || args[i] == "--length") &&
            i < args.size())
        {
            if ((MAX_WORD_LEN = atoi(args[i + 1].c_str())) > 20 || MAX_WORD_LEN == 0)
            {
                std::cerr << "Invalid length" << std::endl;
                return 1;
            }
            i++;
        }
        if ((args[i] == "-w" || args[i] == "--words") &&
            i < args.size())
        {
            if ((WORD_COUNT = atol(args[i + 1].c_str())) > 1000000 || WORD_COUNT == 0)
            {
                std::cerr << "Invalid word count" << std::endl;
                return 1;
            }
            i++;
        }
        if ((args[i] == "-n" || args[i] == "--numloops") &&
            i < args.size())
        {
            if ((N = atol(args[i + 1].c_str())) > 1000000000000UL || N == 0)
            {
                std::cerr << "Invalid number of loops" << std::endl;
                return 1;
            }
            i++;
        }
        if ((args[i] == "-o" || args[i] == "--output") &&
            i < args.size())
        {
            out_filename = args[i + 1];
            i++;
        }

        i++;
    }

    for (size_t L = 1; L <= MAX_WORD_LEN; ++L)
    {

      Name2Time best;
      std::vector<std::string> v;
      generate_add(v, WORD_COUNT, L, digits_only);

      std::cout << "Digits per number: " << L << " The string contains"<< (digits_only ? " digits only" : " whitespace and sign" )<< std::endl;
      std::cout << "Int size in bytes:" << sizeof(myint) << std::endl;
      std::cout << "Loops:" << N << std::endl;
      std::cout << "Words:" << WORD_COUNT << std::endl;
      std::cout << "Ramp up:" << std::endl;
      test(N, atoi, v, best, "");

      for (int i = 0; i < 3; ++i)
      {
          test(N, zero, v, best,            "zero..........");
          test(N, atoi, v, best,            "atoi..........");
          test(N, atoisimple, v, best,      "atoisimple....");
          test(N, fastatoi, v, best,        "fastatoi......");
          test(N, fastatoiadd, v, best,     "fastatoiadd...");
          test(N, fastatoiaddunr, v, best,  "fastatoiaddunr");
      }

      for (auto& kv : best)
      {
        std::cout << "Best: " << kv.first << " : " << std::setw(11) << kv.second << std::endl;
      }

      if (out_filename.length() > 0)
      {
        std::ofstream f(out_filename.c_str(), std::ios::app | std::ios::out);
        if (!f.fail())
        {
          for (auto& kv : best)
          {
            f << L << "," << (digits_only ? "DO" : "WS" ) << "," << kv.first << "," << kv.second << std::endl;
          }
        }
      }
      else
      {
        std::cout << "No output file param" << std::endl;
      }

    }

    return 0;
}

<commit_msg>Improve formatting<commit_after>// main.cpp

#include <iostream>
#include <iomanip>
#include <fstream>
#include <vector>
#include <string>
#include <map>
#include <ctime>
#include <chrono>
#include <cstdlib>
#include <cassert>

typedef long myint;

// this definition does not work properly for tabs, newlines etc.
//#define isspace_fast(x) ((x) == ' ')

// "C" locale compatible definition
#define isspace_fast(x) ((x) == ' ' || (x) == '\t' || (x) == '\n' || (x) == '\v' || (x) == '\f' || (x) == '\r')

myint atoisimple(const char *b)
{
    myint res = 0; // Initialize result
    int sgn = 1;

    // Skip whitespace
    for (; isspace_fast(*b); ++b);

    if (*b == '-')
    {
        sgn = -1;
        ++b;
    }
    else if (*b == '+')
    {
        ++b;
    }

    // Iterate through all characters of input string and update result
    for (; *b != 0; ++b)
    {
        if (*b < '0' || *b > '9')
        {
            return sgn * res;
        }
        res = res * 10 + *b - '0';
    }

    // return result.
    return sgn * res;
}

myint fastatoi(const char *b)
{
    myint res = 0; // Initialize result
    int sgn = 1;

    // Skip whitespace
    for (; isspace_fast(*b); ++b);

    if (*b == '-')
    {
        sgn = -1;
        ++b;
    }
    else if (*b == '+')
    {
        ++b;
    }

    // Iterate through all characters of input string and update result
    for (; *b != 0; ++b)
    {
        unsigned d = static_cast<unsigned>(*b) - '0';
        if (d > 9)
        {
            return sgn * res;
        }
        res = res * 10 + d;
    }

    // return result.
    return sgn * res;
}

myint fastatoiadd(const char *b)
{
    myint res = 0; // Initialize result

    // Skip whitespace
    for (; isspace_fast(*b); ++b);

    if (*b == '-')
    {
        ++b;
        // Iterate through all characters of input string and update result
        for (; ; ++b)
        {
            unsigned d = static_cast<unsigned>(*b) - '0';
            if (d > 9)
            {
                return res;
            }
            res = res * 10 - d;
        }

    }
    else if (*b == '+')
    {
        ++b;
    }

    // Iterate through all characters of input string and update result
    for (; ; ++b)
    {
        unsigned d = static_cast<unsigned>(*b) - '0';
        if (d > 9)
        {
            return res;
        }
        res = res * 10 + d;
    }

    //  unreachable
    return res;
}

myint fastatoiaddunr(const char *b)
{
    myint res = 0; // Initialize result

    // Skip whitespace
    for (; isspace_fast(*b); ++b);

    if (*b == '-')
    {
        ++b;
        unsigned d = static_cast<unsigned>(*b) - '0';
        if (d > 9)
        {
            return 0;
        }
        res = -static_cast<myint>(d);
        ++b;

        // Iterate through all characters of input string and update result
        for (; ; ++b)
        {
            unsigned d = static_cast<unsigned>(*b) - '0';
            if (d > 9)
            {
                return res;
            }
            res = res * 10 - d;
        }

    }
    else if (*b == '+')
    {
        ++b;
    }

    unsigned d = static_cast<unsigned>(*b) - '0';
    if (d > 9)
    {
        return 0;
    }
    res = d;
    ++b;

    // Iterate through all characters of input string and update result
    for (; ; ++b)
    {
        unsigned d = static_cast<unsigned>(*b) - '0';
        if (d > 9)
        {
            return res;
        }
        res = res * 10 + d;
    }

    //  unreachable
    return res;
}

myint zero(const char *b)
{
    volatile myint res = (*b == 0); // Initialize result

    // return result.
    return res;
}

typedef std::map<std::string, unsigned long long> Name2Time;

template <typename F>
void test(unsigned long rep,
          F f,
          const std::vector<std::string>& v,
          Name2Time& best,
          const std::string& name)
{
    try
    {
        const char* b = 0;

        myint r = 0;
        auto et0 = std::chrono::system_clock::now();
        std::clock_t t0 = std::clock();
        for (unsigned int i = 0; i < rep; ++i)
        {
            unsigned int ii = i % v.size();
            b = v[ii].c_str();
            r += f(b);
        }
        std::clock_t t = std::clock();
        auto et = std::chrono::system_clock::now() - et0;

        std::cout << name << ":" << std::setw(18) << r << "," <<
                     std::setw(10) << t - t0 << ", " <<
                     std::setw(10) << et.count() << std::endl;
        if (name.length() > 0)
        {
            std::string ename = "e." + name;
            std::string cname = "c." + name;
            auto bt = best[ename];
            if (bt == 0 || bt > et.count()) { best[ename] = et.count(); }
            bt = best[cname];
            if (bt == 0 || bt > t - t0) { best[cname] = t - t0; }
        }
    }
    catch(std::exception& exc)
    {
        std::cout << "ERROR" << std::endl;
    }
}

void unit_test()
{
    std::vector<myint (*)(const char *)> v = { atoisimple, fastatoi, fastatoiadd, fastatoiaddunr };
    std::vector<std::string> sv = { "0", " 1", " 2", "\t 3", "4x", "5%",
                                    "  10  ", " 99.", "100", "12345", "999999",
                                    "-1", " -2x", "   +123456+", " -345", "\n\v8I",
                                    " fake", "values", " +", "    zero  "};
    for (auto pf : v)
    {
       for (const auto s: sv)
       {
           assert((*pf)(s.c_str()) == atoi(s.c_str()));
       }
    }
}

void generate_add(std::vector<std::string>& v, int count, int length, bool digits_only)
{
    for (unsigned i = 0; i < count; ++i)
    {
        std::string s;
        for (unsigned j = 0; j < length; ++j)
        {
            s += '0' + (i + j * 7) % 10;
        }

        int mode = digits_only ? 0 : (i % 5);

        switch (mode)
        {
          case 0:
             v.push_back(s);
             break;
          case 1:
             v.push_back('-' + s);
             break;
          case 2:
              v.push_back('+' + s);
             break;
          case 3:
             v.push_back("    -" + s + ")))");
             break;
          case 4:
             v.push_back("    +" + s + ".12");
             break;
        }

    }
}

int main(int argc, char* argv[])
{
    unsigned MAX_WORD_LEN = 8;
    unsigned long N = 10000000UL;
    unsigned WORD_COUNT = 10000;
    bool digits_only = false;
    std::string out_filename = "";

    std::vector<std::string> args(argv, argv + argc);
    int i = 1;
    while (i < args.size())
    {
        if (args[i] == "-t" || args[i] == "--unittest")
        {
            unit_test();
            return 0;
        }
        if (args[i] == "-d" || args[i] == "--digitsonly")
        {
            digits_only = true;
        }
        if ((args[i] == "-l" || args[i] == "--length") &&
            i < args.size())
        {
            if ((MAX_WORD_LEN = atoi(args[i + 1].c_str())) > 20 || MAX_WORD_LEN == 0)
            {
                std::cerr << "Invalid length" << std::endl;
                return 1;
            }
            i++;
        }
        if ((args[i] == "-w" || args[i] == "--words") &&
            i < args.size())
        {
            if ((WORD_COUNT = atol(args[i + 1].c_str())) > 1000000 || WORD_COUNT == 0)
            {
                std::cerr << "Invalid word count" << std::endl;
                return 1;
            }
            i++;
        }
        if ((args[i] == "-n" || args[i] == "--numloops") &&
            i < args.size())
        {
            if ((N = atol(args[i + 1].c_str())) > 1000000000000UL || N == 0)
            {
                std::cerr << "Invalid number of loops" << std::endl;
                return 1;
            }
            i++;
        }
        if ((args[i] == "-o" || args[i] == "--output") &&
            i < args.size())
        {
            out_filename = args[i + 1];
            i++;
        }

        i++;
    }

    for (size_t L = 1; L <= MAX_WORD_LEN; ++L)
    {

        Name2Time best;
        std::vector<std::string> v;
        generate_add(v, WORD_COUNT, L, digits_only);

        std::cout << "Digits per number: " << L << " The string contains"
                  << (digits_only ? " digits only" : " whitespace and sign" ) << std::endl;
        std::cout << "Int size in bytes:" << sizeof(myint) << std::endl;
        std::cout << "Loops:" << N << std::endl;
        std::cout << "Words:" << WORD_COUNT << std::endl;
        std::cout << "Ramp up:" << std::endl;
        test(N, atoi, v, best, "");

        for (int i = 0; i < 3; ++i)
        {
            test(N, zero, v, best,            "zero..........");
            test(N, atoi, v, best,            "atoi..........");
            test(N, atoisimple, v, best,      "atoisimple....");
            test(N, fastatoi, v, best,        "fastatoi......");
            test(N, fastatoiadd, v, best,     "fastatoiadd...");
            test(N, fastatoiaddunr, v, best,  "fastatoiaddunr");
        }

        for (auto& kv : best)
        {
            std::cout << "Best: " << kv.first << " : " << std::setw(11) << kv.second << std::endl;
        }

        if (out_filename.length() > 0)
        {
            std::ofstream f(out_filename.c_str(), std::ios::app | std::ios::out);
            if (!f.fail())
            {

              for (auto& kv : best)
              {
                  f << L << "," << (digits_only ? "DO" : "WS" ) << "," << kv.first << "," << kv.second << std::endl;
              }
            }
        }
        else
        {
          std::cout << "No output file param" << std::endl;
        }

    }

    return 0;
}

<|endoftext|>


<commit_before>// CS160 Assignment 3 - question 2, knapsack problem
// by Liam Mencel, November 2014
// Information sources: CS160 lecture slide 11, https://en.wikipedia.org/wiki/Knapsack_problem

#include<iostream>
#include<vector>		// If you are not familiar with C++ vectors, read up on them at http://www.cplusplus.com/reference/vector/vector/ They are easier to use in favour of arrays
#include<algorithm>		// for sorting
#include<map>			// for hash tables (to do memoization)
#include<functional>	// gives us std::function, which lets us write recursive lambdas within functions

using namespace std;

struct Knapsack // an instance of a knapsack problem
{
	const int capacity;			// weight limit W
	const int size;				// number of items
	const vector<int> weights;	// table of weights w1, ..., wn
	const vector<int> values;	// table of values v1, ..., vn

	Knapsack(int W, vector<int> &weight_list, vector<int> &value_list) : size(weight_list.size()), capacity(W), weights(weight_list), values(value_list) // constructor function
	{
		if(weights.size() != values.size())
			throw invalid_argument( "Sizes don't match!" );
	}

	vector<int> solve_fractional(void);	// first algorithm, returns optimal item weights x1, ..., xn. You may think you need to return floats, but integers are sufficient to solve the problem.  Can you see why? (Also floats are messy to handle.)
	vector<int> solve_integral(void);	// second algorithm, returns optimal item quantities x1, ..., xn (each x is either 0 or 1)

	int get_opt_fractional(void);		// these two functions can call the methods above, and return only the optimal total values
	int get_opt_integral(void);
};

vector<int> Knapsack::solve_fractional()
{
	vector<int> result(size, 0);	// change the ith 0 to m whenever you want to take m units of item i
	vector<vector<int> > table;		// build a table of triplets, each triplet corresponds to an item
	int i, j;
	for(i=0; i<size; i++)
	{
		vector<int> item(3, 0);
		item[0] = i;			// first entry in the triplet is the item label
		item[1] = weights[i];	// second entry is the item weight
		item[2] = values[i];	// third entry is the item value
		table.push_back(item);
	}

	auto compare = [] (vector<int> x, vector<int> y) {return (x[2]*y[1] > x[1]*y[2]);}; // our custom comparison function used for sorting. x is placed to the left of y if item x is more valuable per unit weight.
	sort(table.begin(), table.end(), compare);											// table of items is sorted by decreasing value per unit weight

	i = 0;
	int knapsack_weight = 0;						// the current total weight of our knapsack, as we add items
	while(knapsack_weight != capacity && i!= size)	// terminate when our knapsack becomes full, or all items have been taken
	{
		j = table[i][0];											// j now points to the ith most valuable item per unit weight
		result[j] = min(weights[j], capacity - knapsack_weight);	// add the most amount of unit i we can fit in our knapsack
		knapsack_weight += result[i];								// now our knapsack becomes heavier
		i++;
	}
	return result;
}

vector<int> Knapsack::solve_integral()		// I will use a top-down approach, because I find it more elegant to program. You can also do bottom-up instead.
{
	vector<int> result(size, 0);			// change the ith 0 to 1 whenever you want to take item i
	map<vector<int>, int> hash_table;	// for each pair (i, w), store the optimal solution for a knapsack of capacity w, using only the first i items

	function<int(int, int)> m = [this, &m, &hash_table] (int i, int w) -> int // this lets you write a recursive lambda function. See http://stackoverflow.com/questions/2067988/recursive-lambda-functions-in-c0x
	{
		vector<int> key(2, 0); // * it feels weird to use a vector for only two elements. Maybe I will look up how to use a pair or tuple structure.
		key[0] = i;
		key[1] = w;
		if(hash_table.find(key) != hash_table.end())
			return hash_table[key];	// if we already calculated this solution earlier, just pull it from the hash table
		int answer;
		if(i == 0)
			answer = 0;
		else
			answer = (weights[i-1] > w) ? m(i-1, w) : max(m(i-1, w), m(i-1, w-weights[i-1]) + values[i-1]);	// this is the defining recursive formula
		hash_table[key] = answer;	// now that we have found the answer, put it in our hash table so we needn't calculate it again next time
		return answer;
	};

	m(size, capacity); // uses dynamic programming to fill the hash table. Now we need to backtrack to find the entire vector of choices

	// * TO DO - implement backtracking

	return result;
}

int Knapsack::get_opt_fractional()
{
	vector<int> opt_amounts = solve_fractional();
	int result = 0;
	for(int i=0; i<size; i++)
		result += opt_amounts[i] * values[i]; // add each items value multiplied by the number of units we take
	return result;
}

int Knapsack::get_opt_integral()
{
	vector<int> opt_choices = solve_integral();
	int result = 0;
	for(int i=0; i<size; i++)
		result += (opt_choices[i] ? values[i] : 0); // add items value if we choose to take it
	return result;
}

bool simple_test() // a quick test to check your code compiles right
{
	bool result = true;

	// We have a knapsack of capacity 5, and only one item with weight 3 and value 2
	int capacity = 5;
	vector<int> weights(1, 3);
	vector<int> values(1, 2);

	vector<int> correct_fractional(1, 3);	// optimal fractional solution should just be {3}, indicating that 3 units of the first item are taken
	vector<int> correct_integral(1, 1);		// optimal fractional solution should just be {1}, indicating that the first item is taken

	Knapsack* K = new Knapsack(capacity, weights, values);
	cout << "\nStarting simple test...\n\n";

	if(K->solve_fractional() == correct_fractional)
		cout << "Fractional test PASSED\n";
	else
	{
		cout << "Fractional test FAILED\n";
		result = false;
	}

	if(K->solve_integral() == correct_integral)
		cout << "Integral test PASSED\n";
	else
	{
		cout << "Integral test FAILED\n";
		result = false;
	}

	delete K;
	return result;
}

int main()
{
	simple_test();

	cout << "\nPress enter to exit...";
	cin.get();
	return 0;
}<commit_msg>added backtracking<commit_after>// CS160 Assignment 3 - question 2, knapsack problem
// by Liam Mencel, November 2014
// Information sources: CS160 lecture slide 11, https://en.wikipedia.org/wiki/Knapsack_problem

#include<iostream>
#include<vector>		// If you are not familiar with C++ vectors, read up on them at http://www.cplusplus.com/reference/vector/vector/ They are easier to use in favour of arrays
#include<algorithm>		// for sorting
#include<map>			// for hash tables (to do memoization)
#include<functional>	// gives us std::function, which lets us write recursive lambdas within functions

using namespace std;

struct Knapsack // an instance of a knapsack problem
{
	const int capacity;			// weight limit W
	const int size;				// number of items
	const vector<int> weights;	// table of weights w1, ..., wn
	const vector<int> values;	// table of values v1, ..., vn

	Knapsack(int W, vector<int> &weight_list, vector<int> &value_list) : size(weight_list.size()), capacity(W), weights(weight_list), values(value_list) // constructor function
	{
		if(weights.size() != values.size())
			throw invalid_argument( "Sizes don't match!" );
	}

	vector<int> solve_fractional(void);	// first algorithm, returns optimal item weights x1, ..., xn. You may think you need to return floats, but integers are sufficient to solve the problem.  Can you see why? (Also floats are messy to handle.)
	vector<int> solve_integral(void);	// second algorithm, returns optimal item quantities x1, ..., xn (each x is either 0 or 1)

	float get_opt_fractional(void);		// these two functions can call the methods above, and return only the optimal total values
	int get_opt_integral(void);
};

vector<int> Knapsack::solve_fractional()
{
	vector<int> result(size, 0);	// change the ith 0 to m whenever you want to take m units of item i
	vector<vector<int> > table;		// build a table of triplets, each triplet corresponds to an item
	int i, j;
	for(i=0; i<size; i++)
	{
		vector<int> item(3, 0);
		item[0] = i;			// first entry in the triplet is the item label
		item[1] = weights[i];	// second entry is the item weight
		item[2] = values[i];	// third entry is the item value
		table.push_back(item);
	}

	auto compare = [] (vector<int> x, vector<int> y) {return (x[2]*y[1] > x[1]*y[2]);}; // our custom comparison function used for sorting. x is placed to the left of y if item x is more valuable per unit weight.
	sort(table.begin(), table.end(), compare);											// table of items is sorted by decreasing value per unit weight

	i = 0;
	int knapsack_weight = 0;						// the current total weight of our knapsack, as we add items
	while(knapsack_weight != capacity && i!= size)	// terminate when our knapsack becomes full, or all items have been taken
	{
		j = table[i][0];											// j now points to the ith most valuable item per unit weight
		result[j] = min(weights[j], capacity - knapsack_weight);	// add the most amount of unit i we can fit in our knapsack
		knapsack_weight += result[j];								// now our knapsack becomes heavier
		i++;
	}
	return result;
}

vector<int> Knapsack::solve_integral()		// I will use a top-down approach, because I find it more elegant to program. You can also do bottom-up instead.
{
	vector<int> result(size, 0);			// change the ith 0 to 1 whenever you want to take item i
	map<vector<int>, int> hash_table;		// for each pair (i, w), store the optimal solution for a knapsack of capacity w, using only the first i items

	function<int(int, int)> m = [this, &m, &result, &hash_table] (int i, int w) -> int // this lets you write a recursive lambda function. See http://stackoverflow.com/questions/2067988/recursive-lambda-functions-in-c0x
	{
		vector<int> key(2, 0); // * it feels weird to use a vector for only two elements. Maybe one can use a pair or tuple structure.
		key[0] = i;
		key[1] = w;
		if(hash_table.find(key) != hash_table.end())
			return hash_table[key];	// if we already calculated this solution earlier, just pull it from the hash table
		int answer, pick_i, dont_pick_i;
		if(i == 0)
			answer = 0;
		else
		{
			dont_pick_i = m(i-1, w);
			answer = dont_pick_i;
			if(weights[i-1] <= w) // this is the defining recursive formula
			{
				pick_i = m(i-1, w-weights[i-1]) + values[i-1];
				if(pick_i > dont_pick_i)
					answer = pick_i;
			}
		}
		hash_table[key] = answer;	// now that we have found the answer, put it in our hash table so we needn't calculate it again next time
		return answer;
	};

	// backtracking to find vector
	int i = size;
	int w = capacity;
	while(i > 0 && w > 0)
	{
		if(weights[i-1] <= w && m(i-1, w - weights[i-1]) + values[i-1] > m(i-1, w))
		{
			result[i-1] = 1;
			w -= weights[i-1];
		}
		i--;
	}

	return result;
}

float Knapsack::get_opt_fractional()
{
	vector<int> opt_amount = solve_fractional();
	float result = 0.0f;
	for(int i=0; i<size; i++)
		result += (float) opt_amount[i] * (float) values[i] / (float) weights[i]; // add the appropriate proportion of value
	return result;
}

int Knapsack::get_opt_integral()
{
	vector<int> opt_choices = solve_integral();
	int result = 0;
	for(int i=0; i<size; i++)
		result += (opt_choices[i] ? values[i] : 0); // add item's value if we choose to take it
	return result;
}

void test(int capacity, vector<int> weights, vector<int> values) // quick test
{
	Knapsack* K = new Knapsack(capacity, weights, values);
	cout << "\nStarting test...\n\n";

	vector<int> frac = K->solve_fractional();
	cout << "Fractional test\nOptimal value = " << K->get_opt_fractional() << "\n\n";
	vector<int> integral = K->solve_integral();
	cout << "Integral test\nOptimal value = " << K->get_opt_integral() << "\n\n";

	delete K;
}

int main()
{
	// first test
	int capacity = 5;
	int myints1[] = {3, 4, 5, 1, 9};
	vector<int> weights1(myints1, myints1 + sizeof(myints1) / sizeof(int) );
	int myints2[] = {6, 8, 13, 3, 9};
	vector<int> values1(myints2, myints2 + sizeof(myints2) / sizeof(int) );
	test(capacity, weights1, values1);
	// should return 13.4 and 13

	// second test
	capacity = 10;
	int myints3[] = {5, 4, 6, 3};
	vector<int> weights2(myints3, myints3 + sizeof(myints3) / sizeof(int) );
	int myints4[] = {10, 40, 30, 50};
	vector<int> values2(myints4, myints4 + sizeof(myints4) / sizeof(int) );
	test(capacity, weights2, values2);
	// should return 105 and 90

	cout << "\nPress enter to exit...";
	cin.get();
	return 0;
}<|endoftext|>


<commit_before>#include <windows.h>
#include <iostream>

#define toggle_key1 VK_LCONTROL
#define toggle_key2 VK_LMENU
#define toggle_key3 'A'
#define wait_nsec 300

using namespace std;

bool checked_key, aim_key_pushing, is_run = true;

int add_aim_key(int check_key,int next_check_key,int put_key,bool shift_pushing){
  aim_key_pushing= false;
  checked_key = GetAsyncKeyState(check_key) && 0x80;

  if(!next_check_key){
    if(checked_key)
      aim_key_pushing = true;
  }else{
    if(checked_key && (GetAsyncKeyState(next_check_key) && 0x80))
      aim_key_pushing = true;
  }

  if(aim_key_pushing){
    if(shift_pushing){
      keybd_event(VK_SHIFT,0,0,0);
    }
    keybd_event(put_key,0,0,0);
    keybd_event(put_key,0,KEYEVENTF_KEYUP,0);
    if(shift_pushing){
      keybd_event(VK_SHIFT,0,KEYEVENTF_KEYUP,0);
    }
    keybd_event(VK_LEFT,0,0,0);
    keybd_event(VK_LEFT,0,KEYEVENTF_KEYUP,0);
    Sleep(wait_nsec);
  }
  return 0;
}

int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow ){
  MessageBox(NULL, "Coder-Assist", "Coder-Assistを起動しました", MB_OK);
  while(true){
    if((GetAsyncKeyState(toggle_key1) && 0x80) &&
       (GetAsyncKeyState(toggle_key2) && 0x80) &&
       (GetAsyncKeyState(toggle_key3) && 0x80))
    {
      is_run = !is_run;
      Sleep(1000);
    }
    if(is_run){
        add_aim_key(VK_OEM_4, 0, VK_OEM_6, false);
        add_aim_key(VK_SHIFT, VK_OEM_COMMA, VK_OEM_PERIOD, true);
        add_aim_key('8', VK_SHIFT,'9', true);
        add_aim_key('2', VK_SHIFT,'2', true);
        add_aim_key('7', VK_SHIFT,'7', true);
    }
    Sleep(10);
  }
}
<commit_msg>起動メッセージ編集<commit_after>#include <windows.h>
#include <iostream>

#define toggle_key1 VK_LCONTROL
#define toggle_key2 VK_LMENU
#define toggle_key3 'A'
#define wait_nsec 300

using namespace std;

bool checked_key, aim_key_pushing, is_run = true;

int add_aim_key(int check_key,int next_check_key,int put_key,bool shift_pushing){
  aim_key_pushing= false;
  checked_key = GetAsyncKeyState(check_key) && 0x80;

  if(!next_check_key){
    if(checked_key)
      aim_key_pushing = true;
  }else{
    if(checked_key && (GetAsyncKeyState(next_check_key) && 0x80))
      aim_key_pushing = true;
  }

  if(aim_key_pushing){
    if(shift_pushing){
      keybd_event(VK_SHIFT,0,0,0);
    }
    keybd_event(put_key,0,0,0);
    keybd_event(put_key,0,KEYEVENTF_KEYUP,0);
    if(shift_pushing){
      keybd_event(VK_SHIFT,0,KEYEVENTF_KEYUP,0);
    }
    keybd_event(VK_LEFT,0,0,0);
    keybd_event(VK_LEFT,0,KEYEVENTF_KEYUP,0);
    Sleep(wait_nsec);
  }
  return 0;
}

int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow ){
  MessageBox(NULL, TEXT("Coder-Assist started"), "Coder-Assist", MB_OK);
  while(true){
    if((GetAsyncKeyState(toggle_key1) && 0x80) &&
       (GetAsyncKeyState(toggle_key2) && 0x80) &&
       (GetAsyncKeyState(toggle_key3) && 0x80))
    {
      is_run = !is_run;
      Sleep(1000);
    }
    if(is_run){
        add_aim_key(VK_OEM_4, 0, VK_OEM_6, false);
        add_aim_key(VK_SHIFT, VK_OEM_COMMA, VK_OEM_PERIOD, true);
        add_aim_key('8', VK_SHIFT,'9', true);
        add_aim_key('2', VK_SHIFT,'2', true);
        add_aim_key('7', VK_SHIFT,'7', true);
    }
    Sleep(10);
  }
}
<|endoftext|>


<commit_before>#include <cstdint>
#include <iostream>
#include "utils.hpp"

namespace ID{
    constexpr size_t MessageType{35};
    constexpr size_t Side{54};
    constexpr size_t ExecInst{18};
}

template<size_t N>
using num = std::integral_constant<size_t, N>;

auto typeFromID(num<ID::MessageType>){
    char ret{'D'};
    return ret;
}

auto typeFromID(num<ID::Side>){
    uint64_t ret{19};
    return ret;
}

auto typeFromID(num<ID::ExecInst>){
    const char* ret{"M"};
    return ret;
}

template <size_t... IDs> struct tuple {};

template <size_t ID , size_t... IDs>
struct tuple<ID, IDs...> : tuple<IDs...> {

    tuple() : tuple<IDs...>(), tail(typeFromID(num<ID>{})){}

    decltype(typeFromID(num<ID>{})) tail;
    static constexpr size_t id{ID};
};

template <size_t ID, size_t... IDs>
constexpr bool is_right(){
    constexpr size_t id{tuple<IDs...>::id};
    return id==ID;
}

template <size_t ID, size_t... IDs, typename std::enable_if_t<is_right<ID, IDs...>(), std::nullptr_t> = nullptr>
auto& get(tuple<IDs...>& t) {
    return t.tail;
}

template <size_t ID, size_t I, size_t... IDs, typename std::enable_if_t<!is_right<ID, I, IDs...>(), std::nullptr_t> = nullptr>
auto& get(tuple<I, IDs...>& t) {
    static_assert(has_int<ID, I, IDs...>(), "ID not in tuple!");

    tuple<IDs...>& base = t;
    return get<ID>(base);
}

<commit_msg>Add todos<commit_after>#include <cstdint>
#include <iostream>
#include "utils.hpp"

namespace ID{
    constexpr size_t MessageType{35};
    constexpr size_t Side{54};
    constexpr size_t ExecInst{18};
}

template<size_t N>
using num = std::integral_constant<size_t, N>;

auto typeFromID(num<ID::MessageType>){
    char ret{'D'};
    return ret;
}

auto typeFromID(num<ID::Side>){
    uint64_t ret{19};
    return ret;
}

auto typeFromID(num<ID::ExecInst>){
    const char* ret{"M"};
    return ret;
}

template <size_t... IDs> struct tuple {};

template <size_t ID , size_t... IDs>
struct tuple<ID, IDs...> : tuple<IDs...> {

    tuple() : tuple<IDs...>(), tail(typeFromID(num<ID>{})){}

    decltype(typeFromID(num<ID>{})) tail;
    static constexpr size_t id{ID};
};

template <size_t ID, size_t... IDs>
constexpr bool is_right(){
    constexpr size_t id{tuple<IDs...>::id};
    return id==ID;
}

template <size_t ID, size_t... IDs, typename std::enable_if_t<is_right<ID, IDs...>(), std::nullptr_t> = nullptr>
auto& get(tuple<IDs...>& t) {
    return t.tail;
}

// TODO : Rename ID to something better. It's the ID we are looking for. Could be better called TARGET, RHS or value?.
// TODO : Rename I to something better. It's the sliced off first ID. Could be better called ID
template <size_t ID, size_t I, size_t... IDs, typename std::enable_if_t<!is_right<ID, I, IDs...>(), std::nullptr_t> = nullptr>
auto& get(tuple<I, IDs...>& t) {
    static_assert(has_int<ID, I, IDs...>(), "ID not in tuple!");

    tuple<IDs...>& base = t;
    return get<ID>(base);
}

<|endoftext|>


<commit_before>
/*
 * Copyright 2011 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */
#include "SkWindow.h"
#include "SkCanvas.h"
#include "SkDevice.h"
#include "SkOSMenu.h"
#include "SkSystemEventTypes.h"
#include "SkTime.h"

#define SK_EventDelayInval "\xd" "n" "\xa" "l"

#define TEST_BOUNDERx

#include "SkBounder.h"
class test_bounder : public SkBounder {
public:
    test_bounder(const SkBitmap& bm) : fCanvas(bm) {}
protected:
    virtual bool onIRect(const SkIRect& r)
    {
        SkRect    rr;

        rr.set(SkIntToScalar(r.fLeft), SkIntToScalar(r.fTop),
                SkIntToScalar(r.fRight), SkIntToScalar(r.fBottom));

        SkPaint    p;

        p.setStyle(SkPaint::kStroke_Style);
        p.setColor(SK_ColorYELLOW);

#if 0
        rr.inset(SK_ScalarHalf, SK_ScalarHalf);
#else
        rr.inset(-SK_ScalarHalf, -SK_ScalarHalf);
#endif

        fCanvas.drawRect(rr, p);
        return true;
    }
private:
    SkCanvas    fCanvas;
};

SkWindow::SkWindow() : fFocusView(NULL)
{
    fClicks.reset();
    fWaitingOnInval = false;

#ifdef SK_BUILD_FOR_WINCE
    fConfig = SkBitmap::kRGB_565_Config;
#else
    fConfig = SkBitmap::kARGB_8888_Config;
#endif

    fMatrix.reset();
}

SkWindow::~SkWindow()
{
    fClicks.deleteAll();
    fMenus.deleteAll();
}

SkCanvas* SkWindow::createCanvas() {
    return new SkCanvas(this->getBitmap());
}

void SkWindow::setMatrix(const SkMatrix& matrix) {
    if (fMatrix != matrix) {
        fMatrix = matrix;
        this->inval(NULL);
    }
}

void SkWindow::preConcat(const SkMatrix& matrix) {
    SkMatrix m;
    m.setConcat(fMatrix, matrix);
    this->setMatrix(m);
}

void SkWindow::postConcat(const SkMatrix& matrix) {
    SkMatrix m;
    m.setConcat(matrix, fMatrix);
    this->setMatrix(m);
}

void SkWindow::setConfig(SkBitmap::Config config)
{
    this->resize(fBitmap.width(), fBitmap.height(), config);
}

void SkWindow::resize(int width, int height, SkBitmap::Config config)
{
    if (config == SkBitmap::kNo_Config)
        config = fConfig;

    if (width != fBitmap.width() || height != fBitmap.height() || config != fConfig)
    {
        fConfig = config;
        fBitmap.setConfig(config, width, height);
        fBitmap.allocPixels();
        fBitmap.setIsOpaque(true);

        this->setSize(SkIntToScalar(width), SkIntToScalar(height));
        this->inval(NULL);
    }
}

void SkWindow::eraseARGB(U8CPU a, U8CPU r, U8CPU g, U8CPU b)
{
    fBitmap.eraseARGB(a, r, g, b);
}

void SkWindow::eraseRGB(U8CPU r, U8CPU g, U8CPU b)
{
    fBitmap.eraseRGB(r, g, b);
}

bool SkWindow::handleInval(const SkRect* localR)
{
    SkIRect    ir;

    if (localR) {
        SkRect devR;
        SkMatrix inverse;
        if (!fMatrix.invert(&inverse)) {
            return false;
        }
        fMatrix.mapRect(&devR, *localR);
        devR.round(&ir);
    } else {
        ir.set(0, 0,
               SkScalarRound(this->width()),
               SkScalarRound(this->height()));
    }
    fDirtyRgn.op(ir, SkRegion::kUnion_Op);

    this->onHandleInval(ir);
    return true;
}

void SkWindow::forceInvalAll() {
    fDirtyRgn.setRect(0, 0,
                      SkScalarCeil(this->width()),
                      SkScalarCeil(this->height()));
}

#if defined(SK_BUILD_FOR_WINCE) && defined(USE_GX_SCREEN)
    #include <windows.h>
    #include <gx.h>
    extern GXDisplayProperties gDisplayProps;
#endif

#ifdef SK_SIMULATE_FAILED_MALLOC
extern bool gEnableControlledThrow;
#endif

bool SkWindow::update(SkIRect* updateArea)
{
    if (!fDirtyRgn.isEmpty())
    {
        SkBitmap bm = this->getBitmap();

#if defined(SK_BUILD_FOR_WINCE) && defined(USE_GX_SCREEN)
        char* buffer = (char*)GXBeginDraw();
        SkASSERT(buffer);

        RECT    rect;
        GetWindowRect((HWND)((SkOSWindow*)this)->getHWND(), &rect);
        buffer += rect.top * gDisplayProps.cbyPitch + rect.left * gDisplayProps.cbxPitch;

        bm.setPixels(buffer);
#endif
        SkCanvas    rasterCanvas(bm);

        rasterCanvas.clipRegion(fDirtyRgn);
        if (updateArea)
            *updateArea = fDirtyRgn.getBounds();

        SkAutoCanvasRestore acr(&rasterCanvas, true);
        rasterCanvas.concat(fMatrix);

        // empty this now, so we can correctly record any inval calls that
        // might be made during the draw call.
        fDirtyRgn.setEmpty();

#ifdef TEST_BOUNDER
        test_bounder    b(bm);
        rasterCanvas.setBounder(&b);
#endif
#ifdef SK_SIMULATE_FAILED_MALLOC
        gEnableControlledThrow = true;
#endif
#ifdef SK_BUILD_FOR_WIN32
        //try {
            this->draw(&rasterCanvas);
        //}
        //catch (...) {
        //}
#else
        this->draw(&rasterCanvas);
#endif
#ifdef SK_SIMULATE_FAILED_MALLOC
        gEnableControlledThrow = false;
#endif
#ifdef TEST_BOUNDER
        rasterCanvas.setBounder(NULL);
#endif

#if defined(SK_BUILD_FOR_WINCE) && defined(USE_GX_SCREEN)
        GXEndDraw();
#endif

        return true;
    }
    return false;
}

bool SkWindow::handleChar(SkUnichar uni)
{
    if (this->onHandleChar(uni))
        return true;

    SkView* focus = this->getFocusView();
    if (focus == NULL)
        focus = this;

    SkEvent evt(SK_EventType_Unichar);
    evt.setFast32(uni);
    return focus->doEvent(evt);
}

bool SkWindow::handleKey(SkKey key)
{
    if (key == kNONE_SkKey)
        return false;

    if (this->onHandleKey(key))
        return true;

    // send an event to the focus-view
    {
        SkView* focus = this->getFocusView();
        if (focus == NULL)
            focus = this;

        SkEvent evt(SK_EventType_Key);
        evt.setFast32(key);
        if (focus->doEvent(evt))
            return true;
    }

    if (key == kUp_SkKey || key == kDown_SkKey)
    {
        if (this->moveFocus(key == kUp_SkKey ? kPrev_FocusDirection : kNext_FocusDirection) == NULL)
            this->onSetFocusView(NULL);
        return true;
    }
    return false;
}

bool SkWindow::handleKeyUp(SkKey key)
{
    if (key == kNONE_SkKey)
        return false;

    if (this->onHandleKeyUp(key))
        return true;

    //send an event to the focus-view
    {
        SkView* focus = this->getFocusView();
        if (focus == NULL)
            focus = this;

        //should this one be the same?
        SkEvent evt(SK_EventType_KeyUp);
        evt.setFast32(key);
        if (focus->doEvent(evt))
            return true;
    }
    return false;
}

void SkWindow::addMenu(SkOSMenu* menu) {
    *fMenus.append() = menu;
    this->onAddMenu(menu);
}

void SkWindow::setTitle(const char title[]) {
    if (NULL == title) {
        title = "";
    }
    fTitle.set(title);
    this->onSetTitle(title);
}

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

bool SkWindow::onEvent(const SkEvent& evt)
{
    if (evt.isType(SK_EventDelayInval))
    {
        SkRegion::Iterator    iter(fDirtyRgn);

        for (; !iter.done(); iter.next())
            this->onHandleInval(iter.rect());
        fWaitingOnInval = false;
        return true;
    }
    return this->INHERITED::onEvent(evt);
}

bool SkWindow::onGetFocusView(SkView** focus) const
{
    if (focus)
        *focus = fFocusView;
    return true;
}

bool SkWindow::onSetFocusView(SkView* focus)
{
    if (fFocusView != focus)
    {
        if (fFocusView)
            fFocusView->onFocusChange(false);
        fFocusView = focus;
        if (focus)
            focus->onFocusChange(true);
    }
    return true;
}

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

void SkWindow::onHandleInval(const SkIRect&)
{
}

bool SkWindow::onHandleChar(SkUnichar)
{
    return false;
}

bool SkWindow::onHandleKey(SkKey key)
{
    return false;
}

bool SkWindow::onHandleKeyUp(SkKey key)
{
    return false;
}

bool SkWindow::handleClick(int x, int y, Click::State state, void *owner) {
    return this->onDispatchClick(x, y, state, owner);
}

bool SkWindow::onDispatchClick(int x, int y, Click::State state,
        void* owner) {
    bool handled = false;

    // First, attempt to find an existing click with this owner.
    int index = -1;
    for (int i = 0; i < fClicks.count(); i++) {
        if (owner == fClicks[i]->fOwner) {
            index = i;
            break;
        }
    }

    switch (state) {
        case Click::kDown_State: {
            if (index != -1) {
                delete fClicks[index];
                fClicks.remove(index);
            }
            Click* click = this->findClickHandler(SkIntToScalar(x),
                    SkIntToScalar(y));

            if (click) {
                click->fOwner = owner;
                *fClicks.append() = click;
                SkView::DoClickDown(click, x, y);
                handled = true;
            }
            break;
        }
        case Click::kMoved_State:
            if (index != -1) {
                SkView::DoClickMoved(fClicks[index], x, y);
                handled = true;
            }
            break;
        case Click::kUp_State:
            if (index != -1) {
                SkView::DoClickUp(fClicks[index], x, y);
                delete fClicks[index];
                fClicks.remove(index);
                handled = true;
            }
            break;
        default:
            // Do nothing
            break;
    }
    return handled;
}

<commit_msg>Fixed canvas creation in SampleApp<commit_after>
/*
 * Copyright 2011 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */
#include "SkWindow.h"
#include "SkCanvas.h"
#include "SkDevice.h"
#include "SkOSMenu.h"
#include "SkSystemEventTypes.h"
#include "SkTime.h"

#define SK_EventDelayInval "\xd" "n" "\xa" "l"

#define TEST_BOUNDERx

#include "SkBounder.h"
class test_bounder : public SkBounder {
public:
    test_bounder(const SkBitmap& bm) : fCanvas(bm) {}
protected:
    virtual bool onIRect(const SkIRect& r)
    {
        SkRect    rr;

        rr.set(SkIntToScalar(r.fLeft), SkIntToScalar(r.fTop),
                SkIntToScalar(r.fRight), SkIntToScalar(r.fBottom));

        SkPaint    p;

        p.setStyle(SkPaint::kStroke_Style);
        p.setColor(SK_ColorYELLOW);

#if 0
        rr.inset(SK_ScalarHalf, SK_ScalarHalf);
#else
        rr.inset(-SK_ScalarHalf, -SK_ScalarHalf);
#endif

        fCanvas.drawRect(rr, p);
        return true;
    }
private:
    SkCanvas    fCanvas;
};

SkWindow::SkWindow() : fFocusView(NULL)
{
    fClicks.reset();
    fWaitingOnInval = false;

#ifdef SK_BUILD_FOR_WINCE
    fConfig = SkBitmap::kRGB_565_Config;
#else
    fConfig = SkBitmap::kARGB_8888_Config;
#endif

    fMatrix.reset();
}

SkWindow::~SkWindow()
{
    fClicks.deleteAll();
    fMenus.deleteAll();
}

SkCanvas* SkWindow::createCanvas() {
    return new SkCanvas(this->getBitmap());
}

void SkWindow::setMatrix(const SkMatrix& matrix) {
    if (fMatrix != matrix) {
        fMatrix = matrix;
        this->inval(NULL);
    }
}

void SkWindow::preConcat(const SkMatrix& matrix) {
    SkMatrix m;
    m.setConcat(fMatrix, matrix);
    this->setMatrix(m);
}

void SkWindow::postConcat(const SkMatrix& matrix) {
    SkMatrix m;
    m.setConcat(matrix, fMatrix);
    this->setMatrix(m);
}

void SkWindow::setConfig(SkBitmap::Config config)
{
    this->resize(fBitmap.width(), fBitmap.height(), config);
}

void SkWindow::resize(int width, int height, SkBitmap::Config config)
{
    if (config == SkBitmap::kNo_Config)
        config = fConfig;

    if (width != fBitmap.width() || height != fBitmap.height() || config != fConfig)
    {
        fConfig = config;
        fBitmap.setConfig(config, width, height);
        fBitmap.allocPixels();
        fBitmap.setIsOpaque(true);

        this->setSize(SkIntToScalar(width), SkIntToScalar(height));
        this->inval(NULL);
    }
}

void SkWindow::eraseARGB(U8CPU a, U8CPU r, U8CPU g, U8CPU b)
{
    fBitmap.eraseARGB(a, r, g, b);
}

void SkWindow::eraseRGB(U8CPU r, U8CPU g, U8CPU b)
{
    fBitmap.eraseRGB(r, g, b);
}

bool SkWindow::handleInval(const SkRect* localR)
{
    SkIRect    ir;

    if (localR) {
        SkRect devR;
        SkMatrix inverse;
        if (!fMatrix.invert(&inverse)) {
            return false;
        }
        fMatrix.mapRect(&devR, *localR);
        devR.round(&ir);
    } else {
        ir.set(0, 0,
               SkScalarRound(this->width()),
               SkScalarRound(this->height()));
    }
    fDirtyRgn.op(ir, SkRegion::kUnion_Op);

    this->onHandleInval(ir);
    return true;
}

void SkWindow::forceInvalAll() {
    fDirtyRgn.setRect(0, 0,
                      SkScalarCeil(this->width()),
                      SkScalarCeil(this->height()));
}

#if defined(SK_BUILD_FOR_WINCE) && defined(USE_GX_SCREEN)
    #include <windows.h>
    #include <gx.h>
    extern GXDisplayProperties gDisplayProps;
#endif

#ifdef SK_SIMULATE_FAILED_MALLOC
extern bool gEnableControlledThrow;
#endif

bool SkWindow::update(SkIRect* updateArea)
{
    if (!fDirtyRgn.isEmpty())
    {
        SkBitmap bm = this->getBitmap();

#if defined(SK_BUILD_FOR_WINCE) && defined(USE_GX_SCREEN)
        char* buffer = (char*)GXBeginDraw();
        SkASSERT(buffer);

        RECT    rect;
        GetWindowRect((HWND)((SkOSWindow*)this)->getHWND(), &rect);
        buffer += rect.top * gDisplayProps.cbyPitch + rect.left * gDisplayProps.cbxPitch;

        bm.setPixels(buffer);
#endif

        SkAutoTUnref<SkCanvas> canvas(this->createCanvas());

        canvas->clipRegion(fDirtyRgn);
        if (updateArea)
            *updateArea = fDirtyRgn.getBounds();

        SkAutoCanvasRestore acr(canvas, true);
        canvas->concat(fMatrix);

        // empty this now, so we can correctly record any inval calls that
        // might be made during the draw call.
        fDirtyRgn.setEmpty();

#ifdef TEST_BOUNDER
        test_bounder    b(bm);
        canvas->setBounder(&b);
#endif
#ifdef SK_SIMULATE_FAILED_MALLOC
        gEnableControlledThrow = true;
#endif
#ifdef SK_BUILD_FOR_WIN32
        //try {
            this->draw(canvas);
        //}
        //catch (...) {
        //}
#else
        this->draw(canvas);
#endif
#ifdef SK_SIMULATE_FAILED_MALLOC
        gEnableControlledThrow = false;
#endif
#ifdef TEST_BOUNDER
        canvas->setBounder(NULL);
#endif

#if defined(SK_BUILD_FOR_WINCE) && defined(USE_GX_SCREEN)
        GXEndDraw();
#endif

        return true;
    }
    return false;
}

bool SkWindow::handleChar(SkUnichar uni)
{
    if (this->onHandleChar(uni))
        return true;

    SkView* focus = this->getFocusView();
    if (focus == NULL)
        focus = this;

    SkEvent evt(SK_EventType_Unichar);
    evt.setFast32(uni);
    return focus->doEvent(evt);
}

bool SkWindow::handleKey(SkKey key)
{
    if (key == kNONE_SkKey)
        return false;

    if (this->onHandleKey(key))
        return true;

    // send an event to the focus-view
    {
        SkView* focus = this->getFocusView();
        if (focus == NULL)
            focus = this;

        SkEvent evt(SK_EventType_Key);
        evt.setFast32(key);
        if (focus->doEvent(evt))
            return true;
    }

    if (key == kUp_SkKey || key == kDown_SkKey)
    {
        if (this->moveFocus(key == kUp_SkKey ? kPrev_FocusDirection : kNext_FocusDirection) == NULL)
            this->onSetFocusView(NULL);
        return true;
    }
    return false;
}

bool SkWindow::handleKeyUp(SkKey key)
{
    if (key == kNONE_SkKey)
        return false;

    if (this->onHandleKeyUp(key))
        return true;

    //send an event to the focus-view
    {
        SkView* focus = this->getFocusView();
        if (focus == NULL)
            focus = this;

        //should this one be the same?
        SkEvent evt(SK_EventType_KeyUp);
        evt.setFast32(key);
        if (focus->doEvent(evt))
            return true;
    }
    return false;
}

void SkWindow::addMenu(SkOSMenu* menu) {
    *fMenus.append() = menu;
    this->onAddMenu(menu);
}

void SkWindow::setTitle(const char title[]) {
    if (NULL == title) {
        title = "";
    }
    fTitle.set(title);
    this->onSetTitle(title);
}

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

bool SkWindow::onEvent(const SkEvent& evt)
{
    if (evt.isType(SK_EventDelayInval))
    {
        SkRegion::Iterator    iter(fDirtyRgn);

        for (; !iter.done(); iter.next())
            this->onHandleInval(iter.rect());
        fWaitingOnInval = false;
        return true;
    }
    return this->INHERITED::onEvent(evt);
}

bool SkWindow::onGetFocusView(SkView** focus) const
{
    if (focus)
        *focus = fFocusView;
    return true;
}

bool SkWindow::onSetFocusView(SkView* focus)
{
    if (fFocusView != focus)
    {
        if (fFocusView)
            fFocusView->onFocusChange(false);
        fFocusView = focus;
        if (focus)
            focus->onFocusChange(true);
    }
    return true;
}

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

void SkWindow::onHandleInval(const SkIRect&)
{
}

bool SkWindow::onHandleChar(SkUnichar)
{
    return false;
}

bool SkWindow::onHandleKey(SkKey key)
{
    return false;
}

bool SkWindow::onHandleKeyUp(SkKey key)
{
    return false;
}

bool SkWindow::handleClick(int x, int y, Click::State state, void *owner) {
    return this->onDispatchClick(x, y, state, owner);
}

bool SkWindow::onDispatchClick(int x, int y, Click::State state,
        void* owner) {
    bool handled = false;

    // First, attempt to find an existing click with this owner.
    int index = -1;
    for (int i = 0; i < fClicks.count(); i++) {
        if (owner == fClicks[i]->fOwner) {
            index = i;
            break;
        }
    }

    switch (state) {
        case Click::kDown_State: {
            if (index != -1) {
                delete fClicks[index];
                fClicks.remove(index);
            }
            Click* click = this->findClickHandler(SkIntToScalar(x),
                    SkIntToScalar(y));

            if (click) {
                click->fOwner = owner;
                *fClicks.append() = click;
                SkView::DoClickDown(click, x, y);
                handled = true;
            }
            break;
        }
        case Click::kMoved_State:
            if (index != -1) {
                SkView::DoClickMoved(fClicks[index], x, y);
                handled = true;
            }
            break;
        case Click::kUp_State:
            if (index != -1) {
                SkView::DoClickUp(fClicks[index], x, y);
                delete fClicks[index];
                fClicks.remove(index);
                handled = true;
            }
            break;
        default:
            // Do nothing
            break;
    }
    return handled;
}

<|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (C) Qxt Foundation. Some rights reserved.
**
** This file is part of the QxtCore module of the Qt eXTension library
**
** This library is free software; you can redistribute it and/or modify it
** under the terms of th Common Public License, version 1.0, as published by
** IBM.
**
** This file is provided "AS IS", without WARRANTIES OR CONDITIONS OF ANY
** KIND, EITHER EXPRESS OR IMPLIED INCLUDING, WITHOUT LIMITATION, ANY
** WARRANTIES OR CONDITIONS OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY OR
** FITNESS FOR A PARTICULAR PURPOSE.
**
** You should have received a copy of the CPL along with this file.
** See the LICENSE file and the cpl1.0.txt file included with the source
** distribution for more information. If you did not receive a copy of the
** license, contact the Qxt Foundation.
**
** <http://libqxt.sourceforge.net>  <libqxt@gmail.com>
**
****************************************************************************/
#include "qxtwebcore.h"
#include "qxtwebcore_p.h"
#include <QTimer>
#include <QUrl>
#include "qxtwebcontroller.h"
#include <QCoreApplication>
#include <QTcpSocket>
#include <QVariant>
#include <QtDebug>
/*!
        \class QxtWebCore QxtWebCore
        \ingroup web
        \brief qxtweb application core class. communicates, delegates, does all of the magic ;)

        QxtWebCore is the base class of your web application.
        it listens to the scgi protocoll

        construct one webcore object in the main function of your application.
        you must contruct it AFTER QCoreApplication and BEFORe any controllers.

        \code
        int main(int argc,char ** argv)
                {
                QCoreApplication  app(argc,argv);
                QxtWebCore core();
                core.listen(8080);
                QxtWebController controller("root");
                app.exec();
                }
        \endcode
*/

/*!
        \fn static QxtWebCore* instance();
        singleton accessor
        \fn static void send(QByteArray);
        Send data to the client. Use this rarely, but use it always when sending binary data such as images. \n
        normal text/html comunication should be done using the controllers echo() function \n
        note that after you called send the first time you cannot modify the header anymore \n
        sending may be ignored by the transport when there is no client currently handled
        \fn static QIODevice * socket();
        direct access to a iodevice for writing binary data. \n
        You shouldn't use that unless it's absolutly nessesary
        \fn static QxtError parseString(QByteArray str, post_t & POST);
        much like phps parse_string \n
        \fn static QByteArray readContent(int maxsize=5000);
        reads the content from the current socket if any has sent. \n
        returns an empty QByteArray on any error.  \n
        the content is cut at maxsize and not read from the socket.  \n
        FIXME:\warning: this function is BLOCKING.  while content is read from the client, no other requests can be handled.
        FIXME:\warning: due to paranoid timeouts this might not work for slow clients
 */

static QxtWebCore * singleton_m=0;

//-----------------------interface----------------------------
QxtWebCore::QxtWebCore():QObject()
	{
        if(singleton_m)
                qFatal("you're trying to construct QxtWebCore twice!");
	qRegisterMetaType<server_t>("server_t");
        qRegisterMetaTypeStreamOperators<server_t>("server_t");

        singleton_m=this;

	QXT_INIT_PRIVATE(QxtWebCore);
	}

QxtWebCore::~QxtWebCore()
        {
        singleton_m=0;
        }

QxtWebCore * QxtWebCore::instance()
        {
        if(!singleton_m)
                qFatal("no QxtWebCore constructed");
        return singleton_m;
        }
void QxtWebCore::send(QByteArray a)
        {
        instance()->qxt_d().send(a);
        }
void QxtWebCore::header(QByteArray a,QByteArray b)
        {
        instance()->qxt_d().header(a,b);
        }

server_t &  QxtWebCore::SERVER()
        {
        return instance()->qxt_d().currentservert;
        }

QIODevice * QxtWebCore::socket()
        {
        return instance()->qxt_d().socket_m;
        }

int QxtWebCore::listen (quint16 port ,const QHostAddress & address )
        {
        return qxt_d().listen(address,port);
        }

//-----------------------implementation----------------------------

QxtWebCorePrivate::QxtWebCorePrivate(QObject *parent):QTcpServer(parent)
        {
        }

void QxtWebCorePrivate::incomingConnection(int socketDescriptor)
        {
        header_sent=false;
        answer.clear();
        qDebug("%i, -> incomming",(int)time(NULL));
	QTcpSocket * tcpSocket = new QTcpSocket;
	if (!tcpSocket->setSocketDescriptor(socketDescriptor))
		{
		return;
		}
        socket_m=tcpSocket;
	connect(tcpSocket,SIGNAL(disconnected()),tcpSocket,SLOT(deleteLater()));

	server_t SERVER;
	int eee1=readHeaderFromSocket(tcpSocket,SERVER);

        if(eee1)
		{
                tcpSocket->write("Status: 500 INTERNAL SERVER ERROR\r\ncontent-type: text/html\r\n\r\nHEADER NOT READABLE");
		}

        qDebug("%i, %s -> %s",(int)time(NULL),SERVER["HTTP_HOST"].constData(),SERVER["REQUEST_URI"].constData());

        currentservert=SERVER;

        emit(qxt_p().request());

	///--------------find controller ------------------
	QByteArray path="404";
	QList<QByteArray> requestsplit = SERVER["REQUEST_URI"].split('/');
	if (requestsplit.count()>1)
		{
		path=requestsplit.at(1);
		if (path.trimmed().isEmpty())path="root";
		}
	else if (requestsplit.count()>0)
		path="root";

	///--------------controller------------------

	QxtWebController * controller =qFindChild<QxtWebController *> (QCoreApplication::instance(), path );
	if (!controller)
		{
                tcpSocket->write("Status: 500 INTERNAL SERVER ERROR\r\ncontent-type: text/html\r\n\r\nERROR HANDLING NOT IMPLEMENTED");
		qDebug("controller '%s' not found",path.constData());
                return;
		}

	int i=controller->invoke(SERVER);
	if(i)
                {
                tcpSocket->write("Status: 500 INTERNAL SERVER ERROR\r\ncontent-type: text/html\r\n\r\nERROR HANDLING NOT IMPLEMENTED");
                }

        tcpSocket->disconnectFromHost();

        }

void QxtWebCorePrivate::sendheader()
        {
        if(!header_sent)
                {
                if(!answer.contains("Status"))
                        answer["Status"]="200 OK";
                if(!answer.contains("Content-Type"))
                        answer["Content-Type"]="text/html; charset=utf-8";

                server_t::const_iterator i = answer.constBegin();
                while (i != answer.constEnd())
                        {
                        socket_m->write(i.key()+": "+i.value()+"\r\n");
                        ++i;
                        }
                socket_m->write("\r\n");
                header_sent=true;
                }
        }

void QxtWebCorePrivate::header(QByteArray k ,QByteArray v)
        {
        answer[k]=v;
        }
void QxtWebCorePrivate::send(QByteArray a)
        {
        if(socket_m)
                {
                sendheader();
                socket_m->write(a);
                }
        else
		qDebug()<<"<send attemp when no connection open";
        }

//-----------------------helper----------------------------

static QByteArray readContent(int maxsize)
	{
        QIODevice * tcpSocket= QxtWebCore::socket();
        server_t SERVER= QxtWebCore::SERVER();

	if (!tcpSocket)
		return QByteArray();

        int content_size=SERVER["CONTENT_LENGTH"].toInt();

	if (content_size<1)
		{
                return QByteArray();
		}

        if(content_size>maxsize)
                content_size=maxsize;

	///--------------read the content------------------

	while(tcpSocket->bytesAvailable ()<content_size)
		{
		if (!tcpSocket->waitForReadyRead (2000))
                        return QByteArray();
		}

	QByteArray content_in;
	content_in.resize(content_size);

	if (tcpSocket->read (content_in.data(), content_size )!=content_size)
                return QByteArray();

	if (SERVER["CONTENT_TYPE"]!="application/x-www-form-urlencoded")
                return QByteArray();

        return content_in;
	}

QxtError QxtWebCore::parseString(QByteArray content_in, post_t & POST)
	{
	QList<QByteArray> posts = content_in.split('&');
	QByteArray post;
	foreach(post,posts)
		{
		QList<QByteArray> b =post.split('=');
		if (b.count()!=2)continue;
		POST[QUrl::fromPercentEncoding  ( b[0].replace("+","%20"))]=QUrl::fromPercentEncoding  ( b[1].replace("+","%20") );
		}
	QXT_DROP_OK
	}

int QxtWebCorePrivate::readHeaderFromSocket(QTcpSocket * tcpSocket,server_t & SERVER)
	{
	if (!tcpSocket)
		return 5012;

	///--------------get the header size----------------

	QByteArray size_in;
	while(!size_in.endsWith(':'))
		{
		if(!tcpSocket->bytesAvailable ())
			if (!tcpSocket->waitForReadyRead (200))
                                return 50033;

		char a[4]; ///4? yes, i know i'm paranoid about bounds.

		if (!tcpSocket->read (a, 1 ))
                                return 50034;

		size_in+=a[0];

		if (size_in.size()>20)/// after the 20ths char is an attack atemp for sure
                                return 50034;

		}

	size_in.chop(1);
	int size=size_in.toInt()+1;

	if (size>10240)  ///do not accept headers over 10kb
                                return 50037;

	///--------------read the header------------------

	while(tcpSocket->bytesAvailable ()<size)
		{
		if (!tcpSocket->waitForReadyRead (200))
                                return 50033;
		}
	QByteArray header_in;
	header_in.resize(size);

	if (tcpSocket->read (header_in.data(), size )!=size)
                                return 50034;

	if (!header_in.endsWith(','))
                                return 50090;
	///--------------parse the header------------------

	int i=0;
	QByteArray name="";
	QByteArray a =header_in;
	while((i=a.indexOf('\0'))>-1)
		{
		if(name=="")
			{
			name= a.left(i).replace('\0',"");
			}
		else
			{
			SERVER[name]=a.left(i).replace('\0',"").replace("%20"," ");
			name="";
			}

		a=a.mid(i+1);
		}

        return 0;
	}
//---------------------------------------------------------------------------

<commit_msg>woops<commit_after>/****************************************************************************
**
** Copyright (C) Qxt Foundation. Some rights reserved.
**
** This file is part of the QxtCore module of the Qt eXTension library
**
** This library is free software; you can redistribute it and/or modify it
** under the terms of th Common Public License, version 1.0, as published by
** IBM.
**
** This file is provided "AS IS", without WARRANTIES OR CONDITIONS OF ANY
** KIND, EITHER EXPRESS OR IMPLIED INCLUDING, WITHOUT LIMITATION, ANY
** WARRANTIES OR CONDITIONS OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY OR
** FITNESS FOR A PARTICULAR PURPOSE.
**
** You should have received a copy of the CPL along with this file.
** See the LICENSE file and the cpl1.0.txt file included with the source
** distribution for more information. If you did not receive a copy of the
** license, contact the Qxt Foundation.
**
** <http://libqxt.sourceforge.net>  <libqxt@gmail.com>
**
****************************************************************************/
#include "qxtwebcore.h"
#include "qxtwebcore_p.h"
#include <QTimer>
#include <QUrl>
#include "qxtwebcontroller.h"
#include <QCoreApplication>
#include <QTcpSocket>
#include <QVariant>
#include <QtDebug>
/*!
        \class QxtWebCore QxtWebCore
        \ingroup web
        \brief qxtweb application core class. communicates, delegates, does all of the magic ;)

        QxtWebCore is the base class of your web application.
        it listens to the scgi protocoll

        construct one webcore object in the main function of your application.
        you must contruct it AFTER QCoreApplication and BEFORe any controllers.

        \code
        int main(int argc,char ** argv)
                {
                QCoreApplication  app(argc,argv);
                QxtWebCore core();
                core.listen(8080);
                QxtWebController controller("root");
                app.exec();
                }
        \endcode
*/

/*!
        \fn static QxtWebCore* instance();
        singleton accessor
        \fn static void send(QByteArray);
        Send data to the client. Use this rarely, but use it always when sending binary data such as images. \n
        normal text/html comunication should be done using the controllers echo() function \n
        note that after you called send the first time you cannot modify the header anymore \n
        sending may be ignored by the transport when there is no client currently handled
        \fn static QIODevice * socket();
        direct access to a iodevice for writing binary data. \n
        You shouldn't use that unless it's absolutly nessesary
        \fn static QxtError parseString(QByteArray str, post_t & POST);
        much like phps parse_string \n
        \fn static QByteArray readContent(int maxsize=5000);
        reads the content from the current socket if any has sent. \n
        returns an empty QByteArray on any error.  \n
        the content is cut at maxsize and not read from the socket.  \n
        FIXME:\warning: this function is BLOCKING.  while content is read from the client, no other requests can be handled.
        FIXME:\warning: due to paranoid timeouts this might not work for slow clients
 */

static QxtWebCore * singleton_m=0;

//-----------------------interface----------------------------
QxtWebCore::QxtWebCore():QObject()
	{
        if(singleton_m)
                qFatal("you're trying to construct QxtWebCore twice!");
	qRegisterMetaType<server_t>("server_t");
        qRegisterMetaTypeStreamOperators<server_t>("server_t");

        singleton_m=this;

	QXT_INIT_PRIVATE(QxtWebCore);
	}

QxtWebCore::~QxtWebCore()
        {
        singleton_m=0;
        }

QxtWebCore * QxtWebCore::instance()
        {
        if(!singleton_m)
                qFatal("no QxtWebCore constructed");
        return singleton_m;
        }
void QxtWebCore::send(QByteArray a)
        {
        instance()->qxt_d().send(a);
        }
void QxtWebCore::header(QByteArray a,QByteArray b)
        {
        instance()->qxt_d().header(a,b);
        }

server_t &  QxtWebCore::SERVER()
        {
        return instance()->qxt_d().currentservert;
        }

QIODevice * QxtWebCore::socket()
        {
        return instance()->qxt_d().socket_m;
        }

int QxtWebCore::listen (quint16 port ,const QHostAddress & address )
        {
        return qxt_d().listen(address,port);
        }

//-----------------------implementation----------------------------

QxtWebCorePrivate::QxtWebCorePrivate(QObject *parent):QTcpServer(parent)
        {
        }

void QxtWebCorePrivate::incomingConnection(int socketDescriptor)
        {
        header_sent=false;
        answer.clear();
        qDebug("%i, -> incomming",(int)time(NULL));
	QTcpSocket * tcpSocket = new QTcpSocket;
	if (!tcpSocket->setSocketDescriptor(socketDescriptor))
		{
		return;
		}
        socket_m=tcpSocket;
	connect(tcpSocket,SIGNAL(disconnected()),tcpSocket,SLOT(deleteLater()));

	server_t SERVER;
	int eee1=readHeaderFromSocket(tcpSocket,SERVER);

        if(eee1)
		{
                tcpSocket->write("Status: 500 INTERNAL SERVER ERROR\r\ncontent-type: text/html\r\n\r\nHEADER NOT READABLE");
		}

        qDebug("%i, %s -> %s",(int)time(NULL),SERVER["HTTP_HOST"].constData(),SERVER["REQUEST_URI"].constData());

        currentservert=SERVER;

        emit(qxt_p().request());

	///--------------find controller ------------------
	QByteArray path="404";
	QList<QByteArray> requestsplit = SERVER["REQUEST_URI"].split('/');
	if (requestsplit.count()>1)
		{
		path=requestsplit.at(1);
		if (path.trimmed().isEmpty())path="root";
		}
	else if (requestsplit.count()>0)
		path="root";

	///--------------controller------------------

	QxtWebController * controller =qFindChild<QxtWebController *> (QCoreApplication::instance(), path );
	if (!controller)
		{
                tcpSocket->write("Status: 500 INTERNAL SERVER ERROR\r\ncontent-type: text/html\r\n\r\nERROR HANDLING NOT IMPLEMENTED");
		qDebug("controller '%s' not found",path.constData());
                return;
		}

	int i=controller->invoke(SERVER);
	if(i)
                {
                tcpSocket->write("Status: 500 INTERNAL SERVER ERROR\r\ncontent-type: text/html\r\n\r\nERROR HANDLING NOT IMPLEMENTED");
                }

        tcpSocket->disconnectFromHost();

        }

void QxtWebCorePrivate::sendheader()
        {
        if(!header_sent)
                {
                if(!answer.contains("Status"))
                        answer["Status"]="200 OK";
                if(!answer.contains("Content-Type"))
                        answer["Content-Type"]="text/html; charset=utf-8";

                server_t::const_iterator i = answer.constBegin();
                while (i != answer.constEnd())
                        {
                        socket_m->write(i.key()+": "+i.value()+"\r\n");
                        ++i;
                        }
                socket_m->write("\r\n");
                header_sent=true;
                }
        }

void QxtWebCorePrivate::header(QByteArray k ,QByteArray v)
        {
        answer[k]=v;
        }
void QxtWebCorePrivate::send(QByteArray a)
        {
        if(socket_m)
                {
                sendheader();
                socket_m->write(a);
                }
        else
		qDebug()<<"<send attemp when no connection open";
        }

//-----------------------helper----------------------------

QByteArray QxtWebCore::readContent(int maxsize)
	{
        QIODevice * tcpSocket= QxtWebCore::socket();
        server_t SERVER= QxtWebCore::SERVER();

	if (!tcpSocket)
		return QByteArray();

        int content_size=SERVER["CONTENT_LENGTH"].toInt();

	if (content_size<1)
		{
                return QByteArray();
		}

        if(content_size>maxsize)
                content_size=maxsize;

	///--------------read the content------------------

	while(tcpSocket->bytesAvailable ()<content_size)
		{
		if (!tcpSocket->waitForReadyRead (2000))
                        return QByteArray();
		}

	QByteArray content_in;
	content_in.resize(content_size);

	if (tcpSocket->read (content_in.data(), content_size )!=content_size)
                return QByteArray();

	if (SERVER["CONTENT_TYPE"]!="application/x-www-form-urlencoded")
                return QByteArray();

        return content_in;
	}

QxtError QxtWebCore::parseString(QByteArray content_in, post_t & POST)
	{
	QList<QByteArray> posts = content_in.split('&');
	QByteArray post;
	foreach(post,posts)
		{
		QList<QByteArray> b =post.split('=');
		if (b.count()!=2)continue;
		POST[QUrl::fromPercentEncoding  ( b[0].replace("+","%20"))]=QUrl::fromPercentEncoding  ( b[1].replace("+","%20") );
		}
	QXT_DROP_OK
	}

int QxtWebCorePrivate::readHeaderFromSocket(QTcpSocket * tcpSocket,server_t & SERVER)
	{
	if (!tcpSocket)
		return 5012;

	///--------------get the header size----------------

	QByteArray size_in;
	while(!size_in.endsWith(':'))
		{
		if(!tcpSocket->bytesAvailable ())
			if (!tcpSocket->waitForReadyRead (200))
                                return 50033;

		char a[4]; ///4? yes, i know i'm paranoid about bounds.

		if (!tcpSocket->read (a, 1 ))
                                return 50034;

		size_in+=a[0];

		if (size_in.size()>20)/// after the 20ths char is an attack atemp for sure
                                return 50034;

		}

	size_in.chop(1);
	int size=size_in.toInt()+1;

	if (size>10240)  ///do not accept headers over 10kb
                                return 50037;

	///--------------read the header------------------

	while(tcpSocket->bytesAvailable ()<size)
		{
		if (!tcpSocket->waitForReadyRead (200))
                                return 50033;
		}
	QByteArray header_in;
	header_in.resize(size);

	if (tcpSocket->read (header_in.data(), size )!=size)
                                return 50034;

	if (!header_in.endsWith(','))
                                return 50090;
	///--------------parse the header------------------

	int i=0;
	QByteArray name="";
	QByteArray a =header_in;
	while((i=a.indexOf('\0'))>-1)
		{
		if(name=="")
			{
			name= a.left(i).replace('\0',"");
			}
		else
			{
			SERVER[name]=a.left(i).replace('\0',"").replace("%20"," ");
			name="";
			}

		a=a.mid(i+1);
		}

        return 0;
	}
//---------------------------------------------------------------------------

<|endoftext|>


<commit_before>#include <GL/gl.h>
#include <GL/glu.h>
#include <GL/glut.h>

//DECLARACION DE VARIABLES A UTILIZAR

int id_menu[2]; // vector donde almacenaremos el id de la imagen a imprimir

//METODO QUE PERMITE IMPRIMIR LA IMAGEN A MOSTRAR
void punto(float x, float y){
	glClear (GL_COLOR_BUFFER_BIT);
	glPointSize(5.0f);
	glBegin(GL_POINTS);
    glVertex2f(x,y);
    glEnd();
}

void init (void)
{
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    glOrtho(-1, 1, -1, 1, -1, 1);
}

void menu(int opc){
    id_menu[1]=opc; // En el vector VF, en su campo 1, se almacenara el id de la imagen
    glClear (GL_COLOR_BUFFER_BIT);//limpiar la pantalla
    switch(opc){ // checando la imagen elegida para mostrar
       case 1:
           punto(0,0);
           break;
       case 2:
		exit(0);
   }
   glutPostRedisplay();//redibujar denuevo cada una de las imagenes
   glFlush();
}

// METODO QUE RE DIBUJA LA PANTALLA
void redraw( void ){
    //Limpiando la pantalla
    glClear(GL_COLOR_BUFFER_BIT);
    // Haciendo uso del metodo menu, pasandoles como paramentro el id
    menu(id_menu[1]);
	glutSwapBuffers();
}

int main(int argc, char *argv[]){
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE);
    glutCreateWindow("Ejemplo menu ");
    glutPositionWindow(200,200);
    init ();
    // CREACION DEL MENU PARA ELEGIR ALGUNA IMAGEN
    glutCreateMenu(menu);
      glutAddMenuEntry("PUNTO",1);
      glutAddMenuEntry("SALIR",2);
      glutAttachMenu(GLUT_RIGHT_BUTTON); // Eligiendo con el click derecho del raton
	  glMatrixMode(GL_PROJECTION);
      glLoadIdentity();
	  glutDisplayFunc(redraw);
	  glutIdleFunc(redraw);
    glutMainLoop();
    return 0;
}
<commit_msg>Modificado<commit_after>//Yanci
#include <GL/gl.h>
#include <GL/glu.h>
#include <GL/glut.h>

//DECLARACION DE VARIABLES A UTILIZAR

int id_menu[2]; // vector donde almacenaremos el id de la imagen a imprimir

//METODO QUE PERMITE IMPRIMIR LA IMAGEN A MOSTRAR
void punto(float x, float y){
	glClear (GL_COLOR_BUFFER_BIT);
	glPointSize(5.0f);
	glBegin(GL_POINTS);
    glVertex2f(x,y);
    glEnd();
}

void init (void)
{
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    glOrtho(-1, 1, -1, 1, -1, 1);
}

void menu(int opc){
    id_menu[1]=opc; // En el vector VF, en su campo 1, se almacenara el id de la imagen
    glClear (GL_COLOR_BUFFER_BIT);//limpiar la pantalla
    switch(opc){ // checando la imagen elegida para mostrar
       case 1:
           punto(0,0);
           break;
       case 2:
		exit(0);
   }
   glutPostRedisplay();//redibujar denuevo cada una de las imagenes
   glFlush();
}

// METODO QUE RE DIBUJA LA PANTALLA
void redraw( void ){
    //Limpiando la pantalla
    glClear(GL_COLOR_BUFFER_BIT);
    // Haciendo uso del metodo menu, pasandoles como paramentro el id
    menu(id_menu[1]);
	glutSwapBuffers();
}

int main(int argc, char *argv[]){
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE);
    glutCreateWindow("Ejemplo menu ");
    glutPositionWindow(200,200);
    init ();
    // CREACION DEL MENU PARA ELEGIR ALGUNA IMAGEN
    glutCreateMenu(menu);
      glutAddMenuEntry("PUNTO",1);
      glutAddMenuEntry("SALIR",2);
      glutAttachMenu(GLUT_RIGHT_BUTTON); // Eligiendo con el click derecho del raton
	  glMatrixMode(GL_PROJECTION);
      glLoadIdentity();
	  glutDisplayFunc(redraw);
	  glutIdleFunc(redraw);
    glutMainLoop();
    return 0;
}
<|endoftext|>