<commit_before>#include "Example1.h"

#include <FrameView.h>
#include <TextLabel.h>
#include <LinearLayout.h>
#include <Button.h>
#include <ScrollLayout.h>
#include <Switch.h>
#include <TextField.h>
#include <ImageElement.h>
#include <NavigationBar.h>
#include <NavigationBarItem.h>
#include <NavigationDrawer.h>
#include <FrameLayout.h>
#include <ProgressBar.h>
#include <FlipperLayout.h>
#include <ActionBar.h>
#include <TimerEvent.h>

#include "ImageDialog.h"

#include <iostream>

#define ID_CLICK_ME_BUTTON 1
#define ID_SHOW_MENU_BUTTON 2

using namespace std;

Example1::Example1() : FWApplication("com.sometrik.example1")
{
  createTimer(1000);

  actionBar = std::make_shared<ActionBar>();
  addChild(actionBar);

  navigationDrawer = std::make_shared<NavigationDrawer>();
  auto navigationLayout = std::make_shared<LinearLayout>(FW_VERTICAL);
  navigationDrawer->addChild(navigationLayout);
  navigationDrawer->style("background", "#cccccc");
  navigationLayout->addChild(make_shared<TextLabel>("Hello sidebar!"));
  navigationLayout->addChild(make_shared<Button>("OK"));
  addChild(navigationDrawer);

  auto view = std::make_shared<FrameView>();
  view->style("background-color", "#555555");
  addChild(view);

  auto flipper = std::make_shared<FlipperLayout>();
  view->addChild(flipper);

  auto firstPage = std::make_shared<LinearLayout>(FW_VERTICAL);
  flipper->addChild(firstPage);

  auto image = std::make_shared<ImageElement>("test.png");
  firstPage->addChild(image);

  auto title = make_shared<TextLabel>("Hello again!", 1234);
  title->style("font-size", 20);
  title->style("background-color", "#e03030");
  title->style("shadow", 5);
  title->style("border", "#801010");
  title->style("border-radius", 5);
  firstPage->addChild(title);

  auto nameLayout = make_shared<LinearLayout>(FW_HORIZONTAL);
  firstPage->addChild(nameLayout);
  nameLayout->addChild(make_shared<TextLabel>("Kirjoita nimesi:"));

  textField = make_shared<TextField>();
  nameLayout->addChild(textField);

  auto buttonLayout = std::make_shared<LinearLayout>(FW_HORIZONTAL);
  buttonLayout->addChild(make_shared<Button>("Click me!", ID_CLICK_ME_BUTTON)).style("background", "#30e030").style("border-radius", 5);
  buttonLayout->addChild(make_shared<Button>("Show menu", ID_SHOW_MENU_BUTTON));
  buttonLayout->addChild(make_shared<Button>("Useless button"));
  firstPage->addChild(buttonLayout);

  auto scrollLayout = std::make_shared<ScrollLayout>();
  scrollLayout->style("min-height", 200);
  firstPage->addChild(scrollLayout);
  scrollContent = std::make_shared<LinearLayout>(FW_VERTICAL);
  scrollLayout->addChild(scrollContent);

  for (int i = 0; i < 100; i++) {
    scrollContent->addChild(std::make_shared<TextLabel>("Number: " + to_string(i)));
  }

  firstPage->addChild(make_shared<Switch>("On", "Off"));

  auto navigationBar = std::make_shared<NavigationBar>();
  navigationBar->addChild(std::make_shared<NavigationBarItem>("Page 1"));
  navigationBar->addChild(std::make_shared<NavigationBarItem>("Page 2"));
  navigationBar->addChild(std::make_shared<NavigationBarItem>("Page 3"));

  view->addChild(navigationBar);

#if 1
  auto secondPage = std::make_shared<LinearLayout>(FW_VERTICAL);
  secondPage->style("background", "#e03030");
  flipper->addChild(secondPage);
  secondPage->addChild(make_shared<ProgressBar>());
#endif
}

void
Example1::onCommandEvent(CommandEvent & ev) {
  cerr << "got command event: " << ev.getElementId() << endl;
  switch (ev.getElementId()) {
    case ID_CLICK_ME_BUTTON: {
      cerr << "showing dialog" << endl;
      auto dialog = make_shared<ImageDialog>();
      dialog->showModal(this);
    }
      break;
    case ID_SHOW_MENU_BUTTON: {
      cerr << "showing menu" << endl;
      navigationDrawer->show();
    }
      break;
  }
}

void
Example1::onTimerEvent(TimerEvent & ev) {
#if 1
  auto & children = scrollContent->getChildren();
  cerr << "timer: front child = " << children.front()->getInternalId() << endl;
  scrollContent->reorderChildren(*(children.back()), 0);
  children.insert(children.begin(), children.back());
  children.pop_back();
#endif
}

FWApplication * applicationMain() {
  return new Example1();
}
<commit_msg>add icons<commit_after>#include "Example1.h"

#include <FrameView.h>
#include <TextLabel.h>
#include <LinearLayout.h>
#include <Button.h>
#include <ScrollLayout.h>
#include <Switch.h>
#include <TextField.h>
#include <ImageElement.h>
#include <NavigationBar.h>
#include <NavigationBarItem.h>
#include <NavigationDrawer.h>
#include <FrameLayout.h>
#include <ProgressBar.h>
#include <FlipperLayout.h>
#include <ActionBar.h>
#include <TimerEvent.h>

#include "ImageDialog.h"

#include <iostream>

#define ID_CLICK_ME_BUTTON 1
#define ID_SHOW_MENU_BUTTON 2

using namespace std;

Example1::Example1() : FWApplication("com.sometrik.example1")
{
  createTimer(1000);

  actionBar = std::make_shared<ActionBar>();
  addChild(actionBar);

  navigationDrawer = std::make_shared<NavigationDrawer>();
  auto navigationLayout = std::make_shared<LinearLayout>(FW_VERTICAL);
  navigationDrawer->addChild(navigationLayout);
  navigationDrawer->style("background", "#cccccc");
  navigationLayout->addChild(make_shared<TextLabel>("Hello sidebar!"));
  navigationLayout->addChild(make_shared<Button>("OK"));
  addChild(navigationDrawer);

  auto view = std::make_shared<FrameView>();
  view->style("background-color", "#555555");
  addChild(view);

  auto flipper = std::make_shared<FlipperLayout>();
  view->addChild(flipper);

  auto firstPage = std::make_shared<LinearLayout>(FW_VERTICAL);
  flipper->addChild(firstPage);

  auto image = std::make_shared<ImageElement>("test.png");
  firstPage->addChild(image);

  auto title = make_shared<TextLabel>("Hello again!", 1234);
  title->style("font-size", 20);
  title->style("background-color", "#e03030");
  title->style("shadow", 5);
  title->style("border", "#801010");
  title->style("border-radius", 5);
  firstPage->addChild(title);

  auto nameLayout = make_shared<LinearLayout>(FW_HORIZONTAL);
  firstPage->addChild(nameLayout);
  nameLayout->addChild(make_shared<TextLabel>("Kirjoita nimesi:"));

  textField = make_shared<TextField>();
  nameLayout->addChild(textField);

  auto buttonLayout = std::make_shared<LinearLayout>(FW_HORIZONTAL);
  buttonLayout->addChild(make_shared<Button>("Click me!", ID_CLICK_ME_BUTTON)).style("background", "#30e030").style("border-radius", 5);
  buttonLayout->addChild(make_shared<Button>("Show menu", ID_SHOW_MENU_BUTTON));
  buttonLayout->addChild(make_shared<Button>("Useless button")).style("icon", "button.png");
  firstPage->addChild(buttonLayout);

  auto scrollLayout = std::make_shared<ScrollLayout>();
  scrollLayout->style("min-height", 200);
  firstPage->addChild(scrollLayout);
  scrollContent = std::make_shared<LinearLayout>(FW_VERTICAL);
  scrollLayout->addChild(scrollContent);

  for (int i = 0; i < 100; i++) {
    scrollContent->addChild(std::make_shared<TextLabel>("Number: " + to_string(i)));
  }

  firstPage->addChild(make_shared<Switch>("On", "Off"));

  auto navigationBar = std::make_shared<NavigationBar>();
  navigationBar->addChild(std::make_shared<NavigationBarItem>("Page 1")).style("icon", "icon1.png");
  navigationBar->addChild(std::make_shared<NavigationBarItem>("Page 2")).style("icon", "icon2.png");
  navigationBar->addChild(std::make_shared<NavigationBarItem>("Page 3")).style("icon", "icon3.png");

  view->addChild(navigationBar);

#if 1
  auto secondPage = std::make_shared<LinearLayout>(FW_VERTICAL);
  secondPage->style("background", "#e03030");
  flipper->addChild(secondPage);
  secondPage->addChild(make_shared<ProgressBar>());
#endif
}

void
Example1::onCommandEvent(CommandEvent & ev) {
  cerr << "got command event: " << ev.getElementId() << endl;
  switch (ev.getElementId()) {
    case ID_CLICK_ME_BUTTON: {
      cerr << "showing dialog" << endl;
      auto dialog = make_shared<ImageDialog>();
      dialog->showModal(this);
    }
      break;
    case ID_SHOW_MENU_BUTTON: {
      cerr << "showing menu" << endl;
      navigationDrawer->show();
    }
      break;
  }
}

void
Example1::onTimerEvent(TimerEvent & ev) {
#if 1
  auto & children = scrollContent->getChildren();
  cerr << "timer: front child = " << children.front()->getInternalId() << endl;
  scrollContent->reorderChildren(*(children.back()), 0);
  children.insert(children.begin(), children.back());
  children.pop_back();
#endif
}

FWApplication * applicationMain() {
  return new Example1();
}
<|endoftext|>


<commit_before>#include <vector>

#include <boost/range/algorithm.hpp>
#include <lib/amgcl.h>
#include "sample_problem.hpp"

int main() {
    std::vector<int>    ptr;
    std::vector<int>    col;
    std::vector<double> val;
    std::vector<double> rhs;

    int n = sample_problem(128l, val, col, ptr, rhs);

    amgclHandle prm = amgcl_params_create();
    amgcl_params_seti(prm, "coarse_enough", 1000);
    amgcl_params_setf(prm, "aggr.eps_strong", 1e-3);

    amgclHandle amg = amgcl_precond_create(
            amgclBackendBuiltin,
            amgclCoarseningSmoothedAggregation,
            amgclRelaxationSPAI0,
            prm,
            n, ptr.data(), col.data(), val.data()
            );

    amgcl_params_seti(prm, "L", 1);
    amgclHandle solver = amgcl_solver_create(
            amgclBackendBuiltin,
            amgclSolverBiCGStabL,
            prm, n
            );

    std::vector<double> x(n, 0);
    amgcl_solver_solve(solver, amg, rhs.data(), x.data());

    // Solve same problem again, but explicitly provide the matrix this time:
    boost::fill(x, 0);
    amgcl_solver_solve_mtx(solver, ptr.data(), col.data(), val.data(), amg,
            rhs.data(), x.data());

    amgcl_solver_destroy(solver);
    amgcl_precond_destroy(amg);
    amgcl_params_destroy(prm);
}
<commit_msg>Fix parameter name in call_lib.cpp<commit_after>#include <vector>

#include <boost/range/algorithm.hpp>
#include <lib/amgcl.h>
#include "sample_problem.hpp"

int main() {
    std::vector<int>    ptr;
    std::vector<int>    col;
    std::vector<double> val;
    std::vector<double> rhs;

    int n = sample_problem(128l, val, col, ptr, rhs);

    amgclHandle prm = amgcl_params_create();
    amgcl_params_seti(prm, "coarse_enough", 1000);
    amgcl_params_setf(prm, "coarsening.aggr.eps_strong", 1e-3);

    amgclHandle amg = amgcl_precond_create(
            amgclBackendBuiltin,
            amgclCoarseningSmoothedAggregation,
            amgclRelaxationSPAI0,
            prm,
            n, ptr.data(), col.data(), val.data()
            );

    amgcl_params_seti(prm, "L", 1);
    amgclHandle solver = amgcl_solver_create(
            amgclBackendBuiltin,
            amgclSolverBiCGStabL,
            prm, n
            );

    std::vector<double> x(n, 0);
    amgcl_solver_solve(solver, amg, rhs.data(), x.data());

    // Solve same problem again, but explicitly provide the matrix this time:
    boost::fill(x, 0);
    amgcl_solver_solve_mtx(solver, ptr.data(), col.data(), val.data(), amg,
            rhs.data(), x.data());

    amgcl_solver_destroy(solver);
    amgcl_precond_destroy(amg);
    amgcl_params_destroy(prm);
}
<|endoftext|>


<commit_before>#include "../base/base.hpp"

// Similarly to namespace m2 - 2d math, this is a namespace for nd math.
namespace mn
{

template <typename PointT> class DistanceToLineSquare
{
public:
  DistanceToLineSquare(PointT p0, PointT p1)
    : m_P0(p0), m_P1(p1), m_D(m_P1 - m_P0), m_D2(DotProduct(m_D, m_D)), m_InvD2(1.0 / m_D2)
  {
  }

  double operator () (PointT Y) const
  {
    PointT const YmP0 = Y - m_P0;
    double const t = DotProduct(m_D, YmP0);
    if (t <= 0)
    {
      // Y is closest to P0.
      return DotProduct(YmP0, YmP0);
    }
    if (t >= m_D2)
    {
      // Y is closest to P1.
      PointT const YmP1 = Y - m_P1;
      return DotProduct(YmP1, YmP1);
    }
    // Closest point is interior to segment.
    return DotProduct(YmP0, YmP0) - t * t * m_InvD2;
  }
private:
  PointT m_P0, m_P1, m_D;
  double m_D2, m_InvD2;
};

}
<commit_msg>Include guard.<commit_after>#pragma once
#include "../base/base.hpp"

// Similarly to namespace m2 - 2d math, this is a namespace for nd math.
namespace mn
{

template <typename PointT> class DistanceToLineSquare
{
public:
  DistanceToLineSquare(PointT p0, PointT p1)
    : m_P0(p0), m_P1(p1), m_D(m_P1 - m_P0), m_D2(DotProduct(m_D, m_D)), m_InvD2(1.0 / m_D2)
  {
  }

  double operator () (PointT Y) const
  {
    PointT const YmP0 = Y - m_P0;
    double const t = DotProduct(m_D, YmP0);
    if (t <= 0)
    {
      // Y is closest to P0.
      return DotProduct(YmP0, YmP0);
    }
    if (t >= m_D2)
    {
      // Y is closest to P1.
      PointT const YmP1 = Y - m_P1;
      return DotProduct(YmP1, YmP1);
    }
    // Closest point is interior to segment.
    return DotProduct(YmP0, YmP0) - t * t * m_InvD2;
  }
private:
  PointT m_P0, m_P1, m_D;
  double m_D2, m_InvD2;
};

}
<|endoftext|>


<commit_before>/**
 * \file getcover.cpp
 * \brief implementation for class GetCover
 */
#include "getcover.h"
#include "yoseshm.h"

#include <QImage>
#include <QDebug>
#include <QRegExp>
#include <QFile>
#include <QCryptographicHash>

// taglib headers {
#include <taglib/taglib.h>
#include <taglib/tmap.h>
#include <taglib/tstring.h>
//#include <taglib/tpropertymap.h>
#include <taglib/id3v1tag.h>
#include <taglib/id3v2tag.h>
#include <taglib/mpegfile.h>
#include <taglib/id3v2frame.h>
#include <taglib/attachedpictureframe.h>
#include <taglib/mp4file.h>
#include <taglib/mp4tag.h>
#include <taglib/mp4coverart.h>
// taglib headers }

#define DEFAULT_BUFFER_SIZE     (512)
char buffer[DEFAULT_BUFFER_SIZE];

/// default will output tb
bool GetCover::m_writetb = true;
bool GetCover::m_followtype = false;
bool GetCover::m_resizetb = false;

GetCover::GetCover()
{
}

void GetCover::save_hash(const QString& hash)
{
    qDebug() << Q_FUNC_INFO << "=>" << hash;
    QByteArray arr = hash.toLocal8Bit();
    qDebug() << arr.size() << arr.constData();
    myShm::saveToShm(arr.size(), (const char*)arr.constData());
}
QString GetCover::load_hash()
{
    QString ret = "";

    uint32_t size = 0;
    myShm::readFromShm(size, buffer);
    QByteArray arr((char*)buffer, (int)size);
    ret.append(arr);
    return ret;
}
QString GetCover::get_thumb_name(const QString& hstr)
{
    QString res = QString("/tmp/") + hstr + QString(".png");
    return res;
}
QString GetCover::md5sum(const char* buffer, int size)
{
    QCryptographicHash hash( QCryptographicHash::Md5 );
    hash.addData(buffer, size);
    QString str_hash = hash.result().toHex().data();
    return str_hash;
}

QString GetCover::get_hash_filename(const QString& fn)
{
    QCryptographicHash hash( QCryptographicHash::Md5 );
    hash.addData(fn.toStdString().c_str(), fn.length());
    QString str_hash = hash.result().toHex().data();
    return str_hash;
}

bool GetCover::getcover(const QString& fn, QString& tbfn)
{
    QFile fileobj(fn);
    //fileobj.setFileName(tbfn);
    if (!fileobj.exists()) {
        qDebug() << fn << "not exists";
        return false;
    }

    QRegExp rxmp3("\\.mp3$");
    QRegExp rxm4a("\\.m4a$");
    bool ret = false;

    if (fn.contains(rxmp3)) {
        //qDebug() << "call extract_cover_from_mp3()...";
        ret = extract_cover_from_mp3(fn, tbfn);
    } else if (fn.contains(rxm4a)) {
        //qDebug() << "call extract_cover_from_mp4()...";
        ret = extract_cover_from_mp4(fn, tbfn);
    }

    return ret;
}

bool GetCover::extract_cover_from_mp3(const QString& fn, QString& tbfn)
{
    TagLib::MPEG::File file(fn.toStdString().c_str());
    tbfn = "";
    if (!file.isValid()) {
        //qDebug() << "file is invalid";
        return false;
    }
    if (!file.hasID3v2Tag()) {
        return false;
    }

    //qDebug() << "id3v2 tag...";
    TagLib::ID3v2::Tag *tag = file.ID3v2Tag();
    // m_artist = tag->artist().toCString(true);
    // m_album = tag->album().toCString(true);
    // m_title = tag->title().toCString(true);
    TagLib::ID3v2::FrameList frames = tag->frameListMap()["APIC"];
    if (frames.isEmpty()) {
        //qDebug() << "APIC frame is empty";
        return false;
    }
/*
      ID3v2::FrameList::ConstIterator it = id3v2tag->frameList().begin();
      for(; it != id3v2tag->frameList().end(); it++)
        cout << (*it)->frameID() << " - \"" << (*it)->toString() << "\"" << endl;
*/
    TagLib::ID3v2::FrameList::ConstIterator it = frames.begin();
    //cout << (*it)->frameID() << "==>" << (*it)->toString();
    QString tbtype = (*it)->toString().toCString(); // shows: APIC
    qDebug() << (*it)->frameID().data() << "type:" << tbtype;   // shows: images/jpeg
    //cast Frame * to AttachedPictureFrame*
    TagLib::ID3v2::AttachedPictureFrame *pf = static_cast<TagLib::ID3v2::AttachedPictureFrame *> (*it);
    if (pf == NULL) {
        //qDebug() << "getMP3Frame: pf is null";
        return false;
    }
    bool isJpeg = tbtype.contains("jpeg");
    /// _img is the original thumbnail from media file
    QImage _img;
    _img.loadFromData((const uchar*)pf->picture().data(), pf->picture().size());
    bool ret = save_thumbnail(_img, tbfn, isJpeg);

    return ret;
}

/**
    \return true if thumbnail extracted, false if no thumbnail
**/
bool GetCover::extract_cover_from_mp4(const QString& fn, QString& tbfn)
{
    TagLib::MP4::File file(fn.toStdString().c_str());
    TagLib::MP4::Tag *tag = file.tag();
    tbfn = "";
    if (tag == NULL) {
        //qDebug() << "tag is null";
        return false;
    }
    // m_artist = tag->artist().toCString(true);
    // m_album = tag->album().toCString(true);
    // m_title = tag->title().toCString(true);
    /// get covr from m4a
    if ( !tag->itemListMap().contains("covr") ) {
        //qDebug() << "no covr";
        return false;
    }

    //qDebug() << "get covr...";
    TagLib::MP4::CoverArtList list = tag->itemListMap()["covr"].toCoverArtList();
    // const char *psz_format = list[0].format() == TagLib::MP4::CoverArt::PNG ? "image/png" : "image/jpeg";
    // (void)psz_format;
    bool isJpeg = (list[0].format() == TagLib::MP4::CoverArt::JPEG);
//    qDebug() << "id3tag: mp4: found embedded art: " << psz_format << ", "
//             << list[0].data().size() << "bytes";
    QImage _img;
    _img.loadFromData((const uchar *)list[0].data().data(), list[0].data().size());
    //QString confmd5 = ();

    bool ret = save_thumbnail(_img, tbfn, isJpeg);
    return ret;
}

bool GetCover::save_thumbnail(const QImage& img, QString& tbfn, bool isJpeg)
{
    QString hstr = md5sum((const char*)img.constBits(), img.byteCount());
    //qDebug() << "hstr:" << hstr;
    tbfn = get_thumb_name(hstr);
    //qDebug() << "tbfn:" << hstr;
    if ( isFileExisted(tbfn) ) {
        //qDebug() << "such thumbnail existed, don't save and report last tbfn:" << tbfn;
        return true;
    }

    const int DEFAULT_SHRINK_WIDTH = 800;
    const int DEFAULT_SHRINK_HEIGHT = 800;
    if (m_writetb) {
        // m_resizetb will ignore m_followtype
        if (m_resizetb) {
            QImage resized_img = img.scaled(
                QSize(DEFAULT_SHRINK_WIDTH, DEFAULT_SHRINK_HEIGHT),
                Qt::KeepAspectRatio);
            resized_img.save(tbfn, "PNG");
        } else {
            if (m_followtype && isJpeg) {
                    img.save(tbfn, "JPG");
            } else {
                img.save(tbfn, "PNG");
            }
        }
    } else {
        qDebug() << "will not save tb...";
    }

    //qDebug() << "thumbnail:" << tbfn;
    return true;
}

bool GetCover::isFileExisted(const QString& fn)
{
    QFile fileobj(fn);
    return fileobj.exists();
}

void GetCover::setWriteTb(bool b)
{
    m_writetb = b;
}
void GetCover::setFollowImageType(bool b)
{
    m_followtype = b;
}
void GetCover::setResizeTb(bool b)
{
    m_resizetb = b;
}
void GetCover::show_toggles()
{
    qDebug() << "m_writetb" << (m_writetb?"on":"off")
        << "m_followtype" << (m_followtype?"on":"off")
        << "m_resizetb" << (m_resizetb?"on":"off");
}
<commit_msg>add TODO and comment<commit_after>/**
 * \file getcover.cpp
 * \brief implementation for class GetCover
 */
#include "getcover.h"
#include "yoseshm.h"

#include <QImage>
#include <QDebug>
#include <QRegExp>
#include <QFile>
#include <QCryptographicHash>

// taglib headers {
#include <taglib/taglib.h>
#include <taglib/tmap.h>
#include <taglib/tstring.h>
//#include <taglib/tpropertymap.h>
#include <taglib/id3v1tag.h>
#include <taglib/id3v2tag.h>
#include <taglib/mpegfile.h>
#include <taglib/id3v2frame.h>
#include <taglib/attachedpictureframe.h>
#include <taglib/mp4file.h>
#include <taglib/mp4tag.h>
#include <taglib/mp4coverart.h>
// taglib headers }

#define DEFAULT_BUFFER_SIZE     (512)
char buffer[DEFAULT_BUFFER_SIZE];

/// default will output tb
bool GetCover::m_writetb = true;
bool GetCover::m_followtype = false;
bool GetCover::m_resizetb = false;

GetCover::GetCover()
{
}

void GetCover::save_hash(const QString& hash)
{
    qDebug() << Q_FUNC_INFO << "=>" << hash;
    QByteArray arr = hash.toLocal8Bit();
    qDebug() << arr.size() << arr.constData();
    myShm::saveToShm(arr.size(), (const char*)arr.constData());
}
QString GetCover::load_hash()
{
    QString ret = "";

    uint32_t size = 0;
    myShm::readFromShm(size, buffer);
    QByteArray arr((char*)buffer, (int)size);
    ret.append(arr);
    return ret;
}
QString GetCover::get_thumb_name(const QString& hstr)
{
    QString res = QString("/tmp/") + hstr + QString(".png");
    return res;
}
QString GetCover::md5sum(const char* buffer, int size)
{
    QCryptographicHash hash( QCryptographicHash::Md5 );
    hash.addData(buffer, size);
    QString str_hash = hash.result().toHex().data();
    return str_hash;
}

QString GetCover::get_hash_filename(const QString& fn)
{
    QCryptographicHash hash( QCryptographicHash::Md5 );
    hash.addData(fn.toStdString().c_str(), fn.length());
    QString str_hash = hash.result().toHex().data();
    return str_hash;
}

bool GetCover::getcover(const QString& fn, QString& tbfn)
{
    QFile fileobj(fn);
    //fileobj.setFileName(tbfn);
    if (!fileobj.exists()) {
        qDebug() << fn << "not exists";
        return false;
    }

    QRegExp rxmp3("\\.mp3$");
    QRegExp rxm4a("\\.m4a$");
    bool ret = false;

    if (fn.contains(rxmp3)) {
        //qDebug() << "call extract_cover_from_mp3()...";
        ret = extract_cover_from_mp3(fn, tbfn);
    } else if (fn.contains(rxm4a)) {
        //qDebug() << "call extract_cover_from_mp4()...";
        ret = extract_cover_from_mp4(fn, tbfn);
    }
    // TODO: add function to extract flac album
    // http://stackoverflow.com/questions/7119073/c-taglib-cover-art-from-flac-and-asf-files

    return ret;
}

/// fn [in] path to media file to be extracted album art
/// tbfn [out] path to extracted album art
/// bool: true if successful, false if failed
bool GetCover::extract_cover_from_mp3(const QString& fn, QString& tbfn)
{
    TagLib::MPEG::File file(fn.toStdString().c_str());
    tbfn = "";
    if (!file.isValid()) {
        //qDebug() << "file is invalid";
        return false;
    }
    if (!file.hasID3v2Tag()) {
        return false;
    }

    //qDebug() << "id3v2 tag...";
    TagLib::ID3v2::Tag *tag = file.ID3v2Tag();
    // m_artist = tag->artist().toCString(true);
    // m_album = tag->album().toCString(true);
    // m_title = tag->title().toCString(true);
    TagLib::ID3v2::FrameList frames = tag->frameListMap()["APIC"];
    if (frames.isEmpty()) {
        //qDebug() << "APIC frame is empty";
        return false;
    }
/*
      ID3v2::FrameList::ConstIterator it = id3v2tag->frameList().begin();
      for(; it != id3v2tag->frameList().end(); it++)
        cout << (*it)->frameID() << " - \"" << (*it)->toString() << "\"" << endl;
*/
    TagLib::ID3v2::FrameList::ConstIterator it = frames.begin();
    //cout << (*it)->frameID() << "==>" << (*it)->toString();
    QString tbtype = (*it)->toString().toCString(); // shows: APIC
    qDebug() << (*it)->frameID().data() << "type:" << tbtype;   // shows: images/jpeg
    //cast Frame * to AttachedPictureFrame*
    TagLib::ID3v2::AttachedPictureFrame *pf = static_cast<TagLib::ID3v2::AttachedPictureFrame *> (*it);
    if (pf == NULL) {
        //qDebug() << "getMP3Frame: pf is null";
        return false;
    }
    bool isJpeg = tbtype.contains("jpeg");
    /// _img is the original thumbnail from media file
    QImage _img;
    _img.loadFromData((const uchar*)pf->picture().data(), pf->picture().size());
    bool ret = save_thumbnail(_img, tbfn, isJpeg);

    return ret;
}

/**
    \return true if thumbnail extracted, false if no thumbnail
**/
bool GetCover::extract_cover_from_mp4(const QString& fn, QString& tbfn)
{
    TagLib::MP4::File file(fn.toStdString().c_str());
    TagLib::MP4::Tag *tag = file.tag();
    tbfn = "";
    if (tag == NULL) {
        //qDebug() << "tag is null";
        return false;
    }
    // m_artist = tag->artist().toCString(true);
    // m_album = tag->album().toCString(true);
    // m_title = tag->title().toCString(true);
    /// get covr from m4a
    if ( !tag->itemListMap().contains("covr") ) {
        //qDebug() << "no covr";
        return false;
    }

    //qDebug() << "get covr...";
    TagLib::MP4::CoverArtList list = tag->itemListMap()["covr"].toCoverArtList();
    // const char *psz_format = list[0].format() == TagLib::MP4::CoverArt::PNG ? "image/png" : "image/jpeg";
    // (void)psz_format;
    bool isJpeg = (list[0].format() == TagLib::MP4::CoverArt::JPEG);
//    qDebug() << "id3tag: mp4: found embedded art: " << psz_format << ", "
//             << list[0].data().size() << "bytes";
    QImage _img;
    _img.loadFromData((const uchar *)list[0].data().data(), list[0].data().size());
    //QString confmd5 = ();

    bool ret = save_thumbnail(_img, tbfn, isJpeg);
    return ret;
}

bool GetCover::save_thumbnail(const QImage& img, QString& tbfn, bool isJpeg)
{
    QString hstr = md5sum((const char*)img.constBits(), img.byteCount());
    //qDebug() << "hstr:" << hstr;
    tbfn = get_thumb_name(hstr);
    //qDebug() << "tbfn:" << hstr;
    if ( isFileExisted(tbfn) ) {
        //qDebug() << "such thumbnail existed, don't save and report last tbfn:" << tbfn;
        return true;
    }

    const int DEFAULT_SHRINK_WIDTH = 800;
    const int DEFAULT_SHRINK_HEIGHT = 800;
    if (m_writetb) {
        // m_resizetb will ignore m_followtype
        if (m_resizetb) {
            QImage resized_img = img.scaled(
                QSize(DEFAULT_SHRINK_WIDTH, DEFAULT_SHRINK_HEIGHT),
                Qt::KeepAspectRatio);
            resized_img.save(tbfn, "PNG");
        } else {
            if (m_followtype && isJpeg) {
                    img.save(tbfn, "JPG");
            } else {
                img.save(tbfn, "PNG");
            }
        }
    } else {
        qDebug() << "will not save tb...";
    }

    //qDebug() << "thumbnail:" << tbfn;
    return true;
}

bool GetCover::isFileExisted(const QString& fn)
{
    QFile fileobj(fn);
    return fileobj.exists();
}

void GetCover::setWriteTb(bool b)
{
    m_writetb = b;
}
void GetCover::setFollowImageType(bool b)
{
    m_followtype = b;
}
void GetCover::setResizeTb(bool b)
{
    m_resizetb = b;
}
void GetCover::show_toggles()
{
    qDebug() << "m_writetb" << (m_writetb?"on":"off")
        << "m_followtype" << (m_followtype?"on":"off")
        << "m_resizetb" << (m_resizetb?"on":"off");
}
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2010, Intel Corporation.
 *
 * Author: Raymond Liu <raymond.liu@intel.com>
 *
 *
 * 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., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA
 */

#include "debug.h"
#include <QEvent>
#include <QKeyEvent>

#include "qt-keysym-map.h"
#include "qt-gtk-translate.h"

GdkEventKey *
compose_gdk_keyevent(GdkEventType type, guint keyval, guint state, GdkWindow *window)
{
	GdkEventKey *event = NULL;

	if ((type != GDK_KEY_PRESS) && (type != GDK_KEY_RELEASE))
		return NULL;

	event = (GdkEventKey *)(gdk_event_new(type));
	event->length = 0;
	event->string = 0;
	event->is_modifier = 0;
	event->time = GDK_CURRENT_TIME;
	event->state = state;
	if (type == GDK_KEY_RELEASE)
		event->state |= GDK_RELEASE_MASK;
	event->keyval = keyval;
	event->window = window;

	if (event->window) {
		GdkKeymap *key_map = gdk_keymap_get_default();
		GdkKeymapKey *keys;
		gint n;

		g_object_ref(event->window); // seems when event is freed, the event->window will be unref

		if (gdk_keymap_get_entries_for_keyval(key_map, event->keyval, &keys, &n)) {
			event->hardware_keycode = keys[0].keycode;
			event->group = keys[0].group;
		} else {
			event->hardware_keycode = 0;
			event->group = 0;
		}
	}

	DBG("event type=0x%x, state=0x%x, keyval=0x%x, keycode=0x%x, group=%d",
		event->type, event->state, event->keyval, event->hardware_keycode, event->group);

	return event;
}

GdkEventKey *
qt_key_event_to_gdk(int type, int key, int modifiers, char *text, GdkWindow *window)
{
	guint state = 0;
	guint keyval;

	STEP();
	if ((type != QEvent::KeyPress) && (type != QEvent::KeyRelease))
		return NULL;

	if (modifiers & Qt::ShiftModifier)
		state |= GDK_SHIFT_MASK;
	if (modifiers & Qt::ControlModifier)
		state |= GDK_CONTROL_MASK;
	if (modifiers & Qt::AltModifier)
		state |= GDK_MOD1_MASK;

	keyval = QtKeyToXKeySym(key);

	if (type == QEvent::KeyPress) {
		return compose_gdk_keyevent(GDK_KEY_PRESS, keyval, state, window);
	} else {
		return compose_gdk_keyevent(GDK_KEY_RELEASE, keyval, state, window);
	}

}

gboolean
gdk_key_event_to_qt(GdkEventKey *event, int *type, int *key, int *modifier)
{

	switch (event->type) {
	case GDK_KEY_PRESS:
		*type = QEvent::KeyPress;
		break;
	case GDK_KEY_RELEASE:
		*type = QEvent::KeyRelease;
		break;
	default:
		return FALSE;
	}

	*key = XKeySymToQTKey(event->keyval);
	if (*key == Qt::Key_unknown) {
		qWarning("Unkonwn key");
		return FALSE;
	}

	*modifier = Qt::NoModifier;
	if (event->state & GDK_SHIFT_MASK)
		*modifier |= Qt::ShiftModifier;
	if (event->state & GDK_CONTROL_MASK)
		*modifier |= Qt::ControlModifier;
	if (event->state & GDK_MOD1_MASK)
		*modifier |= Qt::AltModifier;
	if (event->state & GDK_META_MASK)
		*modifier |= Qt::MetaModifier;

	DBG("qtkey type =%d, qtkey=0x%x, modifier=0x%x", *type, *key, *modifier);

	return TRUE;
}
<commit_msg>Workaround a build issue for glib >= 2.25<commit_after>/*
 * Copyright (C) 2010, Intel Corporation.
 *
 * Author: Raymond Liu <raymond.liu@intel.com>
 *
 *
 * 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., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA
 */

#include "debug.h"
#include <QEvent>
#include <QKeyEvent>

#include "qt-keysym-map.h"

// To workaround glib >= 2.25 where signals is used, while QT already define it as C++ keyword: protected
#ifdef signals
#undef signals
#endif
#include "qt-gtk-translate.h"

GdkEventKey *
compose_gdk_keyevent(GdkEventType type, guint keyval, guint state, GdkWindow *window)
{
	GdkEventKey *event = NULL;

	if ((type != GDK_KEY_PRESS) && (type != GDK_KEY_RELEASE))
		return NULL;

	event = (GdkEventKey *)(gdk_event_new(type));
	event->length = 0;
	event->string = 0;
	event->is_modifier = 0;
	event->time = GDK_CURRENT_TIME;
	event->state = state;
	if (type == GDK_KEY_RELEASE)
		event->state |= GDK_RELEASE_MASK;
	event->keyval = keyval;
	event->window = window;

	if (event->window) {
		GdkKeymap *key_map = gdk_keymap_get_default();
		GdkKeymapKey *keys;
		gint n;

		g_object_ref(event->window); // seems when event is freed, the event->window will be unref

		if (gdk_keymap_get_entries_for_keyval(key_map, event->keyval, &keys, &n)) {
			event->hardware_keycode = keys[0].keycode;
			event->group = keys[0].group;
		} else {
			event->hardware_keycode = 0;
			event->group = 0;
		}
	}

	DBG("event type=0x%x, state=0x%x, keyval=0x%x, keycode=0x%x, group=%d",
		event->type, event->state, event->keyval, event->hardware_keycode, event->group);

	return event;
}

GdkEventKey *
qt_key_event_to_gdk(int type, int key, int modifiers, char *text, GdkWindow *window)
{
	guint state = 0;
	guint keyval;

	STEP();
	if ((type != QEvent::KeyPress) && (type != QEvent::KeyRelease))
		return NULL;

	if (modifiers & Qt::ShiftModifier)
		state |= GDK_SHIFT_MASK;
	if (modifiers & Qt::ControlModifier)
		state |= GDK_CONTROL_MASK;
	if (modifiers & Qt::AltModifier)
		state |= GDK_MOD1_MASK;

	keyval = QtKeyToXKeySym(key);

	if (type == QEvent::KeyPress) {
		return compose_gdk_keyevent(GDK_KEY_PRESS, keyval, state, window);
	} else {
		return compose_gdk_keyevent(GDK_KEY_RELEASE, keyval, state, window);
	}

}

gboolean
gdk_key_event_to_qt(GdkEventKey *event, int *type, int *key, int *modifier)
{

	switch (event->type) {
	case GDK_KEY_PRESS:
		*type = QEvent::KeyPress;
		break;
	case GDK_KEY_RELEASE:
		*type = QEvent::KeyRelease;
		break;
	default:
		return FALSE;
	}

	*key = XKeySymToQTKey(event->keyval);
	if (*key == Qt::Key_unknown) {
		qWarning("Unkonwn key");
		return FALSE;
	}

	*modifier = Qt::NoModifier;
	if (event->state & GDK_SHIFT_MASK)
		*modifier |= Qt::ShiftModifier;
	if (event->state & GDK_CONTROL_MASK)
		*modifier |= Qt::ControlModifier;
	if (event->state & GDK_MOD1_MASK)
		*modifier |= Qt::AltModifier;
	if (event->state & GDK_META_MASK)
		*modifier |= Qt::MetaModifier;

	DBG("qtkey type =%d, qtkey=0x%x, modifier=0x%x", *type, *key, *modifier);

	return TRUE;
}
<|endoftext|>


<commit_before>// Copyright (c) 2006-2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "webkit/glue/glue_serialize.h"

#include <string>

#include "base/pickle.h"
#include "base/utf_string_conversions.h"
#include "googleurl/src/gurl.h"
#include "third_party/WebKit/WebKit/chromium/public/WebData.h"
#include "third_party/WebKit/WebKit/chromium/public/WebHistoryItem.h"
#include "third_party/WebKit/WebKit/chromium/public/WebHTTPBody.h"
#include "third_party/WebKit/WebKit/chromium/public/WebPoint.h"
#include "third_party/WebKit/WebKit/chromium/public/WebString.h"
#include "third_party/WebKit/WebKit/chromium/public/WebVector.h"
#include "webkit/glue/webkit_glue.h"

using WebKit::WebData;
using WebKit::WebHistoryItem;
using WebKit::WebHTTPBody;
using WebKit::WebPoint;
using WebKit::WebString;
using WebKit::WebUChar;
using WebKit::WebVector;

namespace webkit_glue {

struct SerializeObject {
  SerializeObject() : iter(NULL) {}
  SerializeObject(const char* data, int len) : pickle(data, len), iter(NULL) {}

  std::string GetAsString() {
    return std::string(static_cast<const char*>(pickle.data()), pickle.size());
  }

  Pickle pickle;
  mutable void* iter;
  mutable int version;
};

// TODO(mpcomplete): obsolete versions 1 and 2 after 1/1/2008.
// Version ID used in reading/writing history items.
// 1: Initial revision.
// 2: Added case for NULL string versus "". Version 2 code can read Version 1
//    data, but not vice versa.
// 3: Version 2 was broken, it stored number of WebUChars, not number of bytes.
//    This version checks and reads v1 and v2 correctly.
// 4: Adds support for storing FormData::identifier().
// 5: Adds support for empty FormData
// Should be const, but unit tests may modify it.
//
// NOTE: If the version is -1, then the pickle contains only a URL string.
// See CreateHistoryStateForURL.
//
int kVersion = 5;

// A bunch of convenience functions to read/write to SerializeObjects.
// The serializers assume the input data is in the correct format and so does
// no error checking.
inline void WriteData(const void* data, int length, SerializeObject* obj) {
  obj->pickle.WriteData(static_cast<const char*>(data), length);
}

inline void ReadData(const SerializeObject* obj, const void** data,
                     int* length) {
  const char* tmp = NULL;
  obj->pickle.ReadData(&obj->iter, &tmp, length);
  *data = tmp;
}

inline bool ReadBytes(const SerializeObject* obj, const void** data,
                     int length) {
  const char *tmp;
  if (!obj->pickle.ReadBytes(&obj->iter, &tmp, length))
    return false;
  *data = tmp;
  return true;
}

inline void WriteInteger(int data, SerializeObject* obj) {
  obj->pickle.WriteInt(data);
}

inline int ReadInteger(const SerializeObject* obj) {
  int tmp = 0;
  obj->pickle.ReadInt(&obj->iter, &tmp);
  return tmp;
}

inline void WriteInteger64(int64 data, SerializeObject* obj) {
  obj->pickle.WriteInt64(data);
}

inline int64 ReadInteger64(const SerializeObject* obj) {
  int64 tmp = 0;
  obj->pickle.ReadInt64(&obj->iter, &tmp);
  return tmp;
}

inline void WriteReal(double data, SerializeObject* obj) {
  WriteData(&data, sizeof(double), obj);
}

inline double ReadReal(const SerializeObject* obj) {
  const void* tmp;
  int length = 0;
  ReadData(obj, &tmp, &length);
  if (length > 0 && length >= static_cast<int>(sizeof(0.0)))
    return *static_cast<const double*>(tmp);
  else
    return 0.0;
}

inline void WriteBoolean(bool data, SerializeObject* obj) {
  obj->pickle.WriteInt(data ? 1 : 0);
}

inline bool ReadBoolean(const SerializeObject* obj) {
  bool tmp = false;
  obj->pickle.ReadBool(&obj->iter, &tmp);
  return tmp;
}

inline void WriteGURL(const GURL& url, SerializeObject* obj) {
  obj->pickle.WriteString(url.possibly_invalid_spec());
}

inline GURL ReadGURL(const SerializeObject* obj) {
  std::string spec;
  obj->pickle.ReadString(&obj->iter, &spec);
  return GURL(spec);
}

// Read/WriteString pickle the WebString as <int length><WebUChar* data>.
// If length == -1, then the WebString itself is NULL (WebString()).
// Otherwise the length is the number of WebUChars (not bytes) in the WebString.
inline void WriteString(const WebString& str, SerializeObject* obj) {
  switch (kVersion) {
    case 1:
      // Version 1 writes <length in bytes><string data>.
      // It saves WebString() and "" as "".
      obj->pickle.WriteInt(str.length() * sizeof(WebUChar));
      obj->pickle.WriteBytes(str.data(), str.length() * sizeof(WebUChar));
      break;
    case 2:
      // Version 2 writes <length in WebUChar><string data>.
      // It uses -1 in the length field to mean WebString().
      if (str.isNull()) {
        obj->pickle.WriteInt(-1);
      } else {
        obj->pickle.WriteInt(str.length());
        obj->pickle.WriteBytes(str.data(),
                               str.length() * sizeof(WebUChar));
      }
      break;
    default:
      // Version 3+ writes <length in bytes><string data>.
      // It uses -1 in the length field to mean WebString().
      if (str.isNull()) {
        obj->pickle.WriteInt(-1);
      } else {
        obj->pickle.WriteInt(str.length() * sizeof(WebUChar));
        obj->pickle.WriteBytes(str.data(),
                               str.length() * sizeof(WebUChar));
      }
      break;
  }
}

// This reads a serialized WebString from obj. If a string can't be read,
// WebString() is returned.
inline WebString ReadString(const SerializeObject* obj) {
  int length;

  // Versions 1, 2, and 3 all start with an integer.
  if (!obj->pickle.ReadInt(&obj->iter, &length))
    return WebString();

  // Starting with version 2, -1 means WebString().
  if (length == -1)
    return WebString();

  // In version 2, the length field was the length in WebUChars.
  // In version 1 and 3 it is the length in bytes.
  int bytes = ((obj->version == 2) ? length * sizeof(WebUChar) : length);

  const void* data;
  if (!ReadBytes(obj, &data, bytes))
    return WebString();
  return WebString(static_cast<const WebUChar*>(data), bytes / sizeof(WebUChar));
}

// Writes a Vector of Strings into a SerializeObject for serialization.
static void WriteStringVector(
    const WebVector<WebString>& data, SerializeObject* obj) {
  WriteInteger(static_cast<int>(data.size()), obj);
  for (size_t i = 0, c = data.size(); i < c; ++i) {
    unsigned ui = static_cast<unsigned>(i);  // sigh
    WriteString(data[ui], obj);
  }
}

static WebVector<WebString> ReadStringVector(const SerializeObject* obj) {
  int num_elements = ReadInteger(obj);
  WebVector<WebString> result(static_cast<size_t>(num_elements));
  for (int i = 0; i < num_elements; ++i)
    result[i] = ReadString(obj);
  return result;
}

// Writes a FormData object into a SerializeObject for serialization.
static void WriteFormData(const WebHTTPBody& http_body, SerializeObject* obj) {
  WriteBoolean(!http_body.isNull(), obj);

  if (http_body.isNull())
    return;

  WriteInteger(static_cast<int>(http_body.elementCount()), obj);
  WebHTTPBody::Element element;
  for (size_t i = 0; http_body.elementAt(i, element); ++i) {
    WriteInteger(element.type, obj);
    if (element.type == WebHTTPBody::Element::TypeData) {
      WriteData(element.data.data(), static_cast<int>(element.data.size()),
                obj);
    } else {
      WriteString(element.filePath, obj);
    }
  }
  WriteInteger64(http_body.identifier(), obj);
}

static WebHTTPBody ReadFormData(const SerializeObject* obj) {
  // In newer versions, an initial boolean indicates if we have form data.
  if (obj->version >= 5 && !ReadBoolean(obj))
    return WebHTTPBody();

  // In older versions, 0 elements implied no form data.
  int num_elements = ReadInteger(obj);
  if (num_elements == 0 && obj->version < 5)
    return WebHTTPBody();

  WebHTTPBody http_body;
  http_body.initialize();

  for (int i = 0; i < num_elements; ++i) {
    int type = ReadInteger(obj);
    if (type == WebHTTPBody::Element::TypeData) {
      const void* data;
      int length = -1;
      ReadData(obj, &data, &length);
      if (length >= 0)
        http_body.appendData(WebData(static_cast<const char*>(data), length));
    } else {
      http_body.appendFile(ReadString(obj));
    }
  }
  if (obj->version >= 4)
    http_body.setIdentifier(ReadInteger64(obj));

  return http_body;
}

// Writes the HistoryItem data into the SerializeObject object for
// serialization.
static void WriteHistoryItem(
    const WebHistoryItem& item, SerializeObject* obj) {
  // WARNING: This data may be persisted for later use. As such, care must be
  // taken when changing the serialized format. If a new field needs to be
  // written, only adding at the end will make it easier to deal with loading
  // older versions. Similarly, this should NOT save fields with sensitive
  // data, such as password fields.
  WriteInteger(kVersion, obj);
  WriteString(item.urlString(), obj);
  WriteString(item.originalURLString(), obj);
  WriteString(item.target(), obj);
  WriteString(item.parent(), obj);
  WriteString(item.title(), obj);
  WriteString(item.alternateTitle(), obj);
  WriteReal(item.lastVisitedTime(), obj);
  WriteInteger(item.scrollOffset().x, obj);
  WriteInteger(item.scrollOffset().y, obj);
  WriteBoolean(item.isTargetItem(), obj);
  WriteInteger(item.visitCount(), obj);
  WriteString(item.referrer(), obj);

  WriteStringVector(item.documentState(), obj);

  // Yes, the referrer is written twice.  This is for backwards
  // compatibility with the format.
  WriteFormData(item.httpBody(), obj);
  WriteString(item.httpContentType(), obj);
  WriteString(item.referrer(), obj);

  // Subitems
  const WebVector<WebHistoryItem>& children = item.children();
  WriteInteger(static_cast<int>(children.size()), obj);
  for (size_t i = 0, c = children.size(); i < c; ++i)
    WriteHistoryItem(children[i], obj);
}

// Creates a new HistoryItem tree based on the serialized string.
// Assumes the data is in the format returned by WriteHistoryItem.
static WebHistoryItem ReadHistoryItem(
    const SerializeObject* obj, bool include_form_data) {
  // See note in WriteHistoryItem. on this.
  obj->version = ReadInteger(obj);

  if (obj->version == -1) {
    GURL url = ReadGURL(obj);
    WebHistoryItem item;
    item.initialize();
    item.setURLString(WebString::fromUTF8(url.possibly_invalid_spec()));
    return item;
  }

  if (obj->version > kVersion || obj->version < 1)
    return WebHistoryItem();

  WebHistoryItem item;
  item.initialize();

  item.setURLString(ReadString(obj));
  item.setOriginalURLString(ReadString(obj));
  item.setTarget(ReadString(obj));
  item.setParent(ReadString(obj));
  item.setTitle(ReadString(obj));
  item.setAlternateTitle(ReadString(obj));
  item.setLastVisitedTime(ReadReal(obj));
  int x = ReadInteger(obj);
  int y = ReadInteger(obj);
  item.setScrollOffset(WebPoint(x, y));
  item.setIsTargetItem(ReadBoolean(obj));
  item.setVisitCount(ReadInteger(obj));
  item.setReferrer(ReadString(obj));

  item.setDocumentState(ReadStringVector(obj));

  // The extra referrer string is read for backwards compat.
  const WebHTTPBody& http_body = ReadFormData(obj);
  const WebString& http_content_type = ReadString(obj);
  ALLOW_UNUSED const WebString& unused_referrer = ReadString(obj);
  if (include_form_data) {
    item.setHTTPBody(http_body);
    item.setHTTPContentType(http_content_type);
  }

  // Subitems
  int num_children = ReadInteger(obj);
  for (int i = 0; i < num_children; ++i)
    item.appendToChildren(ReadHistoryItem(obj, include_form_data));

  return item;
}

// Serialize a HistoryItem to a string, using our JSON Value serializer.
std::string HistoryItemToString(const WebHistoryItem& item) {
  if (item.isNull())
    return std::string();

  SerializeObject obj;
  WriteHistoryItem(item, &obj);
  return obj.GetAsString();
}

// Reconstruct a HistoryItem from a string, using our JSON Value deserializer.
// This assumes that the given serialized string has all the required key,value
// pairs, and does minimal error checking. If |include_form_data| is true,
// the form data from a post is restored, otherwise the form data is empty.
static WebHistoryItem HistoryItemFromString(
    const std::string& serialized_item,
    bool include_form_data) {
  if (serialized_item.empty())
    return WebHistoryItem();

  SerializeObject obj(serialized_item.data(),
                      static_cast<int>(serialized_item.length()));
  return ReadHistoryItem(&obj, include_form_data);
}

WebHistoryItem HistoryItemFromString(
    const std::string& serialized_item) {
  return HistoryItemFromString(serialized_item, true);
}

// For testing purposes only.
void HistoryItemToVersionedString(const WebHistoryItem& item, int version,
                                  std::string* serialized_item) {
  if (item.isNull()) {
    serialized_item->clear();
    return;
  }

  // Temporarily change the version.
  int real_version = kVersion;
  kVersion = version;

  SerializeObject obj;
  WriteHistoryItem(item, &obj);
  *serialized_item = obj.GetAsString();

  kVersion = real_version;
}

std::string CreateHistoryStateForURL(const GURL& url) {
  // We avoid using the WebKit API here, so that we do not need to have WebKit
  // initialized before calling this method.  Instead, we write a simple
  // serialization of the given URL with a dummy version number of -1.  This
  // will be interpreted by ReadHistoryItem as a request to create a default
  // WebHistoryItem.
  SerializeObject obj;
  WriteInteger(-1, &obj);
  WriteGURL(url, &obj);
  return obj.GetAsString();
}

std::string RemoveFormDataFromHistoryState(const std::string& content_state) {
  // TODO(darin): We should avoid using the WebKit API here, so that we do not
  // need to have WebKit initialized before calling this method.
  const WebHistoryItem& item = HistoryItemFromString(content_state, false);
  if (item.isNull()) {
    // Couldn't parse the string, return an empty string.
    return std::string();
  }

  return HistoryItemToString(item);
}

}  // namespace webkit_glue
<commit_msg>Make WebHistoryItem serialization include the documentSequenceNumber.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "webkit/glue/glue_serialize.h"

#include <string>

#include "base/pickle.h"
#include "base/utf_string_conversions.h"
#include "googleurl/src/gurl.h"
#include "third_party/WebKit/WebKit/chromium/public/WebData.h"
#include "third_party/WebKit/WebKit/chromium/public/WebHistoryItem.h"
#include "third_party/WebKit/WebKit/chromium/public/WebHTTPBody.h"
#include "third_party/WebKit/WebKit/chromium/public/WebPoint.h"
#include "third_party/WebKit/WebKit/chromium/public/WebString.h"
#include "third_party/WebKit/WebKit/chromium/public/WebVector.h"
#include "webkit/glue/webkit_glue.h"

using WebKit::WebData;
using WebKit::WebHistoryItem;
using WebKit::WebHTTPBody;
using WebKit::WebPoint;
using WebKit::WebString;
using WebKit::WebUChar;
using WebKit::WebVector;

namespace webkit_glue {

struct SerializeObject {
  SerializeObject() : iter(NULL) {}
  SerializeObject(const char* data, int len) : pickle(data, len), iter(NULL) {}

  std::string GetAsString() {
    return std::string(static_cast<const char*>(pickle.data()), pickle.size());
  }

  Pickle pickle;
  mutable void* iter;
  mutable int version;
};

// TODO(mpcomplete): obsolete versions 1 and 2 after 1/1/2008.
// Version ID used in reading/writing history items.
// 1: Initial revision.
// 2: Added case for NULL string versus "". Version 2 code can read Version 1
//    data, but not vice versa.
// 3: Version 2 was broken, it stored number of WebUChars, not number of bytes.
//    This version checks and reads v1 and v2 correctly.
// 4: Adds support for storing FormData::identifier().
// 5: Adds support for empty FormData
// 6: Adds support for documentSequenceNumbers
// Should be const, but unit tests may modify it.
//
// NOTE: If the version is -1, then the pickle contains only a URL string.
// See CreateHistoryStateForURL.
//
int kVersion = 6;

// A bunch of convenience functions to read/write to SerializeObjects.
// The serializers assume the input data is in the correct format and so does
// no error checking.
inline void WriteData(const void* data, int length, SerializeObject* obj) {
  obj->pickle.WriteData(static_cast<const char*>(data), length);
}

inline void ReadData(const SerializeObject* obj, const void** data,
                     int* length) {
  const char* tmp = NULL;
  obj->pickle.ReadData(&obj->iter, &tmp, length);
  *data = tmp;
}

inline bool ReadBytes(const SerializeObject* obj, const void** data,
                     int length) {
  const char *tmp;
  if (!obj->pickle.ReadBytes(&obj->iter, &tmp, length))
    return false;
  *data = tmp;
  return true;
}

inline void WriteInteger(int data, SerializeObject* obj) {
  obj->pickle.WriteInt(data);
}

inline int ReadInteger(const SerializeObject* obj) {
  int tmp = 0;
  obj->pickle.ReadInt(&obj->iter, &tmp);
  return tmp;
}

inline void WriteInteger64(int64 data, SerializeObject* obj) {
  obj->pickle.WriteInt64(data);
}

inline int64 ReadInteger64(const SerializeObject* obj) {
  int64 tmp = 0;
  obj->pickle.ReadInt64(&obj->iter, &tmp);
  return tmp;
}

inline void WriteReal(double data, SerializeObject* obj) {
  WriteData(&data, sizeof(double), obj);
}

inline double ReadReal(const SerializeObject* obj) {
  const void* tmp;
  int length = 0;
  ReadData(obj, &tmp, &length);
  if (length > 0 && length >= static_cast<int>(sizeof(0.0)))
    return *static_cast<const double*>(tmp);
  else
    return 0.0;
}

inline void WriteBoolean(bool data, SerializeObject* obj) {
  obj->pickle.WriteInt(data ? 1 : 0);
}

inline bool ReadBoolean(const SerializeObject* obj) {
  bool tmp = false;
  obj->pickle.ReadBool(&obj->iter, &tmp);
  return tmp;
}

inline void WriteGURL(const GURL& url, SerializeObject* obj) {
  obj->pickle.WriteString(url.possibly_invalid_spec());
}

inline GURL ReadGURL(const SerializeObject* obj) {
  std::string spec;
  obj->pickle.ReadString(&obj->iter, &spec);
  return GURL(spec);
}

// Read/WriteString pickle the WebString as <int length><WebUChar* data>.
// If length == -1, then the WebString itself is NULL (WebString()).
// Otherwise the length is the number of WebUChars (not bytes) in the WebString.
inline void WriteString(const WebString& str, SerializeObject* obj) {
  switch (kVersion) {
    case 1:
      // Version 1 writes <length in bytes><string data>.
      // It saves WebString() and "" as "".
      obj->pickle.WriteInt(str.length() * sizeof(WebUChar));
      obj->pickle.WriteBytes(str.data(), str.length() * sizeof(WebUChar));
      break;
    case 2:
      // Version 2 writes <length in WebUChar><string data>.
      // It uses -1 in the length field to mean WebString().
      if (str.isNull()) {
        obj->pickle.WriteInt(-1);
      } else {
        obj->pickle.WriteInt(str.length());
        obj->pickle.WriteBytes(str.data(),
                               str.length() * sizeof(WebUChar));
      }
      break;
    default:
      // Version 3+ writes <length in bytes><string data>.
      // It uses -1 in the length field to mean WebString().
      if (str.isNull()) {
        obj->pickle.WriteInt(-1);
      } else {
        obj->pickle.WriteInt(str.length() * sizeof(WebUChar));
        obj->pickle.WriteBytes(str.data(),
                               str.length() * sizeof(WebUChar));
      }
      break;
  }
}

// This reads a serialized WebString from obj. If a string can't be read,
// WebString() is returned.
inline WebString ReadString(const SerializeObject* obj) {
  int length;

  // Versions 1, 2, and 3 all start with an integer.
  if (!obj->pickle.ReadInt(&obj->iter, &length))
    return WebString();

  // Starting with version 2, -1 means WebString().
  if (length == -1)
    return WebString();

  // In version 2, the length field was the length in WebUChars.
  // In version 1 and 3 it is the length in bytes.
  int bytes = ((obj->version == 2) ? length * sizeof(WebUChar) : length);

  const void* data;
  if (!ReadBytes(obj, &data, bytes))
    return WebString();
  return WebString(static_cast<const WebUChar*>(data), bytes / sizeof(WebUChar));
}

// Writes a Vector of Strings into a SerializeObject for serialization.
static void WriteStringVector(
    const WebVector<WebString>& data, SerializeObject* obj) {
  WriteInteger(static_cast<int>(data.size()), obj);
  for (size_t i = 0, c = data.size(); i < c; ++i) {
    unsigned ui = static_cast<unsigned>(i);  // sigh
    WriteString(data[ui], obj);
  }
}

static WebVector<WebString> ReadStringVector(const SerializeObject* obj) {
  int num_elements = ReadInteger(obj);
  WebVector<WebString> result(static_cast<size_t>(num_elements));
  for (int i = 0; i < num_elements; ++i)
    result[i] = ReadString(obj);
  return result;
}

// Writes a FormData object into a SerializeObject for serialization.
static void WriteFormData(const WebHTTPBody& http_body, SerializeObject* obj) {
  WriteBoolean(!http_body.isNull(), obj);

  if (http_body.isNull())
    return;

  WriteInteger(static_cast<int>(http_body.elementCount()), obj);
  WebHTTPBody::Element element;
  for (size_t i = 0; http_body.elementAt(i, element); ++i) {
    WriteInteger(element.type, obj);
    if (element.type == WebHTTPBody::Element::TypeData) {
      WriteData(element.data.data(), static_cast<int>(element.data.size()),
                obj);
    } else {
      WriteString(element.filePath, obj);
    }
  }
  WriteInteger64(http_body.identifier(), obj);
}

static WebHTTPBody ReadFormData(const SerializeObject* obj) {
  // In newer versions, an initial boolean indicates if we have form data.
  if (obj->version >= 5 && !ReadBoolean(obj))
    return WebHTTPBody();

  // In older versions, 0 elements implied no form data.
  int num_elements = ReadInteger(obj);
  if (num_elements == 0 && obj->version < 5)
    return WebHTTPBody();

  WebHTTPBody http_body;
  http_body.initialize();

  for (int i = 0; i < num_elements; ++i) {
    int type = ReadInteger(obj);
    if (type == WebHTTPBody::Element::TypeData) {
      const void* data;
      int length = -1;
      ReadData(obj, &data, &length);
      if (length >= 0)
        http_body.appendData(WebData(static_cast<const char*>(data), length));
    } else {
      http_body.appendFile(ReadString(obj));
    }
  }
  if (obj->version >= 4)
    http_body.setIdentifier(ReadInteger64(obj));

  return http_body;
}

// Writes the HistoryItem data into the SerializeObject object for
// serialization.
static void WriteHistoryItem(
    const WebHistoryItem& item, SerializeObject* obj) {
  // WARNING: This data may be persisted for later use. As such, care must be
  // taken when changing the serialized format. If a new field needs to be
  // written, only adding at the end will make it easier to deal with loading
  // older versions. Similarly, this should NOT save fields with sensitive
  // data, such as password fields.
  WriteInteger(kVersion, obj);
  WriteString(item.urlString(), obj);
  WriteString(item.originalURLString(), obj);
  WriteString(item.target(), obj);
  WriteString(item.parent(), obj);
  WriteString(item.title(), obj);
  WriteString(item.alternateTitle(), obj);
  WriteReal(item.lastVisitedTime(), obj);
  WriteInteger(item.scrollOffset().x, obj);
  WriteInteger(item.scrollOffset().y, obj);
  WriteBoolean(item.isTargetItem(), obj);
  WriteInteger(item.visitCount(), obj);
  WriteString(item.referrer(), obj);

  WriteStringVector(item.documentState(), obj);

  if (kVersion >= 6)
    WriteInteger64(item.documentSequenceNumber(), obj);

  // Yes, the referrer is written twice.  This is for backwards
  // compatibility with the format.
  WriteFormData(item.httpBody(), obj);
  WriteString(item.httpContentType(), obj);
  WriteString(item.referrer(), obj);

  // Subitems
  const WebVector<WebHistoryItem>& children = item.children();
  WriteInteger(static_cast<int>(children.size()), obj);
  for (size_t i = 0, c = children.size(); i < c; ++i)
    WriteHistoryItem(children[i], obj);
}

// Creates a new HistoryItem tree based on the serialized string.
// Assumes the data is in the format returned by WriteHistoryItem.
static WebHistoryItem ReadHistoryItem(
    const SerializeObject* obj, bool include_form_data) {
  // See note in WriteHistoryItem. on this.
  obj->version = ReadInteger(obj);

  if (obj->version == -1) {
    GURL url = ReadGURL(obj);
    WebHistoryItem item;
    item.initialize();
    item.setURLString(WebString::fromUTF8(url.possibly_invalid_spec()));
    return item;
  }

  if (obj->version > kVersion || obj->version < 1)
    return WebHistoryItem();

  WebHistoryItem item;
  item.initialize();

  item.setURLString(ReadString(obj));
  item.setOriginalURLString(ReadString(obj));
  item.setTarget(ReadString(obj));
  item.setParent(ReadString(obj));
  item.setTitle(ReadString(obj));
  item.setAlternateTitle(ReadString(obj));
  item.setLastVisitedTime(ReadReal(obj));
  int x = ReadInteger(obj);
  int y = ReadInteger(obj);
  item.setScrollOffset(WebPoint(x, y));
  item.setIsTargetItem(ReadBoolean(obj));
  item.setVisitCount(ReadInteger(obj));
  item.setReferrer(ReadString(obj));

  item.setDocumentState(ReadStringVector(obj));

  if (obj->version >= 6)
    item.setDocumentSequenceNumber(ReadInteger64(obj));

  // The extra referrer string is read for backwards compat.
  const WebHTTPBody& http_body = ReadFormData(obj);
  const WebString& http_content_type = ReadString(obj);
  ALLOW_UNUSED const WebString& unused_referrer = ReadString(obj);
  if (include_form_data) {
    item.setHTTPBody(http_body);
    item.setHTTPContentType(http_content_type);
  }

  // Subitems
  int num_children = ReadInteger(obj);
  for (int i = 0; i < num_children; ++i)
    item.appendToChildren(ReadHistoryItem(obj, include_form_data));

  return item;
}

// Serialize a HistoryItem to a string, using our JSON Value serializer.
std::string HistoryItemToString(const WebHistoryItem& item) {
  if (item.isNull())
    return std::string();

  SerializeObject obj;
  WriteHistoryItem(item, &obj);
  return obj.GetAsString();
}

// Reconstruct a HistoryItem from a string, using our JSON Value deserializer.
// This assumes that the given serialized string has all the required key,value
// pairs, and does minimal error checking. If |include_form_data| is true,
// the form data from a post is restored, otherwise the form data is empty.
static WebHistoryItem HistoryItemFromString(
    const std::string& serialized_item,
    bool include_form_data) {
  if (serialized_item.empty())
    return WebHistoryItem();

  SerializeObject obj(serialized_item.data(),
                      static_cast<int>(serialized_item.length()));
  return ReadHistoryItem(&obj, include_form_data);
}

WebHistoryItem HistoryItemFromString(
    const std::string& serialized_item) {
  return HistoryItemFromString(serialized_item, true);
}

// For testing purposes only.
void HistoryItemToVersionedString(const WebHistoryItem& item, int version,
                                  std::string* serialized_item) {
  if (item.isNull()) {
    serialized_item->clear();
    return;
  }

  // Temporarily change the version.
  int real_version = kVersion;
  kVersion = version;

  SerializeObject obj;
  WriteHistoryItem(item, &obj);
  *serialized_item = obj.GetAsString();

  kVersion = real_version;
}

std::string CreateHistoryStateForURL(const GURL& url) {
  // We avoid using the WebKit API here, so that we do not need to have WebKit
  // initialized before calling this method.  Instead, we write a simple
  // serialization of the given URL with a dummy version number of -1.  This
  // will be interpreted by ReadHistoryItem as a request to create a default
  // WebHistoryItem.
  SerializeObject obj;
  WriteInteger(-1, &obj);
  WriteGURL(url, &obj);
  return obj.GetAsString();
}

std::string RemoveFormDataFromHistoryState(const std::string& content_state) {
  // TODO(darin): We should avoid using the WebKit API here, so that we do not
  // need to have WebKit initialized before calling this method.
  const WebHistoryItem& item = HistoryItemFromString(content_state, false);
  if (item.isNull()) {
    // Couldn't parse the string, return an empty string.
    return std::string();
  }

  return HistoryItemToString(item);
}

}  // namespace webkit_glue
<|endoftext|>


<commit_before>// Copyright 2008, Google Inc.
// 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 Google Inc. 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
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

#include "config.h"

#include "webkit/glue/npruntime_util.h"

// Import the definition of PrivateIdentifier
#if USE(V8_BINDING)
#include "webkit/port/bindings/v8/np_v8object.h"
#elif USE(JAVASCRIPTCORE_BINDINGS)
#include "third_party/npapi/bindings/c/c_utility.h"
using KJS::Bindings::PrivateIdentifier;
#endif

#include "base/pickle.h"

namespace webkit_glue {

bool SerializeNPIdentifier(NPIdentifier identifier, Pickle* pickle) {
  PrivateIdentifier* priv = static_cast<PrivateIdentifier*>(identifier);

  // If the identifier was null, then we just send a numeric 0.  This is to
  // support cases where the other end doesn't care about the NPIdentifier
  // being serialized, so the bogus value of 0 is really inconsequential.
  PrivateIdentifier null_id;
  if (!priv) {
    priv = &null_id;
    priv->isString = false;
    priv->value.number = 0;
  }

  if (!pickle->WriteBool(priv->isString))
    return false;
  if (priv->isString) {
    // Write the null byte for efficiency on the other end.
    return pickle->WriteData(
        priv->value.string, strlen(priv->value.string) + 1);
  }
  return pickle->WriteInt(priv->value.number);
}

bool DeserializeNPIdentifier(const Pickle& pickle, void** pickle_iter,
                             NPIdentifier* identifier) {
  bool is_string;
  if (!pickle.ReadBool(pickle_iter, &is_string))
    return false;

  if (is_string) {
    const char* data;
    int data_len;
    if (!pickle.ReadData(pickle_iter, &data, &data_len))
      return false;
    DCHECK_EQ(data_len, strlen(data) + 1);
    *identifier = NPN_GetStringIdentifier(data);
  } else {
    int number;
    if (!pickle.ReadInt(pickle_iter, &number))
      return false;
    *identifier = NPN_GetIntIdentifier(number);
  }
  return true;
}

}  // namespace webkit_glue
<commit_msg>Revert my change for c_utility so that the JSC build will compile<commit_after>// Copyright 2008, Google Inc.
// 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 Google Inc. 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
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

#include "config.h"

#include "webkit/glue/npruntime_util.h"

// Import the definition of PrivateIdentifier
#if USE(V8_BINDING)
#include "webkit/port/bindings/v8/np_v8object.h"
#elif USE(JAVASCRIPTCORE_BINDINGS)
#include "bindings/c/c_utility.h"
using KJS::Bindings::PrivateIdentifier;
#endif

#include "base/pickle.h"

namespace webkit_glue {

bool SerializeNPIdentifier(NPIdentifier identifier, Pickle* pickle) {
  PrivateIdentifier* priv = static_cast<PrivateIdentifier*>(identifier);

  // If the identifier was null, then we just send a numeric 0.  This is to
  // support cases where the other end doesn't care about the NPIdentifier
  // being serialized, so the bogus value of 0 is really inconsequential.
  PrivateIdentifier null_id;
  if (!priv) {
    priv = &null_id;
    priv->isString = false;
    priv->value.number = 0;
  }

  if (!pickle->WriteBool(priv->isString))
    return false;
  if (priv->isString) {
    // Write the null byte for efficiency on the other end.
    return pickle->WriteData(
        priv->value.string, strlen(priv->value.string) + 1);
  }
  return pickle->WriteInt(priv->value.number);
}

bool DeserializeNPIdentifier(const Pickle& pickle, void** pickle_iter,
                             NPIdentifier* identifier) {
  bool is_string;
  if (!pickle.ReadBool(pickle_iter, &is_string))
    return false;

  if (is_string) {
    const char* data;
    int data_len;
    if (!pickle.ReadData(pickle_iter, &data, &data_len))
      return false;
    DCHECK_EQ(data_len, strlen(data) + 1);
    *identifier = NPN_GetStringIdentifier(data);
  } else {
    int number;
    if (!pickle.ReadInt(pickle_iter, &number))
      return false;
    *identifier = NPN_GetIntIdentifier(number);
  }
  return true;
}

}  // namespace webkit_glue
<|endoftext|>


<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "webkit/glue/webpreferences.h"

#include "base/string_util.h"
#include "base/utf_string_conversions.h"
#include "third_party/WebKit/WebKit/chromium/public/WebRuntimeFeatures.h"
#include "third_party/WebKit/WebKit/chromium/public/WebKit.h"
#include "third_party/WebKit/WebKit/chromium/public/WebSettings.h"
#include "third_party/WebKit/WebKit/chromium/public/WebString.h"
#include "third_party/WebKit/WebKit/chromium/public/WebURL.h"
#include "third_party/WebKit/WebKit/chromium/public/WebView.h"
#include "webkit/glue/webkit_glue.h"

using WebKit::WebRuntimeFeatures;
using WebKit::WebSettings;
using WebKit::WebString;
using WebKit::WebURL;
using WebKit::WebView;

void WebPreferences::Apply(WebView* web_view) const {
  WebSettings* settings = web_view->settings();
  settings->setStandardFontFamily(WideToUTF16Hack(standard_font_family));
  settings->setFixedFontFamily(WideToUTF16Hack(fixed_font_family));
  settings->setSerifFontFamily(WideToUTF16Hack(serif_font_family));
  settings->setSansSerifFontFamily(WideToUTF16Hack(sans_serif_font_family));
  settings->setCursiveFontFamily(WideToUTF16Hack(cursive_font_family));
  settings->setFantasyFontFamily(WideToUTF16Hack(fantasy_font_family));
  settings->setDefaultFontSize(default_font_size);
  settings->setDefaultFixedFontSize(default_fixed_font_size);
  settings->setMinimumFontSize(minimum_font_size);
  settings->setMinimumLogicalFontSize(minimum_logical_font_size);
  settings->setDefaultTextEncodingName(ASCIIToUTF16(default_encoding));
  settings->setJavaScriptEnabled(javascript_enabled);
  settings->setWebSecurityEnabled(web_security_enabled);
  settings->setJavaScriptCanOpenWindowsAutomatically(
      javascript_can_open_windows_automatically);
  settings->setLoadsImagesAutomatically(loads_images_automatically);
  settings->setPluginsEnabled(plugins_enabled);
  settings->setDOMPasteAllowed(dom_paste_enabled);
  settings->setDeveloperExtrasEnabled(developer_extras_enabled);
  settings->setNeedsSiteSpecificQuirks(site_specific_quirks_enabled);
  settings->setShrinksStandaloneImagesToFit(shrinks_standalone_images_to_fit);
  settings->setUsesEncodingDetector(uses_universal_detector);
  settings->setTextAreasAreResizable(text_areas_are_resizable);
  settings->setAllowScriptsToCloseWindows(allow_scripts_to_close_windows);
  if (user_style_sheet_enabled)
    settings->setUserStyleSheetLocation(user_style_sheet_location);
  else
    settings->setUserStyleSheetLocation(WebURL());
  settings->setAuthorAndUserStylesEnabled(author_and_user_styles_enabled);
  settings->setUsesPageCache(uses_page_cache);
  settings->setDownloadableBinaryFontsEnabled(remote_fonts_enabled);
  settings->setJavaScriptCanAccessClipboard(javascript_can_access_clipboard);
  settings->setXSSAuditorEnabled(xss_auditor_enabled);
  settings->setLocalStorageEnabled(local_storage_enabled);
  WebRuntimeFeatures::enableDatabase(
      WebRuntimeFeatures::isDatabaseEnabled() || databases_enabled);
  settings->setOfflineWebApplicationCacheEnabled(application_cache_enabled);
  settings->setHTML5ParserEnabled(enable_html5_parser);

  // This setting affects the behavior of links in an editable region:
  // clicking the link should select it rather than navigate to it.
  // Safari uses the same default. It is unlikley an embedder would want to
  // change this, since it would break existing rich text editors.
  settings->setEditableLinkBehaviorNeverLive();

  settings->setFontRenderingModeNormal();
  settings->setJavaEnabled(java_enabled);

  // Turn this on to cause WebCore to paint the resize corner for us.
  settings->setShouldPaintCustomScrollbars(true);

  // By default, allow_universal_access_from_file_urls is set to false and thus
  // we mitigate attacks from local HTML files by not granting file:// URLs
  // universal access. Only test shell will enable this.
  settings->setAllowUniversalAccessFromFileURLs(
      allow_universal_access_from_file_urls);
  settings->setAllowFileAccessFromFileURLs(allow_file_access_from_file_urls);

  // We prevent WebKit from checking if it needs to add a "text direction"
  // submenu to a context menu. it is not only because we don't need the result
  // but also because it cause a possible crash in Editor::hasBidiSelection().
  settings->setTextDirectionSubmenuInclusionBehaviorNeverIncluded();

  // Enable experimental WebGL support if requested on command line
  // and support is compiled in.
  settings->setExperimentalWebGLEnabled(experimental_webgl_enabled);

  // Display colored borders around composited render layers if requested
  // on command line.
  settings->setShowDebugBorders(show_composited_layer_borders);

  // Enable gpu-accelerated compositing if requested on the command line.
  settings->setAcceleratedCompositingEnabled(accelerated_compositing_enabled);

  // Enable gpu-accelerated 2d canvas if requested on the command line.
  settings->setAccelerated2dCanvasEnabled(accelerated_2d_canvas_enabled);

  // Enable memory info reporting to page if requested on the command line.
  settings->setMemoryInfoEnabled(memory_info_enabled);

  for (WebInspectorPreferences::const_iterator it = inspector_settings.begin();
       it != inspector_settings.end(); ++it)
    web_view->setInspectorSetting(WebString::fromUTF8(it->first),
                                  WebString::fromUTF8(it->second));

  // Tabs to link is not part of the settings. WebCore calls
  // ChromeClient::tabsToLinks which is part of the glue code.
  web_view->setTabsToLinks(tabs_to_links);
}
<commit_msg>WebGL web preferences do not disable WebGL if already enabled.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "webkit/glue/webpreferences.h"

#include "base/string_util.h"
#include "base/utf_string_conversions.h"
#include "third_party/WebKit/WebKit/chromium/public/WebRuntimeFeatures.h"
#include "third_party/WebKit/WebKit/chromium/public/WebKit.h"
#include "third_party/WebKit/WebKit/chromium/public/WebSettings.h"
#include "third_party/WebKit/WebKit/chromium/public/WebString.h"
#include "third_party/WebKit/WebKit/chromium/public/WebURL.h"
#include "third_party/WebKit/WebKit/chromium/public/WebView.h"
#include "webkit/glue/webkit_glue.h"

using WebKit::WebRuntimeFeatures;
using WebKit::WebSettings;
using WebKit::WebString;
using WebKit::WebURL;
using WebKit::WebView;

void WebPreferences::Apply(WebView* web_view) const {
  WebSettings* settings = web_view->settings();
  settings->setStandardFontFamily(WideToUTF16Hack(standard_font_family));
  settings->setFixedFontFamily(WideToUTF16Hack(fixed_font_family));
  settings->setSerifFontFamily(WideToUTF16Hack(serif_font_family));
  settings->setSansSerifFontFamily(WideToUTF16Hack(sans_serif_font_family));
  settings->setCursiveFontFamily(WideToUTF16Hack(cursive_font_family));
  settings->setFantasyFontFamily(WideToUTF16Hack(fantasy_font_family));
  settings->setDefaultFontSize(default_font_size);
  settings->setDefaultFixedFontSize(default_fixed_font_size);
  settings->setMinimumFontSize(minimum_font_size);
  settings->setMinimumLogicalFontSize(minimum_logical_font_size);
  settings->setDefaultTextEncodingName(ASCIIToUTF16(default_encoding));
  settings->setJavaScriptEnabled(javascript_enabled);
  settings->setWebSecurityEnabled(web_security_enabled);
  settings->setJavaScriptCanOpenWindowsAutomatically(
      javascript_can_open_windows_automatically);
  settings->setLoadsImagesAutomatically(loads_images_automatically);
  settings->setPluginsEnabled(plugins_enabled);
  settings->setDOMPasteAllowed(dom_paste_enabled);
  settings->setDeveloperExtrasEnabled(developer_extras_enabled);
  settings->setNeedsSiteSpecificQuirks(site_specific_quirks_enabled);
  settings->setShrinksStandaloneImagesToFit(shrinks_standalone_images_to_fit);
  settings->setUsesEncodingDetector(uses_universal_detector);
  settings->setTextAreasAreResizable(text_areas_are_resizable);
  settings->setAllowScriptsToCloseWindows(allow_scripts_to_close_windows);
  if (user_style_sheet_enabled)
    settings->setUserStyleSheetLocation(user_style_sheet_location);
  else
    settings->setUserStyleSheetLocation(WebURL());
  settings->setAuthorAndUserStylesEnabled(author_and_user_styles_enabled);
  settings->setUsesPageCache(uses_page_cache);
  settings->setDownloadableBinaryFontsEnabled(remote_fonts_enabled);
  settings->setJavaScriptCanAccessClipboard(javascript_can_access_clipboard);
  settings->setXSSAuditorEnabled(xss_auditor_enabled);
  settings->setLocalStorageEnabled(local_storage_enabled);
  WebRuntimeFeatures::enableDatabase(
      WebRuntimeFeatures::isDatabaseEnabled() || databases_enabled);
  settings->setOfflineWebApplicationCacheEnabled(application_cache_enabled);
  settings->setHTML5ParserEnabled(enable_html5_parser);

  // This setting affects the behavior of links in an editable region:
  // clicking the link should select it rather than navigate to it.
  // Safari uses the same default. It is unlikley an embedder would want to
  // change this, since it would break existing rich text editors.
  settings->setEditableLinkBehaviorNeverLive();

  settings->setFontRenderingModeNormal();
  settings->setJavaEnabled(java_enabled);

  // Turn this on to cause WebCore to paint the resize corner for us.
  settings->setShouldPaintCustomScrollbars(true);

  // By default, allow_universal_access_from_file_urls is set to false and thus
  // we mitigate attacks from local HTML files by not granting file:// URLs
  // universal access. Only test shell will enable this.
  settings->setAllowUniversalAccessFromFileURLs(
      allow_universal_access_from_file_urls);
  settings->setAllowFileAccessFromFileURLs(allow_file_access_from_file_urls);

  // We prevent WebKit from checking if it needs to add a "text direction"
  // submenu to a context menu. it is not only because we don't need the result
  // but also because it cause a possible crash in Editor::hasBidiSelection().
  settings->setTextDirectionSubmenuInclusionBehaviorNeverIncluded();

  // Enable experimental WebGL support if requested on command line
  // and support is compiled in.
  settings->setExperimentalWebGLEnabled(
      WebRuntimeFeatures::isWebGLEnabled() || experimental_webgl_enabled);

  // Display colored borders around composited render layers if requested
  // on command line.
  settings->setShowDebugBorders(show_composited_layer_borders);

  // Enable gpu-accelerated compositing if requested on the command line.
  settings->setAcceleratedCompositingEnabled(accelerated_compositing_enabled);

  // Enable gpu-accelerated 2d canvas if requested on the command line.
  settings->setAccelerated2dCanvasEnabled(accelerated_2d_canvas_enabled);

  // Enable memory info reporting to page if requested on the command line.
  settings->setMemoryInfoEnabled(memory_info_enabled);

  for (WebInspectorPreferences::const_iterator it = inspector_settings.begin();
       it != inspector_settings.end(); ++it)
    web_view->setInspectorSetting(WebString::fromUTF8(it->first),
                                  WebString::fromUTF8(it->second));

  // Tabs to link is not part of the settings. WebCore calls
  // ChromeClient::tabsToLinks which is part of the glue code.
  web_view->setTabsToLinks(tabs_to_links);
}
<|endoftext|>


<commit_before>///////////////////////////////////////////////////////////////////////////////////////////////////
// OpenGL Mathematics Copyright (c) 2005 - 2011 G-Truc Creation (www.g-truc.net)
///////////////////////////////////////////////////////////////////////////////////////////////////
// Created : 2009-05-07
// Updated : 2009-05-07
// Licence : This source is under MIT License
// File    : glm/gtx/simd_vec4.hpp
///////////////////////////////////////////////////////////////////////////////////////////////////
// Dependency:
// - GLM core
// - intrinsic
///////////////////////////////////////////////////////////////////////////////////////////////////

#ifndef glm_gtx_simd_mat4
#define glm_gtx_simd_mat4

// Dependency:
#include "../glm.hpp"

#if(!(GLM_ARCH & GLM_ARCH_SSE2))
#error "GLM: GLM_GTX_simd_mat4 requires compiler support of SSE2 through intrinsics"
#endif

#include "../core/intrinsic_matrix.hpp"
#include "../gtx/simd_vec4.hpp"

#if(defined(GLM_MESSAGES) && !defined(glm_ext))
#	pragma message("GLM: GLM_GTX_simd_mat4 extension included")
#endif

namespace glm
{
	namespace detail
	{
		GLM_ALIGNED(struct, 16) fmat4x4SIMD
		{
			enum ctor{null};

			typedef float value_type;
			typedef fvec4SIMD col_type;
			typedef fvec4SIMD row_type;
			typedef std::size_t size_type;
			static size_type value_size();
			static size_type col_size();
			static size_type row_size();
			static bool is_matrix();

			fvec4SIMD Data[4];

			//////////////////////////////////////
			// Constructors

			fmat4x4SIMD();
			explicit fmat4x4SIMD(float const & s);
			explicit fmat4x4SIMD(
				float const & x0, float const & y0, float const & z0, float const & w0,
				float const & x1, float const & y1, float const & z1, float const & w1,
				float const & x2, float const & y2, float const & z2, float const & w2,
				float const & x3, float const & y3, float const & z3, float const & w3);
			explicit fmat4x4SIMD(
				fvec4SIMD const & v0,
				fvec4SIMD const & v1,
				fvec4SIMD const & v2,
				fvec4SIMD const & v3);
			explicit fmat4x4SIMD(
				tmat4x4<float> const & m);

			// Conversions
			//template <typename U>
			//explicit tmat4x4(tmat4x4<U> const & m);

			//explicit tmat4x4(tmat2x2<T> const & x);
			//explicit tmat4x4(tmat3x3<T> const & x);
			//explicit tmat4x4(tmat2x3<T> const & x);
			//explicit tmat4x4(tmat3x2<T> const & x);
			//explicit tmat4x4(tmat2x4<T> const & x);
			//explicit tmat4x4(tmat4x2<T> const & x);
			//explicit tmat4x4(tmat3x4<T> const & x);
			//explicit tmat4x4(tmat4x3<T> const & x);

			// Accesses
			fvec4SIMD & operator[](size_type i);
			fvec4SIMD const & operator[](size_type i) const;

			// Unary updatable operators
			fmat4x4SIMD & operator= (fmat4x4SIMD const & m);
			fmat4x4SIMD & operator+= (float const & s);
			fmat4x4SIMD & operator+= (fmat4x4SIMD const & m);
			fmat4x4SIMD & operator-= (float const & s);
			fmat4x4SIMD & operator-= (fmat4x4SIMD const & m);
			fmat4x4SIMD & operator*= (float const & s);
			fmat4x4SIMD & operator*= (fmat4x4SIMD const & m);
			fmat4x4SIMD & operator/= (float const & s);
			fmat4x4SIMD & operator/= (fmat4x4SIMD const & m);
			fmat4x4SIMD & operator++ ();
			fmat4x4SIMD & operator-- ();
		};

		// Binary operators
		fmat4x4SIMD operator+ (fmat4x4SIMD const & m, float const & s);
		fmat4x4SIMD operator+ (float const & s, fmat4x4SIMD const & m);
		fmat4x4SIMD operator+ (fmat4x4SIMD const & m1, fmat4x4SIMD const & m2);

		fmat4x4SIMD operator- (fmat4x4SIMD const & m, float const & s);
		fmat4x4SIMD operator- (float const & s, fmat4x4SIMD const & m);
		fmat4x4SIMD operator- (fmat4x4SIMD const & m1, fmat4x4SIMD const & m2);

		fmat4x4SIMD operator* (fmat4x4SIMD const & m, float const & s);
		fmat4x4SIMD operator* (float const & s, fmat4x4SIMD const & m);

		fvec4SIMD operator* (fmat4x4SIMD const & m, fvec4SIMD const & v);
		fvec4SIMD operator* (fvec4SIMD const & v, fmat4x4SIMD const & m);

		fmat4x4SIMD operator* (fmat4x4SIMD const & m1, fmat4x4SIMD const & m2);

		fmat4x4SIMD operator/ (fmat4x4SIMD const & m, float const & s);
		fmat4x4SIMD operator/ (float const & s, fmat4x4SIMD const & m);

		fvec4SIMD operator/ (fmat4x4SIMD const & m, fvec4SIMD const & v);
		fvec4SIMD operator/ (fvec4SIMD const & v, fmat4x4SIMD const & m);

		fmat4x4SIMD operator/ (fmat4x4SIMD const & m1, fmat4x4SIMD const & m2);

		// Unary constant operators
		fmat4x4SIMD const operator-  (fmat4x4SIMD const & m);
		fmat4x4SIMD const operator-- (fmat4x4SIMD const & m, int);
		fmat4x4SIMD const operator++ (fmat4x4SIMD const & m, int);

	}//namespace detail

	namespace gtx{
	//! GLM_GTX_simd_mat4 extension: SIMD implementation of vec4 type.
	namespace simd_mat4
	{
		typedef detail::fmat4x4SIMD simd_mat4;

		//! Returns the transposed matrix of x
		//! (From GLM_GTX_simd_mat4 extension).
		detail::fmat4x4SIMD simd_transpose(detail::fmat4x4SIMD const & m);

		//! Return the determinant of a mat4 matrix.
		//! (From GLM_GTX_simd_mat4 extension).
		float simd_determinant(detail::fmat4x4SIMD const & m);

		//! Return the inverse of a mat4 matrix.
		//! (From GLM_GTX_simd_mat4 extension).
		detail::fmat4x4SIMD simd_inverse(detail::fmat4x4SIMD const & m);

	}//namespace simd_mat4
	}//namespace gtx
}//namespace glm

#include "simd_mat4.inl"

namespace glm{using namespace gtx::simd_mat4;}

#endif//glm_gtx_simd_mat4
<commit_msg>Updated SSE error message<commit_after>///////////////////////////////////////////////////////////////////////////////////////////////////
// OpenGL Mathematics Copyright (c) 2005 - 2011 G-Truc Creation (www.g-truc.net)
///////////////////////////////////////////////////////////////////////////////////////////////////
// Created : 2009-05-07
// Updated : 2009-05-07
// Licence : This source is under MIT License
// File    : glm/gtx/simd_vec4.hpp
///////////////////////////////////////////////////////////////////////////////////////////////////
// Dependency:
// - GLM core
// - intrinsic
///////////////////////////////////////////////////////////////////////////////////////////////////

#ifndef glm_gtx_simd_mat4
#define glm_gtx_simd_mat4

// Dependency:
#include "../glm.hpp"

#if(GLM_ARCH & GLM_ARCH_SSE2)
#	include "../core/intrinsic_matrix.hpp"
#	include "../gtx/simd_vec4.hpp"
#else
#	error "GLM: GLM_GTX_simd_mat4 requires compiler support of SSE2 through intrinsics"
#endif

#if(defined(GLM_MESSAGES) && !defined(glm_ext))
#	pragma message("GLM: GLM_GTX_simd_mat4 extension included")
#endif

namespace glm
{
	namespace detail
	{
		GLM_ALIGNED(struct, 16) fmat4x4SIMD
		{
			enum ctor{null};

			typedef float value_type;
			typedef fvec4SIMD col_type;
			typedef fvec4SIMD row_type;
			typedef std::size_t size_type;
			static size_type value_size();
			static size_type col_size();
			static size_type row_size();
			static bool is_matrix();

			fvec4SIMD Data[4];

			//////////////////////////////////////
			// Constructors

			fmat4x4SIMD();
			explicit fmat4x4SIMD(float const & s);
			explicit fmat4x4SIMD(
				float const & x0, float const & y0, float const & z0, float const & w0,
				float const & x1, float const & y1, float const & z1, float const & w1,
				float const & x2, float const & y2, float const & z2, float const & w2,
				float const & x3, float const & y3, float const & z3, float const & w3);
			explicit fmat4x4SIMD(
				fvec4SIMD const & v0,
				fvec4SIMD const & v1,
				fvec4SIMD const & v2,
				fvec4SIMD const & v3);
			explicit fmat4x4SIMD(
				tmat4x4<float> const & m);

			// Conversions
			//template <typename U>
			//explicit tmat4x4(tmat4x4<U> const & m);

			//explicit tmat4x4(tmat2x2<T> const & x);
			//explicit tmat4x4(tmat3x3<T> const & x);
			//explicit tmat4x4(tmat2x3<T> const & x);
			//explicit tmat4x4(tmat3x2<T> const & x);
			//explicit tmat4x4(tmat2x4<T> const & x);
			//explicit tmat4x4(tmat4x2<T> const & x);
			//explicit tmat4x4(tmat3x4<T> const & x);
			//explicit tmat4x4(tmat4x3<T> const & x);

			// Accesses
			fvec4SIMD & operator[](size_type i);
			fvec4SIMD const & operator[](size_type i) const;

			// Unary updatable operators
			fmat4x4SIMD & operator= (fmat4x4SIMD const & m);
			fmat4x4SIMD & operator+= (float const & s);
			fmat4x4SIMD & operator+= (fmat4x4SIMD const & m);
			fmat4x4SIMD & operator-= (float const & s);
			fmat4x4SIMD & operator-= (fmat4x4SIMD const & m);
			fmat4x4SIMD & operator*= (float const & s);
			fmat4x4SIMD & operator*= (fmat4x4SIMD const & m);
			fmat4x4SIMD & operator/= (float const & s);
			fmat4x4SIMD & operator/= (fmat4x4SIMD const & m);
			fmat4x4SIMD & operator++ ();
			fmat4x4SIMD & operator-- ();
		};

		// Binary operators
		fmat4x4SIMD operator+ (fmat4x4SIMD const & m, float const & s);
		fmat4x4SIMD operator+ (float const & s, fmat4x4SIMD const & m);
		fmat4x4SIMD operator+ (fmat4x4SIMD const & m1, fmat4x4SIMD const & m2);

		fmat4x4SIMD operator- (fmat4x4SIMD const & m, float const & s);
		fmat4x4SIMD operator- (float const & s, fmat4x4SIMD const & m);
		fmat4x4SIMD operator- (fmat4x4SIMD const & m1, fmat4x4SIMD const & m2);

		fmat4x4SIMD operator* (fmat4x4SIMD const & m, float const & s);
		fmat4x4SIMD operator* (float const & s, fmat4x4SIMD const & m);

		fvec4SIMD operator* (fmat4x4SIMD const & m, fvec4SIMD const & v);
		fvec4SIMD operator* (fvec4SIMD const & v, fmat4x4SIMD const & m);

		fmat4x4SIMD operator* (fmat4x4SIMD const & m1, fmat4x4SIMD const & m2);

		fmat4x4SIMD operator/ (fmat4x4SIMD const & m, float const & s);
		fmat4x4SIMD operator/ (float const & s, fmat4x4SIMD const & m);

		fvec4SIMD operator/ (fmat4x4SIMD const & m, fvec4SIMD const & v);
		fvec4SIMD operator/ (fvec4SIMD const & v, fmat4x4SIMD const & m);

		fmat4x4SIMD operator/ (fmat4x4SIMD const & m1, fmat4x4SIMD const & m2);

		// Unary constant operators
		fmat4x4SIMD const operator-  (fmat4x4SIMD const & m);
		fmat4x4SIMD const operator-- (fmat4x4SIMD const & m, int);
		fmat4x4SIMD const operator++ (fmat4x4SIMD const & m, int);

	}//namespace detail

	namespace gtx{
	//! GLM_GTX_simd_mat4 extension: SIMD implementation of vec4 type.
	namespace simd_mat4
	{
		typedef detail::fmat4x4SIMD simd_mat4;

		//! Returns the transposed matrix of x
		//! (From GLM_GTX_simd_mat4 extension).
		detail::fmat4x4SIMD simd_transpose(detail::fmat4x4SIMD const & m);

		//! Return the determinant of a mat4 matrix.
		//! (From GLM_GTX_simd_mat4 extension).
		float simd_determinant(detail::fmat4x4SIMD const & m);

		//! Return the inverse of a mat4 matrix.
		//! (From GLM_GTX_simd_mat4 extension).
		detail::fmat4x4SIMD simd_inverse(detail::fmat4x4SIMD const & m);

	}//namespace simd_mat4
	}//namespace gtx
}//namespace glm

#include "simd_mat4.inl"

namespace glm{using namespace gtx::simd_mat4;}

#endif//glm_gtx_simd_mat4
<|endoftext|>