<commit_before>
#include <iostream>
#include <ctime>
#include <fstream>
#include <math.h>
#include <iostream>

#include "MUSI8903Config.h"

#include "AudioFileIf.h"

using std::cout;
using std::endl;

// local function declarations
void    showClInfo ();

/////////////////////////////////////////////////////////////////////////////////
// main function
int main(int argc, char* argv[])
{
    std::string             sInputFilePath,                 //!< file paths
                            sOutputFilePath;

    long long               iInFileLength       = 0;        //!< length of input file

//    clock_t                 time                = 0;

    float                   **ppfAudioData      = 0;

    CAudioFileIf            *phAudioFile        = 0;

    CAudioFileIf::FileSpec_t psFileSpec        = {};

    std::ofstream outputFile;

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

    showClInfo ();

    //////////////////////////////////////////////////////////////////////////////
    // parse command line arguments

    if (argc < 2) {
        cout<<"Please provide the input and out path as the 1st and 2nd command line arguments respectively."<<endl;
        return 0;
    }
    else {
        sInputFilePath = argv[1];
        sOutputFilePath = argv[2];
    }

//    cout<<argv[0]<<"|"<<endl<<argv[1]<<"|"<<endl<<argv[2]<<endl;

    //////////////////////////////////////////////////////////////////////////////
    // open the input wave file

    phAudioFile->create(phAudioFile);

    int status = phAudioFile->openFile(sInputFilePath, CAudioFileIf::kFileRead);

    cout<<"File Open status -> "<<status<<endl;

    phAudioFile->getLength(iInFileLength);
    cout<<"The length is "<<iInFileLength<<" samples"<<endl;
    phAudioFile->getFileSpec(psFileSpec);
    cout<<"Num channels "<<psFileSpec.iNumChannels<<endl;

    //////////////////////////////////////////////////////////////////////////////
    // allocate memory

    ppfAudioData = new float *[psFileSpec.iNumChannels];

    for(int i = 0; i < psFileSpec.iNumChannels; i++){
        ppfAudioData[i] = new float[iInFileLength];
    }

    // get audio data
    phAudioFile->readData(ppfAudioData, iInFileLength);

    //////////////////////////////////////////////////////////////////////////////
    // get audio info and print it to stdout

    outputFile.open(sOutputFilePath,outputFile.app);

    outputFile <<"L\t"<<"R"<<endl;

    for (int i = 0; i < iInFileLength; i++) {
        outputFile << ppfAudioData[0][i] <<"\t" << ppfAudioData[1][i] <<endl ;
    }

    outputFile.close();

    //////////////////////////////////////////////////////////////////////////////
    // do processing
    cout << "\nHello there! File has been read successfully! " << endl << endl;

    //////////////////////////////////////////////////////////////////////////////
    // clean-up
    phAudioFile->destroy(phAudioFile);
    free(phAudioFile);

    delete ppfAudioData;

    return 0;

}

void     showClInfo()
{
    cout << "GTCMT MUSI8903" << endl;
    cout << "(c) 2016 by Alexander Lerch" << endl;
    cout  << endl;

    return;
}

<commit_msg>Deleted pointer<commit_after>
#include <iostream>
#include <ctime>
#include <fstream>
#include <math.h>
#include <iostream>

#include "MUSI8903Config.h"

#include "AudioFileIf.h"

using std::cout;
using std::endl;

// local function declarations
void    showClInfo ();

/////////////////////////////////////////////////////////////////////////////////
// main function
int main(int argc, char* argv[])
{
    std::string             sInputFilePath,                 //!< file paths
                            sOutputFilePath;

    long long               iInFileLength       = 0;        //!< length of input file

//    clock_t                 time                = 0;

    float                   **ppfAudioData      = 0;

    CAudioFileIf            *phAudioFile        = 0;

    CAudioFileIf::FileSpec_t psFileSpec        = {};

    std::ofstream outputFile;

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

    showClInfo ();

    //////////////////////////////////////////////////////////////////////////////
    // parse command line arguments

    if (argc < 2) {
        cout<<"Please provide the input and out path as the 1st and 2nd command line arguments respectively."<<endl;
        return 0;
    }
    else {
        sInputFilePath = argv[1];
        sOutputFilePath = argv[2];
    }

//    cout<<argv[0]<<"|"<<endl<<argv[1]<<"|"<<endl<<argv[2]<<endl;

    //////////////////////////////////////////////////////////////////////////////
    // open the input wave file

    phAudioFile->create(phAudioFile);

    int status = phAudioFile->openFile(sInputFilePath, CAudioFileIf::kFileRead);

    cout<<"File Open status -> "<<status<<endl;

    phAudioFile->getLength(iInFileLength);
    cout<<"The length is "<<iInFileLength<<" samples"<<endl;
    phAudioFile->getFileSpec(psFileSpec);
    cout<<"Num channels "<<psFileSpec.iNumChannels<<endl;

    //////////////////////////////////////////////////////////////////////////////
    // allocate memory

    ppfAudioData = new float *[psFileSpec.iNumChannels];

    for(int i = 0; i < psFileSpec.iNumChannels; i++){
        ppfAudioData[i] = new float[iInFileLength];
    }

    // get audio data
    phAudioFile->readData(ppfAudioData, iInFileLength);

    //////////////////////////////////////////////////////////////////////////////
    // get audio info and print it to stdout

    outputFile.open(sOutputFilePath,outputFile.app);

    outputFile <<"L\t"<<"R"<<endl;

    for (int i = 0; i < iInFileLength; i++) {
        outputFile << ppfAudioData[0][i] <<"\t" << ppfAudioData[1][i] <<endl ;
    }

    outputFile.close();

    //////////////////////////////////////////////////////////////////////////////
    // do processing
    cout << "\nHello there! File has been read successfully! " << endl << endl;

    //////////////////////////////////////////////////////////////////////////////
    // clean-up
    // clean-up
    for(int i = 0; i < psFileSpec.iNumChannels; i++) {
        delete [] ppfAudioData[i];
    }
    delete [] ppfAudioData;

    phAudioFile->destroy(phAudioFile);

    return 0;

}

void     showClInfo()
{
    cout << "GTCMT MUSI8903" << endl;
    cout << "(c) 2016 by Alexander Lerch" << endl;
    cout  << endl;

    return;
}

<|endoftext|>


<commit_before>/*
 * Copyright 2014 Mike Pontillo
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may
 * not use this file except in compliance with the License. You may obtain
 * a copy of the License at:
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <stdio.h>
#include <stdlib.h>
#include <pcap/pcap.h>
#include <inttypes.h>
#include <string.h>

#include <string>
#include <map>
#include <iterator>
#include <ctime> // a.k.a time.h

struct ScanContext
{
    uintmax_t packetCount;
    uintmax_t ethernetPacketCount;
    uintmax_t arpPacketCount;
    uintmax_t byteCount;
    unsigned int maxPacketLength;
    unsigned int minPacketLength;

    int isEthernet;

    struct timeval startTime;
    struct timeval endTime;

    std::map<std::string, long> packetCountPerSourceMac;
    std::map<std::string, long> packetCountPerDestMac;

    ScanContext() : packetCount(0), ethernetPacketCount(0), arpPacketCount(0), byteCount(0), maxPacketLength(0), minPacketLength(0), isEthernet(0)
    {
        memset(&this->startTime, 0, sizeof(struct timeval));
        memset(&this->endTime, 0, sizeof(struct timeval));
    }
};

static char* macToString(const unsigned char* bytes)
{
    static char mac[18];
    snprintf(mac, 18, "%02x:%02x:%02x:%02x:%02x:%02x",
             bytes[0],
             bytes[1],
             bytes[2],
             bytes[3],
             bytes[4],
             bytes[5]);

    return mac;
}

static void insertOrIncrementCounter(std::map<std::string, long> &map, std::string &key)
{
    if(map.find(key) != map.end())
    {
        map[key]++;
    }
    else
    {
        map[key] = 1;
    }
}

static void handlePossibleEthernetPacket(u_char *user, const struct pcap_pkthdr *h, const u_char *bytes)
{
    ScanContext* ctx = (struct ScanContext*) user;

    if(ctx->packetCount == 0)
    {
        ctx->startTime = h->ts;
    }
    else
    {
        // we don't know what the last packet will be...
        ctx->endTime = h->ts;
    }

    ctx->packetCount++;

    if(h->len > ctx->maxPacketLength)
    {
        ctx->maxPacketLength = h->len;
    }

    if(ctx->minPacketLength == 0 || h->len < ctx->minPacketLength)
    {
        ctx->minPacketLength = h->len;
    }

    ctx->byteCount += h->len;

    if(ctx->isEthernet)
    {
        ctx->ethernetPacketCount++;

        if(h->caplen >= 12)
        {
            std::string sourceMacString = macToString(bytes+6);
            std::string destMacString = macToString(bytes);

            insertOrIncrementCounter(ctx->packetCountPerDestMac, destMacString);
            insertOrIncrementCounter(ctx->packetCountPerSourceMac, sourceMacString);
        }
    }
}

static void handleArpPacket(u_char *user, const struct pcap_pkthdr *h, const u_char *bytes)
{
    ScanContext* ctx = (struct ScanContext*) user;

    ctx->arpPacketCount++;
}

static void printCountPerAddress(std::map<std::string, long> &macToCount)
{
    std::map<std::string, long>::iterator it;
    for (it = macToCount.begin();
         it != macToCount.end();
         it++)
    {
        printf("%8ld %s\n",
            it->second,
            it->first.c_str());
    }
}

static inline const char* timevalToLocalTime(struct timeval* time)
{
    time_t unixTime = time->tv_sec;
    struct tm* localTime = localtime(&unixTime);
    char* localTimeString = asctime(localTime);

    if(localTimeString)
    {
        localTimeString[strlen(localTimeString) - 1] = '\0';
    }

    return localTimeString ? localTimeString : "?";
}

static void printStatistics(struct ScanContext* ctx)
{
    printf("%ju packets\n", ctx->packetCount);
    printf("%ju Ethernet packets\n", ctx->ethernetPacketCount);
    printf("%ju ARP packets\n", ctx->arpPacketCount);
    printf("Max size packet: %u\n", ctx->maxPacketLength);
    printf("Min size packet: %u\n", ctx->minPacketLength);

    // note: the result from asctime() has a '\n' at the end, so we truncate it
    char* localTimeString;

    printf("Start time: %ju.%06ju seconds (%s)\n",
        (uintmax_t) ctx->startTime.tv_sec, (uintmax_t) ctx->startTime.tv_usec,
        timevalToLocalTime(&ctx->startTime));

    printf("End time: %ju.%06ju seconds (%s)\n",
        (uintmax_t) ctx->endTime.tv_sec, (uintmax_t) ctx->endTime.tv_usec,
        timevalToLocalTime(&ctx->endTime));

    long totalCaptureTime = ctx->endTime.tv_sec - ctx->startTime.tv_sec;
    if(0 == totalCaptureTime)
    {
        // round up to avoid divide by zero
        totalCaptureTime = 1;
    }

    printf("Total time: %ld seconds (%ld.%01ld minutes)\n",
        totalCaptureTime, totalCaptureTime / 60, totalCaptureTime % 60 * 10 / 60);

    printf("Total bytes captured: %ju bytes / %ju kilobytes / %ju megabytes\n",
        ctx->byteCount,
        ctx->byteCount / 1024,
        ctx->byteCount / 1024 / 1024);

    long kilobits = ctx->byteCount * 8 / 1024;
    long kilobitsPerSecond = kilobits / totalCaptureTime;
    printf("Overall capture speed: %ld Kbps (%ld Mbps)\n", kilobitsPerSecond, kilobitsPerSecond / 1024);

    if(!ctx->packetCountPerDestMac.empty())
    {
        printf("\nEthernet destinations:\n");
        printCountPerAddress(ctx->packetCountPerDestMac);
    }

    if(!ctx->packetCountPerSourceMac.empty())
    {
        printf("\nEthernet sources:\n");
        printCountPerAddress(ctx->packetCountPerSourceMac);
    }
}

static int applyCaptureFilter(pcap_t* pcap, struct bpf_program* bpf, const char* filter)
{
    int result = 0;

    if(-1 == pcap_compile(pcap,
                          bpf,
                          filter,
                          1 /* optimize */,
                          PCAP_NETMASK_UNKNOWN))
    {
        fprintf(stderr, "%s\n", pcap_geterr(pcap));
        result = -1;
        goto exit;
    }

    if(-1 == pcap_setfilter(pcap, bpf))
    {
        fprintf(stderr, "%s\n", pcap_geterr(pcap));
        result = -1;
        goto exit;
    }

exit:
    return result;
}

int main(int argc, char* argv[])
{
    int result = 0;
    pcap_t* pcap;
    char errbuf[PCAP_ERRBUF_SIZE];
    struct ScanContext ctx;
    struct bpf_program bpf = { 0 };

    if(argc < 2)
    {
        fprintf(stderr, "Not enough arguments. Please specify a pcap file.\n");
        result = 2;
        goto exit;
    }

    pcap = pcap_open_offline(argv[1], errbuf);
    if(NULL == pcap)
    {
        fprintf(stderr, "%s\n", errbuf);
        result = 3;
        goto exit;
    }

    if(DLT_EN10MB == pcap_datalink(pcap))
    {
        ctx.isEthernet = 1;
    }

    pcap_loop(pcap, -1, handlePossibleEthernetPacket, (u_char*) &ctx);

    // reopen file and check against a capture filter
    pcap_close(pcap);

    pcap = pcap_open_offline(argv[1], errbuf);
    if(NULL == pcap)
    {
        fprintf(stderr, "%s\n", errbuf);
        result = 4;
        goto exit;
    }

    if(0 != applyCaptureFilter(pcap, &bpf, "arp"))
    {
        // expression could reject all packets and throw an error
        goto skip_arp;
    }
    pcap_loop(pcap, -1, handleArpPacket, (u_char*) &ctx);

skip_arp:
    pcap_close(pcap);

    // All done with packet processing.
    printStatistics(&ctx);

exit:
    return result;
}
<commit_msg>Add average packet size<commit_after>/*
 * Copyright 2014 Mike Pontillo
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may
 * not use this file except in compliance with the License. You may obtain
 * a copy of the License at:
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <stdio.h>
#include <stdlib.h>
#include <pcap/pcap.h>
#include <inttypes.h>
#include <string.h>

#include <string>
#include <map>
#include <iterator>
#include <ctime> // a.k.a time.h

struct ScanContext
{
    uintmax_t packetCount;
    uintmax_t ethernetPacketCount;
    uintmax_t arpPacketCount;
    uintmax_t byteCount;
    unsigned int maxPacketLength;
    unsigned int minPacketLength;

    int isEthernet;

    struct timeval startTime;
    struct timeval endTime;

    std::map<std::string, long> packetCountPerSourceMac;
    std::map<std::string, long> packetCountPerDestMac;

    ScanContext() : packetCount(0), ethernetPacketCount(0), arpPacketCount(0), byteCount(0), maxPacketLength(0), minPacketLength(0), isEthernet(0)
    {
        memset(&this->startTime, 0, sizeof(struct timeval));
        memset(&this->endTime, 0, sizeof(struct timeval));
    }
};

static char* macToString(const unsigned char* bytes)
{
    static char mac[18];
    snprintf(mac, 18, "%02x:%02x:%02x:%02x:%02x:%02x",
             bytes[0],
             bytes[1],
             bytes[2],
             bytes[3],
             bytes[4],
             bytes[5]);

    return mac;
}

static void insertOrIncrementCounter(std::map<std::string, long> &map, std::string &key)
{
    if(map.find(key) != map.end())
    {
        map[key]++;
    }
    else
    {
        map[key] = 1;
    }
}

static void handlePossibleEthernetPacket(u_char *user, const struct pcap_pkthdr *h, const u_char *bytes)
{
    ScanContext* ctx = (struct ScanContext*) user;

    if(ctx->packetCount == 0)
    {
        ctx->startTime = h->ts;
    }
    else
    {
        // we don't know what the last packet will be...
        ctx->endTime = h->ts;
    }

    ctx->packetCount++;

    if(h->len > ctx->maxPacketLength)
    {
        ctx->maxPacketLength = h->len;
    }

    if(ctx->minPacketLength == 0 || h->len < ctx->minPacketLength)
    {
        ctx->minPacketLength = h->len;
    }

    ctx->byteCount += h->len;

    if(ctx->isEthernet)
    {
        ctx->ethernetPacketCount++;

        if(h->caplen >= 12)
        {
            std::string sourceMacString = macToString(bytes+6);
            std::string destMacString = macToString(bytes);

            insertOrIncrementCounter(ctx->packetCountPerDestMac, destMacString);
            insertOrIncrementCounter(ctx->packetCountPerSourceMac, sourceMacString);
        }
    }
}

static void handleArpPacket(u_char *user, const struct pcap_pkthdr *h, const u_char *bytes)
{
    ScanContext* ctx = (struct ScanContext*) user;

    ctx->arpPacketCount++;
}

static void printCountPerAddress(std::map<std::string, long> &macToCount)
{
    std::map<std::string, long>::iterator it;
    for (it = macToCount.begin();
         it != macToCount.end();
         it++)
    {
        printf("%8ld %s\n",
            it->second,
            it->first.c_str());
    }
}

static inline const char* timevalToLocalTime(struct timeval* time)
{
    time_t unixTime = time->tv_sec;
    struct tm* localTime = localtime(&unixTime);
    char* localTimeString = asctime(localTime);

    // note: the result from asctime() has a '\n' at the end, so we truncate it
    if(localTimeString)
    {
        localTimeString[strlen(localTimeString) - 1] = '\0';
    }

    return localTimeString ? localTimeString : "?";
}

static void printStatistics(struct ScanContext* ctx)
{
    printf("%ju packets\n", ctx->packetCount);
    printf("%ju Ethernet packets\n", ctx->ethernetPacketCount);
    printf("%ju ARP packets\n", ctx->arpPacketCount);
    printf("Min size packet: %u\n", ctx->minPacketLength);
    printf("Max size packet: %u\n", ctx->maxPacketLength);

    if(0 != ctx->packetCount)
    {
        printf("Average size packet: %ju\n", ctx->byteCount / ctx->packetCount);
    }

    printf("Start time: %ju.%06ju seconds (%s)\n",
        (uintmax_t) ctx->startTime.tv_sec, (uintmax_t) ctx->startTime.tv_usec,
        timevalToLocalTime(&ctx->startTime));

    printf("End time: %ju.%06ju seconds (%s)\n",
        (uintmax_t) ctx->endTime.tv_sec, (uintmax_t) ctx->endTime.tv_usec,
        timevalToLocalTime(&ctx->endTime));

    long totalCaptureTime = ctx->endTime.tv_sec - ctx->startTime.tv_sec;
    if(0 == totalCaptureTime)
    {
        // round up to avoid divide by zero
        totalCaptureTime = 1;
    }

    printf("Total time: %ld seconds (%ld.%01ld minutes)\n",
        totalCaptureTime, totalCaptureTime / 60, totalCaptureTime % 60 * 10 / 60);

    printf("Total bytes captured: %ju bytes / %ju kilobytes / %ju megabytes\n",
        ctx->byteCount,
        ctx->byteCount / 1024,
        ctx->byteCount / 1024 / 1024);

    long kilobits = ctx->byteCount * 8 / 1024;
    long kilobitsPerSecond = kilobits / totalCaptureTime;
    printf("Overall capture speed: %ld Kbps (%ld Mbps)\n", kilobitsPerSecond, kilobitsPerSecond / 1024);

    if(!ctx->packetCountPerDestMac.empty())
    {
        printf("\nEthernet destinations:\n");
        printCountPerAddress(ctx->packetCountPerDestMac);
    }

    if(!ctx->packetCountPerSourceMac.empty())
    {
        printf("\nEthernet sources:\n");
        printCountPerAddress(ctx->packetCountPerSourceMac);
    }
}

static int applyCaptureFilter(pcap_t* pcap, const char* filter)
{
    int result = 0;
    struct bpf_program* bpf = (struct bpf_program*) calloc(1, sizeof(struct bpf_program));

    if(NULL == bpf)
    {
        perror("calloc");
        result = -1;
        goto exit;
    }

    if(-1 == pcap_compile(pcap,
                          bpf,
                          filter,
                          1 /* optimize */,
                          PCAP_NETMASK_UNKNOWN))
    {
        fprintf(stderr, "%s\n", pcap_geterr(pcap));
        result = -1;
        goto exit;
    }

    if(-1 == pcap_setfilter(pcap, bpf))
    {
        fprintf(stderr, "%s\n", pcap_geterr(pcap));
        result = -1;
        goto exit;
    }

exit:
    if(NULL != bpf)
    {
        pcap_freecode(bpf);
        free(bpf);
    }

    return result;
}

int main(int argc, char* argv[])
{
    int result = 0;
    pcap_t* pcap;
    char errbuf[PCAP_ERRBUF_SIZE];
    struct ScanContext ctx;

    if(argc < 2)
    {
        fprintf(stderr, "Not enough arguments. Please specify a pcap file.\n");
        result = 2;
        goto exit;
    }

    pcap = pcap_open_offline(argv[1], errbuf);
    if(NULL == pcap)
    {
        fprintf(stderr, "%s\n", errbuf);
        result = 3;
        goto exit;
    }

    if(DLT_EN10MB == pcap_datalink(pcap))
    {
        ctx.isEthernet = 1;
    }

    pcap_loop(pcap, -1, handlePossibleEthernetPacket, (u_char*) &ctx);

    // reopen file and check against a capture filter
    pcap_close(pcap);

    pcap = pcap_open_offline(argv[1], errbuf);
    if(NULL == pcap)
    {
        fprintf(stderr, "%s\n", errbuf);
        result = 4;
        goto exit;
    }

    if(0 != applyCaptureFilter(pcap, "arp"))
    {
        // expression could reject all packets and throw an error
        goto skip_arp;
    }
    pcap_loop(pcap, -1, handleArpPacket, (u_char*) &ctx);

skip_arp:
    pcap_close(pcap);

    // All done with packet processing.
    printStatistics(&ctx);

exit:
    return result;
}
<|endoftext|>


<commit_before><commit_msg>Resolves: #i119516# allow 0x1 0x1 as well as 0x8 0x1 detection for canvases<commit_after><|endoftext|>


<commit_before>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkSeedWidget.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/
#include "vtkSeedWidget.h"
#include "vtkSeedRepresentation.h"
#include "vtkCommand.h"
#include "vtkCallbackCommand.h"
#include "vtkRenderWindowInteractor.h"
#include "vtkObjectFactory.h"
#include "vtkRenderer.h"
#include "vtkHandleWidget.h"
#include "vtkHandleRepresentation.h"
#include "vtkCoordinate.h"
#include "vtkWidgetCallbackMapper.h"
#include "vtkWidgetEvent.h"
#include "vtkRenderWindow.h"
#include "vtkEvent.h"
#include <vtkstd/vector>

vtkCxxRevisionMacro(vtkSeedWidget, "1.7");
vtkStandardNewMacro(vtkSeedWidget);

// The vtkSeedList is a PIMPLed vector<T>.
class vtkSeedList : public vtkstd::vector<vtkHandleWidget*> {};
typedef vtkstd::vector<vtkHandleWidget*>::iterator vtkSeedListIterator;

//----------------------------------------------------------------------
vtkSeedWidget::vtkSeedWidget()
{
  this->ManagesCursor = 1;
  this->WidgetState = vtkSeedWidget::Start;

  // The widgets for moving the seeds.
  this->Seeds = new vtkSeedList;

  // These are the event callbacks supported by this widget
  this->CallbackMapper->SetCallbackMethod(vtkCommand::LeftButtonPressEvent,
                                          vtkWidgetEvent::AddPoint,
                                          this, vtkSeedWidget::AddPointAction);
  this->CallbackMapper->SetCallbackMethod(vtkCommand::RightButtonPressEvent,
                                          vtkWidgetEvent::Completed,
                                          this, vtkSeedWidget::CompletedAction);
  this->CallbackMapper->SetCallbackMethod(vtkCommand::MouseMoveEvent,
                                          vtkWidgetEvent::Move,
                                          this, vtkSeedWidget::MoveAction);
  this->CallbackMapper->SetCallbackMethod(vtkCommand::LeftButtonReleaseEvent,
                                          vtkWidgetEvent::EndSelect,
                                          this, vtkSeedWidget::EndSelectAction);
  this->CallbackMapper->SetCallbackMethod(vtkCommand::KeyPressEvent,
                                          vtkEvent::NoModifier, 47, 1, NULL,
                                          vtkWidgetEvent::Delete,
                                          this, vtkSeedWidget::DeleteAction);
}

//----------------------------------------------------------------------
inline void vtkSeedWidget::DeleteSeed(int i)
{
  (*this->Seeds)[i]->RemoveObservers(vtkCommand::StartInteractionEvent);
  (*this->Seeds)[i]->RemoveObservers(vtkCommand::InteractionEvent);
  (*this->Seeds)[i]->RemoveObservers(vtkCommand::EndInteractionEvent);
  (*this->Seeds)[i]->Delete();
}

//----------------------------------------------------------------------
vtkSeedWidget::~vtkSeedWidget()
{
  // Loop over all seeds releasing their observes and deleting them
  for (unsigned int i=0; i<this->Seeds->size(); ++i)
    {
    this->DeleteSeed(i);
    }
  delete this->Seeds;
}

//----------------------------------------------------------------------
void vtkSeedWidget::CreateDefaultRepresentation()
{
  if ( ! this->WidgetRep )
    {
    this->WidgetRep = vtkSeedRepresentation::New();
    }
}

//----------------------------------------------------------------------
void vtkSeedWidget::SetEnabled(int enabling)
{
  this->Superclass::SetEnabled(enabling);

  if ( ! enabling )
    {
    this->WidgetState = vtkSeedWidget::Start;
    vtkSeedListIterator siter;
    for (siter=this->Seeds->begin(); siter != this->Seeds->end(); ++siter )
      {
      (*siter)->SetEnabled(0);
      }
    }
}

//-------------------------------------------------------------------------
vtkHandleWidget *vtkSeedWidget::CreateHandleWidget(vtkSeedWidget *self,
                                                   vtkSeedRepresentation *rep)
{
  // Create the handle widget or reuse an old one
  int currentHandleNumber = self->Seeds->size();
  vtkHandleWidget *widget = vtkHandleWidget::New();

  // Configure the handle widget
  widget->SetParent(self);
  widget->SetInteractor(self->Interactor);

  vtkHandleRepresentation *handleRep = rep->GetHandleRepresentation(currentHandleNumber);
  handleRep->SetRenderer(self->CurrentRenderer);
  widget->SetRepresentation(handleRep);

  // Now place the widget into the list of handle widgets (if not already there)
  self->Seeds->resize(currentHandleNumber+1,NULL);
  (*self->Seeds)[currentHandleNumber] = widget;

  return widget;
}

// The following methods are the callbacks that the seed widget responds to.
//-------------------------------------------------------------------------
void vtkSeedWidget::AddPointAction(vtkAbstractWidget *w)
{
  vtkSeedWidget *self = reinterpret_cast<vtkSeedWidget*>(w);

  // Need to distinguish between placing handles and manipulating handles
  if ( self->WidgetState == vtkSeedWidget::MovingSeed ||
       self->WidgetState == vtkSeedWidget::PlacedSeeds )
    {
    return;
    }

  // compute some info we need for all cases
  int X = self->Interactor->GetEventPosition()[0];
  int Y = self->Interactor->GetEventPosition()[1];

  // When a seed is placed, a new handle widget must be created and enabled.
  int state = self->WidgetRep->ComputeInteractionState(X,Y);
  if ( state == vtkSeedRepresentation::NearSeed )
    {
    self->WidgetState = vtkSeedWidget::MovingSeed;
//    int currentHandleNumber = reinterpret_cast<vtkSeedRepresentation*>(self->WidgetRep)->
//      GetActiveHandle();

    // Invoke an event on ourself for the handles
    self->InvokeEvent(vtkCommand::LeftButtonPressEvent,NULL);
    self->Superclass::StartInteraction();
    self->InvokeEvent(vtkCommand::StartInteractionEvent,NULL);
    }

  else //we are placing a new seed
    {
    self->WidgetState = vtkSeedWidget::PlacingSeeds;
    double e[3]; e[2]=0.0;
    e[0] = static_cast<double>(X);
    e[1] = static_cast<double>(Y);
    vtkSeedRepresentation *rep = reinterpret_cast<vtkSeedRepresentation*>(self->WidgetRep);
    int currentHandleNumber = rep->CreateHandle(e);
    vtkHandleWidget *currentHandle = self->CreateHandleWidget(self,rep);
    rep->SetSeedDisplayPosition(currentHandleNumber,e);
    currentHandle->SetEnabled(1);
    self->InvokeEvent(vtkCommand::PlacePointEvent,(void*)&(currentHandleNumber));
    self->InvokeEvent(vtkCommand::InteractionEvent,NULL);
    }

  self->EventCallbackCommand->SetAbortFlag(1);
  self->Render();
}

//-------------------------------------------------------------------------
void vtkSeedWidget::CompletedAction(vtkAbstractWidget *w)
{
  vtkSeedWidget *self = reinterpret_cast<vtkSeedWidget*>(w);

  // Do something only if we are in the middle of placing the seeds
  if ( self->WidgetState != vtkSeedWidget::PlacingSeeds )
    {
    return;
    }

  // All we do is set the state to placed
  self->WidgetState = vtkSeedWidget::PlacedSeeds;
  self->EventCallbackCommand->SetAbortFlag(1);
}

//-------------------------------------------------------------------------
void vtkSeedWidget::MoveAction(vtkAbstractWidget *w)
{
  vtkSeedWidget *self = reinterpret_cast<vtkSeedWidget*>(w);

  // Do nothing if outside
  if ( self->WidgetState == vtkSeedWidget::Start ||
       self->WidgetState == vtkSeedWidget::PlacedSeeds )
    {
    return;
    }

  // else we are moving a seed
  self->InvokeEvent(vtkCommand::MouseMoveEvent, NULL);
  self->RequestCursorShape(VTK_CURSOR_HAND);
  self->EventCallbackCommand->SetAbortFlag(1);
  self->InvokeEvent(vtkCommand::InteractionEvent,NULL);
  self->Render();
}

//-------------------------------------------------------------------------
void vtkSeedWidget::EndSelectAction(vtkAbstractWidget *w)
{
  vtkSeedWidget *self = reinterpret_cast<vtkSeedWidget*>(w);

  // Do nothing if outside
  if ( self->WidgetState != vtkSeedWidget::MovingSeed )
    {
    return;
    }

  // Invoke event for seed handle
  self->WidgetState = vtkSeedWidget::PlacingSeeds;
  self->InvokeEvent(vtkCommand::LeftButtonReleaseEvent,NULL);
  self->EventCallbackCommand->SetAbortFlag(1);
  self->InvokeEvent(vtkCommand::EndInteractionEvent,NULL);
  self->Superclass::EndInteraction();
  self->Render();
}

//-------------------------------------------------------------------------
void vtkSeedWidget::DeleteAction(vtkAbstractWidget *w)
{
  cout << "Delete action\n";
  vtkSeedWidget *self = reinterpret_cast<vtkSeedWidget*>(w);

  // Do nothing if outside
  if ( self->WidgetState != vtkSeedWidget::PlacingSeeds )
    {
    return;
    }

  // Remove last seed
  vtkSeedRepresentation *rep = reinterpret_cast<vtkSeedRepresentation*>(self->WidgetRep);
  rep->RemoveLastHandle();
  int last = self->Seeds->size()-1;
  (*self->Seeds)[last]->SetEnabled(0);
  self->DeleteSeed(last);
  self->Seeds->pop_back();

  // Got this event, abort processing if it
  self->EventCallbackCommand->SetAbortFlag(1);
  self->Render();
}

//----------------------------------------------------------------------
void vtkSeedWidget::SetProcessEvents(int pe)
{
  this->Superclass::SetProcessEvents(pe);

  vtkSeedListIterator iter = this->Seeds->begin();
  for (; iter != this->Seeds->end(); ++iter)
    {
    (*iter)->SetProcessEvents(pe);
    }
}

//----------------------------------------------------------------------
void vtkSeedWidget::PrintSelf(ostream& os, vtkIndent indent)
{
  //Superclass typedef defined in vtkTypeMacro() found in vtkSetGet.h
  this->Superclass::PrintSelf(os,indent);
}
<commit_msg>STYLE: Bug #4044 - STYLE: cout should be removed<commit_after>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkSeedWidget.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/
#include "vtkSeedWidget.h"
#include "vtkSeedRepresentation.h"
#include "vtkCommand.h"
#include "vtkCallbackCommand.h"
#include "vtkRenderWindowInteractor.h"
#include "vtkObjectFactory.h"
#include "vtkRenderer.h"
#include "vtkHandleWidget.h"
#include "vtkHandleRepresentation.h"
#include "vtkCoordinate.h"
#include "vtkWidgetCallbackMapper.h"
#include "vtkWidgetEvent.h"
#include "vtkRenderWindow.h"
#include "vtkEvent.h"
#include <vtkstd/vector>

vtkCxxRevisionMacro(vtkSeedWidget, "1.8");
vtkStandardNewMacro(vtkSeedWidget);

// The vtkSeedList is a PIMPLed vector<T>.
class vtkSeedList : public vtkstd::vector<vtkHandleWidget*> {};
typedef vtkstd::vector<vtkHandleWidget*>::iterator vtkSeedListIterator;

//----------------------------------------------------------------------
vtkSeedWidget::vtkSeedWidget()
{
  this->ManagesCursor = 1;
  this->WidgetState = vtkSeedWidget::Start;

  // The widgets for moving the seeds.
  this->Seeds = new vtkSeedList;

  // These are the event callbacks supported by this widget
  this->CallbackMapper->SetCallbackMethod(vtkCommand::LeftButtonPressEvent,
                                          vtkWidgetEvent::AddPoint,
                                          this, vtkSeedWidget::AddPointAction);
  this->CallbackMapper->SetCallbackMethod(vtkCommand::RightButtonPressEvent,
                                          vtkWidgetEvent::Completed,
                                          this, vtkSeedWidget::CompletedAction);
  this->CallbackMapper->SetCallbackMethod(vtkCommand::MouseMoveEvent,
                                          vtkWidgetEvent::Move,
                                          this, vtkSeedWidget::MoveAction);
  this->CallbackMapper->SetCallbackMethod(vtkCommand::LeftButtonReleaseEvent,
                                          vtkWidgetEvent::EndSelect,
                                          this, vtkSeedWidget::EndSelectAction);
  this->CallbackMapper->SetCallbackMethod(vtkCommand::KeyPressEvent,
                                          vtkEvent::NoModifier, 47, 1, NULL,
                                          vtkWidgetEvent::Delete,
                                          this, vtkSeedWidget::DeleteAction);
}

//----------------------------------------------------------------------
inline void vtkSeedWidget::DeleteSeed(int i)
{
  (*this->Seeds)[i]->RemoveObservers(vtkCommand::StartInteractionEvent);
  (*this->Seeds)[i]->RemoveObservers(vtkCommand::InteractionEvent);
  (*this->Seeds)[i]->RemoveObservers(vtkCommand::EndInteractionEvent);
  (*this->Seeds)[i]->Delete();
}

//----------------------------------------------------------------------
vtkSeedWidget::~vtkSeedWidget()
{
  // Loop over all seeds releasing their observes and deleting them
  for (unsigned int i=0; i<this->Seeds->size(); ++i)
    {
    this->DeleteSeed(i);
    }
  delete this->Seeds;
}

//----------------------------------------------------------------------
void vtkSeedWidget::CreateDefaultRepresentation()
{
  if ( ! this->WidgetRep )
    {
    this->WidgetRep = vtkSeedRepresentation::New();
    }
}

//----------------------------------------------------------------------
void vtkSeedWidget::SetEnabled(int enabling)
{
  this->Superclass::SetEnabled(enabling);

  if ( ! enabling )
    {
    this->WidgetState = vtkSeedWidget::Start;
    vtkSeedListIterator siter;
    for (siter=this->Seeds->begin(); siter != this->Seeds->end(); ++siter )
      {
      (*siter)->SetEnabled(0);
      }
    }
}

//-------------------------------------------------------------------------
vtkHandleWidget *vtkSeedWidget::CreateHandleWidget(vtkSeedWidget *self,
                                                   vtkSeedRepresentation *rep)
{
  // Create the handle widget or reuse an old one
  int currentHandleNumber = self->Seeds->size();
  vtkHandleWidget *widget = vtkHandleWidget::New();

  // Configure the handle widget
  widget->SetParent(self);
  widget->SetInteractor(self->Interactor);

  vtkHandleRepresentation *handleRep = rep->GetHandleRepresentation(currentHandleNumber);
  handleRep->SetRenderer(self->CurrentRenderer);
  widget->SetRepresentation(handleRep);

  // Now place the widget into the list of handle widgets (if not already there)
  self->Seeds->resize(currentHandleNumber+1,NULL);
  (*self->Seeds)[currentHandleNumber] = widget;

  return widget;
}

// The following methods are the callbacks that the seed widget responds to.
//-------------------------------------------------------------------------
void vtkSeedWidget::AddPointAction(vtkAbstractWidget *w)
{
  vtkSeedWidget *self = reinterpret_cast<vtkSeedWidget*>(w);

  // Need to distinguish between placing handles and manipulating handles
  if ( self->WidgetState == vtkSeedWidget::MovingSeed ||
       self->WidgetState == vtkSeedWidget::PlacedSeeds )
    {
    return;
    }

  // compute some info we need for all cases
  int X = self->Interactor->GetEventPosition()[0];
  int Y = self->Interactor->GetEventPosition()[1];

  // When a seed is placed, a new handle widget must be created and enabled.
  int state = self->WidgetRep->ComputeInteractionState(X,Y);
  if ( state == vtkSeedRepresentation::NearSeed )
    {
    self->WidgetState = vtkSeedWidget::MovingSeed;
//    int currentHandleNumber = reinterpret_cast<vtkSeedRepresentation*>(self->WidgetRep)->
//      GetActiveHandle();

    // Invoke an event on ourself for the handles
    self->InvokeEvent(vtkCommand::LeftButtonPressEvent,NULL);
    self->Superclass::StartInteraction();
    self->InvokeEvent(vtkCommand::StartInteractionEvent,NULL);
    }

  else //we are placing a new seed
    {
    self->WidgetState = vtkSeedWidget::PlacingSeeds;
    double e[3]; e[2]=0.0;
    e[0] = static_cast<double>(X);
    e[1] = static_cast<double>(Y);
    vtkSeedRepresentation *rep = reinterpret_cast<vtkSeedRepresentation*>(self->WidgetRep);
    int currentHandleNumber = rep->CreateHandle(e);
    vtkHandleWidget *currentHandle = self->CreateHandleWidget(self,rep);
    rep->SetSeedDisplayPosition(currentHandleNumber,e);
    currentHandle->SetEnabled(1);
    self->InvokeEvent(vtkCommand::PlacePointEvent,(void*)&(currentHandleNumber));
    self->InvokeEvent(vtkCommand::InteractionEvent,NULL);
    }

  self->EventCallbackCommand->SetAbortFlag(1);
  self->Render();
}

//-------------------------------------------------------------------------
void vtkSeedWidget::CompletedAction(vtkAbstractWidget *w)
{
  vtkSeedWidget *self = reinterpret_cast<vtkSeedWidget*>(w);

  // Do something only if we are in the middle of placing the seeds
  if ( self->WidgetState != vtkSeedWidget::PlacingSeeds )
    {
    return;
    }

  // All we do is set the state to placed
  self->WidgetState = vtkSeedWidget::PlacedSeeds;
  self->EventCallbackCommand->SetAbortFlag(1);
}

//-------------------------------------------------------------------------
void vtkSeedWidget::MoveAction(vtkAbstractWidget *w)
{
  vtkSeedWidget *self = reinterpret_cast<vtkSeedWidget*>(w);

  // Do nothing if outside
  if ( self->WidgetState == vtkSeedWidget::Start ||
       self->WidgetState == vtkSeedWidget::PlacedSeeds )
    {
    return;
    }

  // else we are moving a seed
  self->InvokeEvent(vtkCommand::MouseMoveEvent, NULL);
  self->RequestCursorShape(VTK_CURSOR_HAND);
  self->EventCallbackCommand->SetAbortFlag(1);
  self->InvokeEvent(vtkCommand::InteractionEvent,NULL);
  self->Render();
}

//-------------------------------------------------------------------------
void vtkSeedWidget::EndSelectAction(vtkAbstractWidget *w)
{
  vtkSeedWidget *self = reinterpret_cast<vtkSeedWidget*>(w);

  // Do nothing if outside
  if ( self->WidgetState != vtkSeedWidget::MovingSeed )
    {
    return;
    }

  // Invoke event for seed handle
  self->WidgetState = vtkSeedWidget::PlacingSeeds;
  self->InvokeEvent(vtkCommand::LeftButtonReleaseEvent,NULL);
  self->EventCallbackCommand->SetAbortFlag(1);
  self->InvokeEvent(vtkCommand::EndInteractionEvent,NULL);
  self->Superclass::EndInteraction();
  self->Render();
}

//-------------------------------------------------------------------------
void vtkSeedWidget::DeleteAction(vtkAbstractWidget *w)
{
  vtkSeedWidget *self = reinterpret_cast<vtkSeedWidget*>(w);

  // Do nothing if outside
  if ( self->WidgetState != vtkSeedWidget::PlacingSeeds )
    {
    return;
    }

  // Remove last seed
  vtkSeedRepresentation *rep = reinterpret_cast<vtkSeedRepresentation*>(self->WidgetRep);
  rep->RemoveLastHandle();
  int last = self->Seeds->size()-1;
  (*self->Seeds)[last]->SetEnabled(0);
  self->DeleteSeed(last);
  self->Seeds->pop_back();

  // Got this event, abort processing if it
  self->EventCallbackCommand->SetAbortFlag(1);
  self->Render();
}

//----------------------------------------------------------------------
void vtkSeedWidget::SetProcessEvents(int pe)
{
  this->Superclass::SetProcessEvents(pe);

  vtkSeedListIterator iter = this->Seeds->begin();
  for (; iter != this->Seeds->end(); ++iter)
    {
    (*iter)->SetProcessEvents(pe);
    }
}

//----------------------------------------------------------------------
void vtkSeedWidget::PrintSelf(ostream& os, vtkIndent indent)
{
  //Superclass typedef defined in vtkTypeMacro() found in vtkSetGet.h
  this->Superclass::PrintSelf(os,indent);
}
<|endoftext|>


<commit_before>/******************************************************************************
*       SOFA, Simulation Open-Framework Architecture, development version     *
*                (c) 2006-2017 INRIA, USTL, UJF, CNRS, MGH                    *
*                                                                             *
* This program 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; either version 2.1 of the License, or (at     *
* your option) any later version.                                             *
*                                                                             *
* This program is distributed in the hope that it will be useful, but WITHOUT *
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or       *
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License *
* for more details.                                                           *
*                                                                             *
* You should have received a copy of the GNU Lesser General Public License    *
* along with this program. If not, see <http://www.gnu.org/licenses/>.        *
*******************************************************************************
* Authors: The SOFA Team and external contributors (see Authors.txt)          *
*                                                                             *
* Contact information: contact@sofa-framework.org                             *
******************************************************************************/

#include "Binding_GridTopology.h"
#include "Binding_MeshTopology.h"

using namespace sofa::component::topology;
using namespace sofa::core::objectmodel;

extern "C" PyObject * GridTopology_setSize(PyObject *self, PyObject * args)
{
    GridTopology* obj=down_cast<GridTopology>(((PySPtr<Base>*)self)->object->toTopology());
    int nx,ny,nz;
    if (!PyArg_ParseTuple(args, "iii",&nx,&ny,&nz))
    {
        PyErr_BadArgument();
        return NULL;
    }
    obj->setSize(nx,ny,nz);
    Py_RETURN_NONE;
}

extern "C" PyObject * GridTopology_setNumVertices(PyObject *self, PyObject * args)
{
    GridTopology* obj=down_cast<GridTopology>(((PySPtr<Base>*)self)->object->toTopology());
    int nx,ny,nz;
    if (!PyArg_ParseTuple(args, "iii",&nx,&ny,&nz))
    {
        PyErr_BadArgument();
        return NULL;
    }
    obj->setNumVertices(nx,ny,nz);
    Py_RETURN_NONE;
}

extern "C" PyObject * GridTopology_getNx(PyObject *self, PyObject * /*args*/)
{
    GridTopology* obj=down_cast<GridTopology>(((PySPtr<Base>*)self)->object->toTopology());
    return PyInt_FromLong(obj->getNx());
}

extern "C" PyObject * GridTopology_setNx(PyObject *self, PyObject * args)
{
    GridTopology* obj=down_cast<GridTopology>(((PySPtr<Base>*)self)->object->toTopology());
    int nb;
    if (!PyArg_ParseTuple(args, "i",&nb))
    {
        PyErr_BadArgument();
        return NULL;
    }
    obj->setNx(nb);
    Py_RETURN_NONE;
}

extern "C" PyObject * GridTopology_getNy(PyObject *self, PyObject * /*args*/)
{
    GridTopology* obj=down_cast<GridTopology>(((PySPtr<Base>*)self)->object->toTopology());
    return PyInt_FromLong(obj->getNy());
}

extern "C" PyObject * GridTopology_setNy(PyObject *self, PyObject * args)
{
    GridTopology* obj=down_cast<GridTopology>(((PySPtr<Base>*)self)->object->toTopology());
    int nb;
    if (!PyArg_ParseTuple(args, "i",&nb))
    {
        PyErr_BadArgument();
        return NULL;
    }
    obj->setNy(nb);
    Py_RETURN_NONE;
}

extern "C" PyObject * GridTopology_getNz(PyObject *self, PyObject * /*args*/)
{
    GridTopology* obj=down_cast<GridTopology>(((PySPtr<Base>*)self)->object->toTopology());
    return PyInt_FromLong(obj->getNz());
}

extern "C" PyObject * GridTopology_setNz(PyObject *self, PyObject * args)
{
    GridTopology* obj=down_cast<GridTopology>(((PySPtr<Base>*)self)->object->toTopology());
    int nb;
    if (!PyArg_ParseTuple(args, "i",&nb))
    {
        PyErr_BadArgument();
        return NULL;
    }
    obj->setNz(nb);
    Py_RETURN_NONE;
}

SP_CLASS_METHODS_BEGIN(GridTopology)
SP_CLASS_METHOD(GridTopology,setSize)
SP_CLASS_METHOD(GridTopology,setNumVertices)
SP_CLASS_METHOD(GridTopology,getNx)
SP_CLASS_METHOD(GridTopology,getNy)
SP_CLASS_METHOD(GridTopology,getNz)
SP_CLASS_METHOD(GridTopology,setNx)
SP_CLASS_METHOD(GridTopology,setNy)
SP_CLASS_METHOD(GridTopology,setNz)
SP_CLASS_METHODS_END

SP_CLASS_TYPE_SPTR(GridTopology,GridTopology,MeshTopology)

<commit_msg>[SofaPython] FIX: remove the method GridTopology_setNumVertices as it was duplication from GridTopology_setSize<commit_after>/******************************************************************************
*       SOFA, Simulation Open-Framework Architecture, development version     *
*                (c) 2006-2017 INRIA, USTL, UJF, CNRS, MGH                    *
*                                                                             *
* This program 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; either version 2.1 of the License, or (at     *
* your option) any later version.                                             *
*                                                                             *
* This program is distributed in the hope that it will be useful, but WITHOUT *
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or       *
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License *
* for more details.                                                           *
*                                                                             *
* You should have received a copy of the GNU Lesser General Public License    *
* along with this program. If not, see <http://www.gnu.org/licenses/>.        *
*******************************************************************************
* Authors: The SOFA Team and external contributors (see Authors.txt)          *
*                                                                             *
* Contact information: contact@sofa-framework.org                             *
******************************************************************************/

#include "Binding_GridTopology.h"
#include "Binding_MeshTopology.h"

using namespace sofa::component::topology;
using namespace sofa::core::objectmodel;

extern "C" PyObject * GridTopology_setSize(PyObject *self, PyObject * args)
{
    GridTopology* obj=down_cast<GridTopology>(((PySPtr<Base>*)self)->object->toTopology());
    int nx,ny,nz;
    if (!PyArg_ParseTuple(args, "iii",&nx,&ny,&nz))
    {
        PyErr_BadArgument();
        return NULL;
    }
    obj->setSize(nx,ny,nz);
    Py_RETURN_NONE;
}

extern "C" PyObject * GridTopology_getNx(PyObject *self, PyObject * /*args*/)
{
    GridTopology* obj=down_cast<GridTopology>(((PySPtr<Base>*)self)->object->toTopology());
    return PyInt_FromLong(obj->getNx());
}

extern "C" PyObject * GridTopology_setNx(PyObject *self, PyObject * args)
{
    GridTopology* obj=down_cast<GridTopology>(((PySPtr<Base>*)self)->object->toTopology());
    int nb;
    if (!PyArg_ParseTuple(args, "i",&nb))
    {
        PyErr_BadArgument();
        return NULL;
    }
    obj->setNx(nb);
    Py_RETURN_NONE;
}

extern "C" PyObject * GridTopology_getNy(PyObject *self, PyObject * /*args*/)
{
    GridTopology* obj=down_cast<GridTopology>(((PySPtr<Base>*)self)->object->toTopology());
    return PyInt_FromLong(obj->getNy());
}

extern "C" PyObject * GridTopology_setNy(PyObject *self, PyObject * args)
{
    GridTopology* obj=down_cast<GridTopology>(((PySPtr<Base>*)self)->object->toTopology());
    int nb;
    if (!PyArg_ParseTuple(args, "i",&nb))
    {
        PyErr_BadArgument();
        return NULL;
    }
    obj->setNy(nb);
    Py_RETURN_NONE;
}

extern "C" PyObject * GridTopology_getNz(PyObject *self, PyObject * /*args*/)
{
    GridTopology* obj=down_cast<GridTopology>(((PySPtr<Base>*)self)->object->toTopology());
    return PyInt_FromLong(obj->getNz());
}

extern "C" PyObject * GridTopology_setNz(PyObject *self, PyObject * args)
{
    GridTopology* obj=down_cast<GridTopology>(((PySPtr<Base>*)self)->object->toTopology());
    int nb;
    if (!PyArg_ParseTuple(args, "i",&nb))
    {
        PyErr_BadArgument();
        return NULL;
    }
    obj->setNz(nb);
    Py_RETURN_NONE;
}

SP_CLASS_METHODS_BEGIN(GridTopology)
SP_CLASS_METHOD(GridTopology,setSize)
SP_CLASS_METHOD(GridTopology,getNx)
SP_CLASS_METHOD(GridTopology,getNy)
SP_CLASS_METHOD(GridTopology,getNz)
SP_CLASS_METHOD(GridTopology,setNx)
SP_CLASS_METHOD(GridTopology,setNy)
SP_CLASS_METHOD(GridTopology,setNz)
SP_CLASS_METHODS_END

SP_CLASS_TYPE_SPTR(GridTopology,GridTopology,MeshTopology)

<|endoftext|>


<commit_before>/*
    Copyright (c) 2009 Tobias Koenig <tokoe@kde.org>

    This library is free software; you can redistribute it and/or modify it
    under the terms of the GNU Library General Public License as published by
    the Free Software Foundation; either version 2 of the License, or (at your
    option) any later version.

    This library is distributed in the hope that it will be useful, but WITHOUT
    ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Library General Public
    License for more details.

    You should have received a copy of the GNU Library General Public License
    along with this library; see the file COPYING.LIB.  If not, write to the
    Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
    02110-1301, USA.
*/

#include "contactsresource.h"

#include "settingsadaptor.h"
#include "settingsdialog.h"

#include <QtCore/QDir>
#include <QtCore/QDirIterator>
#include <QtCore/QFile>

#include <akonadi/changerecorder.h>
#include <akonadi/collectionfetchscope.h>
#include <akonadi/entitydisplayattribute.h>
#include <akonadi/itemfetchscope.h>

using namespace Akonadi;

ContactsResource::ContactsResource( const QString &id )
  : ResourceBase( id )
{
  setHierarchicalRemoteIdentifiersEnabled( true );

  // setup the resource
  new SettingsAdaptor( Settings::self() );
  QDBusConnection::sessionBus().registerObject( QLatin1String( "/Settings" ),
                            Settings::self(), QDBusConnection::ExportAdaptors );

  changeRecorder()->fetchCollection( true );
  changeRecorder()->itemFetchScope().fetchFullPayload( true );
  changeRecorder()->itemFetchScope().setAncestorRetrieval( ItemFetchScope::All );
  changeRecorder()->collectionFetchScope().setAncestorRetrieval( CollectionFetchScope::All );

  mSupportedMimeTypes << KABC::Addressee::mimeType() << KABC::ContactGroup::mimeType() << Collection::mimeType();
}

ContactsResource::~ContactsResource()
{
}

void ContactsResource::aboutToQuit()
{
}

void ContactsResource::configure( WId windowId )
{
  SettingsDialog dlg( windowId );
  if ( dlg.exec() ) {
    Settings::self()->writeConfig();

    clearCache();
    initializeDirectory( baseDirectoryPath() );

    synchronize();

    emit configurationDialogAccepted();
  } else {
    emit configurationDialogRejected();
  }
}

Collection::List ContactsResource::createCollectionsForDirectory( const QDir &parentDirectory, const Collection &parentCollection ) const
{
  Collection::List collections;

  QDir dir( parentDirectory );
  dir.setFilter( QDir::Dirs | QDir::NoDotAndDotDot | QDir::Readable );
  const QFileInfoList entries = dir.entryInfoList();

  foreach ( const QFileInfo &entry, entries ) {
    QDir subdir( entry.absoluteFilePath() );

    Collection collection;
    collection.setParentCollection( parentCollection );
    collection.setRemoteId( entry.fileName() );
    collection.setName( entry.fileName() );
    collection.setContentMimeTypes( mSupportedMimeTypes );
    collection.setRights( supportedRights() );

    collections << collection;
    collections << createCollectionsForDirectory( subdir, collection );
  }

  return collections;
}

void ContactsResource::retrieveCollections()
{
  // create the resource collection
  Collection resourceCollection;
  resourceCollection.setParentCollection( Collection::root() );
  resourceCollection.setRemoteId( baseDirectoryPath() );
  resourceCollection.setName( i18n( "Personal Contacts" ) );
  resourceCollection.setContentMimeTypes( mSupportedMimeTypes );
  resourceCollection.setRights( supportedRights() );

  const QDir baseDir( baseDirectoryPath() );

  Collection::List collections = createCollectionsForDirectory( baseDir, resourceCollection );
  collections.append( resourceCollection );

  collectionsRetrieved( collections );
}

void ContactsResource::retrieveItems( const Akonadi::Collection &collection )
{
  QDir directory( directoryForCollection( collection ) );
  if ( !directory.exists() ) {
    cancelTask( i18n( "Directory '%1' does not exists", collection.remoteId() ) );
    return;
  }

  directory.setFilter( QDir::Files | QDir::Readable );

  Item::List items;

  const QFileInfoList entries = directory.entryInfoList();

  foreach ( const QFileInfo &entry, entries ) {
    if ( entry.fileName() == "WARNING_README.txt" )
      continue;

    Item item;
    item.setRemoteId( entry.fileName() );

    if ( entry.fileName().endsWith( ".vcf" ) )
      item.setMimeType( KABC::Addressee::mimeType() );
    else if ( entry.fileName().endsWith( ".ctg" ) )
      item.setMimeType( KABC::ContactGroup::mimeType() );
    else {
      cancelTask( i18n( "Found file of unknown format: '%1'", entry.absoluteFilePath() ) );
      return;
    }

    items.append( item );
  }

  itemsRetrieved( items );
}

bool ContactsResource::retrieveItem( const Akonadi::Item &item, const QSet<QByteArray>& )
{
  const QString filePath = directoryForCollection( item.parentCollection() ) + QDir::separator() + item.remoteId();

  Item newItem( item );

  QFile file( filePath );
  if ( !file.open( QIODevice::ReadOnly ) ) {
    cancelTask( i18n( "Unable to open file '%1'", filePath ) );
    return false;
  }

  if ( filePath.endsWith( ".vcf" ) ) {
    KABC::VCardConverter converter;

    const QByteArray content = file.readAll();
    const KABC::Addressee contact = converter.parseVCard( content );
    if ( contact.isEmpty() ) {
      cancelTask( i18n( "Found invalid contact in file '%1'", filePath ) );
      return false;
    }

    newItem.setPayload<KABC::Addressee>( contact );
  } else if ( filePath.endsWith( ".ctg" ) ) {
    KABC::ContactGroup group;
    QString errorMessage;

    if ( !KABC::ContactGroupTool::convertFromXml( &file, group, &errorMessage ) ) {
      cancelTask( i18n( "Found invalid contact contact group in file '%1': %2", filePath, errorMessage ) );
      return false;
    }

    newItem.setPayload<KABC::ContactGroup>( group );
  } else {
    cancelTask( i18n( "Found file of unknown format: '%1'", filePath ) );
    return false;
  }

  file.close();

  itemRetrieved( newItem );

  return true;
}

void ContactsResource::itemAdded( const Akonadi::Item &item, const Akonadi::Collection &collection )
{
  if ( Settings::self()->readOnly() ) {
    cancelTask( i18n( "Trying to write to a read-only directory: '%1'", collection.remoteId() ) );
    return;
  }

  const QString directoryPath = directoryForCollection( collection );

  Item newItem( item );

  if ( item.hasPayload<KABC::Addressee>() ) {
    const KABC::Addressee contact = item.payload<KABC::Addressee>();

    const QString fileName = directoryPath + QDir::separator() + contact.uid() + ".vcf";

    KABC::VCardConverter converter;
    const QByteArray content = converter.createVCard( contact );

    QFile file( fileName );
    if ( !file.open( QIODevice::WriteOnly ) ) {
      cancelTask( i18n( "Unable to write to file '%1': %2", fileName, file.errorString() ) );
      return;
    }

    file.write( content );
    file.close();

    newItem.setRemoteId( contact.uid() + ".vcf" );

  } else if ( item.hasPayload<KABC::ContactGroup>() ) {
    const KABC::ContactGroup group = item.payload<KABC::ContactGroup>();

    const QString fileName = directoryPath + QDir::separator() + group.id() + ".ctg";

    QFile file( fileName );
    if ( !file.open( QIODevice::WriteOnly ) ) {
      cancelTask( i18n( "Unable to write to file '%1': %2", fileName, file.errorString() ) );
      return;
    }

    KABC::ContactGroupTool::convertToXml( group, &file );

    file.close();

    newItem.setRemoteId( group.id() + ".ctg" );

  } else {
    Q_ASSERT( false );
  }

  changeCommitted( newItem );
}

void ContactsResource::itemChanged( const Akonadi::Item &item, const QSet<QByteArray>& )
{
  if ( Settings::self()->readOnly() ) {
    cancelTask( i18n( "Trying to write to a read-only file: '%1'", item.remoteId() ) );
    return;
  }

  Item newItem( item );

  const QString fileName = directoryForCollection( item.parentCollection() ) + QDir::separator() + item.remoteId();

  if ( item.hasPayload<KABC::Addressee>() ) {
    const KABC::Addressee contact = item.payload<KABC::Addressee>();

    KABC::VCardConverter converter;
    const QByteArray content = converter.createVCard( contact );

    QFile file( fileName );
    if ( !file.open( QIODevice::WriteOnly ) ) {
      cancelTask( i18n( "Unable to write to file '%1': %2", fileName, file.errorString() ) );
      return;
    }
    file.write( content );
    file.close();

    newItem.setRemoteId( item.remoteId() );

  } else if ( item.hasPayload<KABC::ContactGroup>() ) {
    const KABC::ContactGroup group = item.payload<KABC::ContactGroup>();

    QFile file( fileName );
    if ( !file.open( QIODevice::WriteOnly ) ) {
      cancelTask( i18n( "Unable to write to file '%1': %2", fileName, file.errorString() ) );
      return;
    }

    KABC::ContactGroupTool::convertToXml( group, &file );

    file.close();

    newItem.setRemoteId( item.remoteId() );

  } else {
    cancelTask( i18n( "Received item with unknown payload %1", item.mimeType() ) );
    return;
  }

  changeCommitted( newItem );
}

void ContactsResource::itemRemoved( const Akonadi::Item &item )
{
  if ( Settings::self()->readOnly() ) {
    cancelTask( i18n( "Trying to write to a read-only file: '%1'", item.remoteId() ) );
    return;
  }

  const QString fileName = directoryForCollection( item.parentCollection() ) + QDir::separator() + item.remoteId();

  if ( !QFile::remove( fileName ) ) {
    cancelTask( i18n( "Unable to remove file '%1'", fileName ) );
    return;
  }

  changeProcessed();
}

void ContactsResource::collectionAdded( const Akonadi::Collection &collection, const Akonadi::Collection &parent )
{
  if ( Settings::self()->readOnly() ) {
    cancelTask( i18n( "Trying to write to a read-only directory: '%1'", parent.remoteId() ) );
    return;
  }

  const QString dirName = directoryForCollection( parent ) + QDir::separator() + collection.name();

  if ( !QDir::root().mkpath( dirName ) ) {
    cancelTask( i18n("Unable to create folder '%1'.", dirName ) );
    return;
  }

  initializeDirectory( dirName );

  Collection newCollection( collection );
  newCollection.setRemoteId( collection.name() );
  changeCommitted( newCollection );
}

void ContactsResource::collectionChanged( const Akonadi::Collection &collection )
{
  if ( Settings::self()->readOnly() ) {
    cancelTask( i18n( "Trying to write to a read-only directory: '%1'", collection.remoteId() ) );
    return;
  }

  if ( collection.parentCollection() == Collection::root() ) {
    if ( collection.name() != name() )
      setName( collection.name() );
    changeProcessed();
    return;
  }

  if ( collection.remoteId() == collection.name() ) {
    changeProcessed();
    return;
  }

  const QString dirName = directoryForCollection( collection );

  QFileInfo oldDirectory( dirName );
  if ( !QDir::root().rename( dirName, oldDirectory.absolutePath() + QDir::separator() + collection.name() ) ) {
    cancelTask( i18n("Unable to rename folder '%1'.", collection.name() ) );
    return;
  }

  Collection newCollection( collection );
  newCollection.setRemoteId( collection.name() );
  changeCommitted( newCollection );
}

void ContactsResource::collectionRemoved( const Akonadi::Collection &collection )
{
  if ( Settings::self()->readOnly() ) {
    cancelTask( i18n( "Trying to write to a read-only directory: '%1'", collection.remoteId() ) );
    return;
  }

  if ( !QFile::remove( directoryForCollection( collection ) ) ) {
    cancelTask( i18n("Unable to delete folder '%1'.", collection.name() ) );
    return;
  }

  changeProcessed();
}

QString ContactsResource::baseDirectoryPath() const
{
  return Settings::self()->path();
}

void ContactsResource::initializeDirectory( const QString &path ) const
{
  QDir dir( path );

  // if folder does not exists, create it
  if ( !dir.exists() )
    QDir::root().mkpath( dir.absolutePath() );

  // check whether warning file is in place...
  QFile file( dir.absolutePath() + QDir::separator() + "WARNING_README.txt" );
  if ( !file.exists() ) {
    // ... if not, create it
    file.open( QIODevice::WriteOnly );
    file.write( "Important Warning!!!\n\n"
                "Don't create or copy vCards inside this folder manually, they are managed by the Akonadi framework!\n" );
    file.close();
  }
}

Collection::Rights ContactsResource::supportedRights() const
{
  Collection::Rights rights = Collection::ReadOnly;

  if ( !Settings::self()->readOnly() ) {
    rights |= Collection::CanChangeItem;
    rights |= Collection::CanCreateItem;
    rights |= Collection::CanDeleteItem;
    rights |= Collection::CanCreateCollection;
    rights |= Collection::CanChangeCollection;
    rights |= Collection::CanDeleteCollection;
  }

  return rights;
}

QString ContactsResource::directoryForCollection( const Collection& collection ) const
{
  if ( collection.remoteId().isEmpty() ) {
    kWarning() << "Got incomplete ancestor chain:" << collection;
    return QString();
  }

  if ( collection.parentCollection() == Collection::root() ) {
    kWarning( collection.remoteId() != baseDirectoryPath() ) << "RID mismatch, is " << collection.remoteId()
                                                             << " expected " << baseDirectoryPath();
    return collection.remoteId();
  }

  const QString parentDirectory = directoryForCollection( collection.parentCollection() );
  if ( parentDirectory.isNull() ) // invalid, != isEmpty() here!
    return QString();

  QString directory = parentDirectory;
  if ( !directory.endsWith( '/' ) )
    directory += QDir::separator() + collection.remoteId();
  else
    directory += collection.remoteId();

  return directory;
}

AKONADI_RESOURCE_MAIN( ContactsResource )

#include "contactsresource.moc"
<commit_msg>Handle removal of collections correctly<commit_after>/*
    Copyright (c) 2009 Tobias Koenig <tokoe@kde.org>

    This library is free software; you can redistribute it and/or modify it
    under the terms of the GNU Library General Public License as published by
    the Free Software Foundation; either version 2 of the License, or (at your
    option) any later version.

    This library is distributed in the hope that it will be useful, but WITHOUT
    ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Library General Public
    License for more details.

    You should have received a copy of the GNU Library General Public License
    along with this library; see the file COPYING.LIB.  If not, write to the
    Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
    02110-1301, USA.
*/

#include "contactsresource.h"

#include "settingsadaptor.h"
#include "settingsdialog.h"

#include <QtCore/QDir>
#include <QtCore/QDirIterator>
#include <QtCore/QFile>

#include <akonadi/changerecorder.h>
#include <akonadi/collectionfetchscope.h>
#include <akonadi/entitydisplayattribute.h>
#include <akonadi/itemfetchscope.h>

using namespace Akonadi;

ContactsResource::ContactsResource( const QString &id )
  : ResourceBase( id )
{
  // setup the resource
  new SettingsAdaptor( Settings::self() );
  QDBusConnection::sessionBus().registerObject( QLatin1String( "/Settings" ),
                            Settings::self(), QDBusConnection::ExportAdaptors );

  changeRecorder()->fetchCollection( true );
  changeRecorder()->itemFetchScope().fetchFullPayload( true );
  changeRecorder()->itemFetchScope().setAncestorRetrieval( ItemFetchScope::All );
  changeRecorder()->collectionFetchScope().setAncestorRetrieval( CollectionFetchScope::All );

  setHierarchicalRemoteIdentifiersEnabled( true );

  mSupportedMimeTypes << KABC::Addressee::mimeType() << KABC::ContactGroup::mimeType() << Collection::mimeType();
}

ContactsResource::~ContactsResource()
{
}

void ContactsResource::aboutToQuit()
{
}

void ContactsResource::configure( WId windowId )
{
  SettingsDialog dlg( windowId );
  if ( dlg.exec() ) {
    Settings::self()->writeConfig();

    clearCache();
    initializeDirectory( baseDirectoryPath() );

    synchronize();

    emit configurationDialogAccepted();
  } else {
    emit configurationDialogRejected();
  }
}

Collection::List ContactsResource::createCollectionsForDirectory( const QDir &parentDirectory, const Collection &parentCollection ) const
{
  Collection::List collections;

  QDir dir( parentDirectory );
  dir.setFilter( QDir::Dirs | QDir::NoDotAndDotDot | QDir::Readable );
  const QFileInfoList entries = dir.entryInfoList();

  foreach ( const QFileInfo &entry, entries ) {
    QDir subdir( entry.absoluteFilePath() );

    Collection collection;
    collection.setParentCollection( parentCollection );
    collection.setRemoteId( entry.fileName() );
    collection.setName( entry.fileName() );
    collection.setContentMimeTypes( mSupportedMimeTypes );
    collection.setRights( supportedRights() );

    collections << collection;
    collections << createCollectionsForDirectory( subdir, collection );
  }

  return collections;
}

void ContactsResource::retrieveCollections()
{
  // create the resource collection
  Collection resourceCollection;
  resourceCollection.setParentCollection( Collection::root() );
  resourceCollection.setRemoteId( baseDirectoryPath() );
  resourceCollection.setName( i18n( "Personal Contacts" ) );
  resourceCollection.setContentMimeTypes( mSupportedMimeTypes );
  resourceCollection.setRights( supportedRights() );

  const QDir baseDir( baseDirectoryPath() );

  Collection::List collections = createCollectionsForDirectory( baseDir, resourceCollection );
  collections.append( resourceCollection );

  collectionsRetrieved( collections );
}

void ContactsResource::retrieveItems( const Akonadi::Collection &collection )
{
  QDir directory( directoryForCollection( collection ) );
  if ( !directory.exists() ) {
    cancelTask( i18n( "Directory '%1' does not exists", collection.remoteId() ) );
    return;
  }

  directory.setFilter( QDir::Files | QDir::Readable );

  Item::List items;

  const QFileInfoList entries = directory.entryInfoList();

  foreach ( const QFileInfo &entry, entries ) {
    if ( entry.fileName() == "WARNING_README.txt" )
      continue;

    Item item;
    item.setRemoteId( entry.fileName() );

    if ( entry.fileName().endsWith( ".vcf" ) )
      item.setMimeType( KABC::Addressee::mimeType() );
    else if ( entry.fileName().endsWith( ".ctg" ) )
      item.setMimeType( KABC::ContactGroup::mimeType() );
    else {
      cancelTask( i18n( "Found file of unknown format: '%1'", entry.absoluteFilePath() ) );
      return;
    }

    items.append( item );
  }

  itemsRetrieved( items );
}

bool ContactsResource::retrieveItem( const Akonadi::Item &item, const QSet<QByteArray>& )
{
  const QString filePath = directoryForCollection( item.parentCollection() ) + QDir::separator() + item.remoteId();

  Item newItem( item );

  QFile file( filePath );
  if ( !file.open( QIODevice::ReadOnly ) ) {
    cancelTask( i18n( "Unable to open file '%1'", filePath ) );
    return false;
  }

  if ( filePath.endsWith( ".vcf" ) ) {
    KABC::VCardConverter converter;

    const QByteArray content = file.readAll();
    const KABC::Addressee contact = converter.parseVCard( content );
    if ( contact.isEmpty() ) {
      cancelTask( i18n( "Found invalid contact in file '%1'", filePath ) );
      return false;
    }

    newItem.setPayload<KABC::Addressee>( contact );
  } else if ( filePath.endsWith( ".ctg" ) ) {
    KABC::ContactGroup group;
    QString errorMessage;

    if ( !KABC::ContactGroupTool::convertFromXml( &file, group, &errorMessage ) ) {
      cancelTask( i18n( "Found invalid contact contact group in file '%1': %2", filePath, errorMessage ) );
      return false;
    }

    newItem.setPayload<KABC::ContactGroup>( group );
  } else {
    cancelTask( i18n( "Found file of unknown format: '%1'", filePath ) );
    return false;
  }

  file.close();

  itemRetrieved( newItem );

  return true;
}

void ContactsResource::itemAdded( const Akonadi::Item &item, const Akonadi::Collection &collection )
{
  if ( Settings::self()->readOnly() ) {
    cancelTask( i18n( "Trying to write to a read-only directory: '%1'", collection.remoteId() ) );
    return;
  }

  const QString directoryPath = directoryForCollection( collection );

  Item newItem( item );

  if ( item.hasPayload<KABC::Addressee>() ) {
    const KABC::Addressee contact = item.payload<KABC::Addressee>();

    const QString fileName = directoryPath + QDir::separator() + contact.uid() + ".vcf";

    KABC::VCardConverter converter;
    const QByteArray content = converter.createVCard( contact );

    QFile file( fileName );
    if ( !file.open( QIODevice::WriteOnly ) ) {
      cancelTask( i18n( "Unable to write to file '%1': %2", fileName, file.errorString() ) );
      return;
    }

    file.write( content );
    file.close();

    newItem.setRemoteId( contact.uid() + ".vcf" );

  } else if ( item.hasPayload<KABC::ContactGroup>() ) {
    const KABC::ContactGroup group = item.payload<KABC::ContactGroup>();

    const QString fileName = directoryPath + QDir::separator() + group.id() + ".ctg";

    QFile file( fileName );
    if ( !file.open( QIODevice::WriteOnly ) ) {
      cancelTask( i18n( "Unable to write to file '%1': %2", fileName, file.errorString() ) );
      return;
    }

    KABC::ContactGroupTool::convertToXml( group, &file );

    file.close();

    newItem.setRemoteId( group.id() + ".ctg" );

  } else {
    Q_ASSERT( false );
  }

  changeCommitted( newItem );
}

void ContactsResource::itemChanged( const Akonadi::Item &item, const QSet<QByteArray>& )
{
  if ( Settings::self()->readOnly() ) {
    cancelTask( i18n( "Trying to write to a read-only file: '%1'", item.remoteId() ) );
    return;
  }

  Item newItem( item );

  const QString fileName = directoryForCollection( item.parentCollection() ) + QDir::separator() + item.remoteId();

  if ( item.hasPayload<KABC::Addressee>() ) {
    const KABC::Addressee contact = item.payload<KABC::Addressee>();

    KABC::VCardConverter converter;
    const QByteArray content = converter.createVCard( contact );

    QFile file( fileName );
    if ( !file.open( QIODevice::WriteOnly ) ) {
      cancelTask( i18n( "Unable to write to file '%1': %2", fileName, file.errorString() ) );
      return;
    }
    file.write( content );
    file.close();

    newItem.setRemoteId( item.remoteId() );

  } else if ( item.hasPayload<KABC::ContactGroup>() ) {
    const KABC::ContactGroup group = item.payload<KABC::ContactGroup>();

    QFile file( fileName );
    if ( !file.open( QIODevice::WriteOnly ) ) {
      cancelTask( i18n( "Unable to write to file '%1': %2", fileName, file.errorString() ) );
      return;
    }

    KABC::ContactGroupTool::convertToXml( group, &file );

    file.close();

    newItem.setRemoteId( item.remoteId() );

  } else {
    cancelTask( i18n( "Received item with unknown payload %1", item.mimeType() ) );
    return;
  }

  changeCommitted( newItem );
}

void ContactsResource::itemRemoved( const Akonadi::Item &item )
{
  if ( Settings::self()->readOnly() ) {
    cancelTask( i18n( "Trying to write to a read-only file: '%1'", item.remoteId() ) );
    return;
  }

  // If the parent collection has no valid remote id, the parent
  // collection will be removed in a second, so stop here and remove
  // all items in collectionRemoved().
  if ( item.parentCollection().remoteId().isEmpty() ) {
    changeProcessed();
    return;
  }

  const QString fileName = directoryForCollection( item.parentCollection() ) + QDir::separator() + item.remoteId();

  if ( !QFile::remove( fileName ) ) {
    cancelTask( i18n( "Unable to remove file '%1'", fileName ) );
    return;
  }

  changeProcessed();
}

void ContactsResource::collectionAdded( const Akonadi::Collection &collection, const Akonadi::Collection &parent )
{
  if ( Settings::self()->readOnly() ) {
    cancelTask( i18n( "Trying to write to a read-only directory: '%1'", parent.remoteId() ) );
    return;
  }

  const QString dirName = directoryForCollection( parent ) + QDir::separator() + collection.name();

  if ( !QDir::root().mkpath( dirName ) ) {
    cancelTask( i18n("Unable to create folder '%1'.", dirName ) );
    return;
  }

  initializeDirectory( dirName );

  Collection newCollection( collection );
  newCollection.setRemoteId( collection.name() );
  changeCommitted( newCollection );
}

void ContactsResource::collectionChanged( const Akonadi::Collection &collection )
{
  if ( Settings::self()->readOnly() ) {
    cancelTask( i18n( "Trying to write to a read-only directory: '%1'", collection.remoteId() ) );
    return;
  }

  if ( collection.parentCollection() == Collection::root() ) {
    if ( collection.name() != name() )
      setName( collection.name() );
    changeProcessed();
    return;
  }

  if ( collection.remoteId() == collection.name() ) {
    changeProcessed();
    return;
  }

  const QString dirName = directoryForCollection( collection );

  QFileInfo oldDirectory( dirName );
  if ( !QDir::root().rename( dirName, oldDirectory.absolutePath() + QDir::separator() + collection.name() ) ) {
    cancelTask( i18n("Unable to rename folder '%1'.", collection.name() ) );
    return;
  }

  Collection newCollection( collection );
  newCollection.setRemoteId( collection.name() );
  changeCommitted( newCollection );
}

/**
 * Removes a @p directory recursively.
 */
static bool removeDirectory( const QDir &directory )
{
  const QFileInfoList infos = directory.entryInfoList( QDir::Files|QDir::Dirs|QDir::NoDotAndDotDot );
  foreach ( const QFileInfo &info, infos ) {
    if ( info.isDir() ) {
      if ( !removeDirectory( QDir( info.absoluteFilePath() ) ) )
        return false;
    } else {
      if ( !QFile::remove( info.filePath() ) )
        return false;
    }
  }

  if ( !QDir::root().rmdir( directory.absolutePath() ) )
    return false;

  return true;
}

void ContactsResource::collectionRemoved( const Akonadi::Collection &collection )
{
  if ( Settings::self()->readOnly() ) {
    cancelTask( i18n( "Trying to write to a read-only directory: '%1'", collection.remoteId() ) );
    return;
  }

  if ( !removeDirectory( directoryForCollection( collection ) ) ) {
    cancelTask( i18n("Unable to delete folder '%1'.", collection.name() ) );
    return;
  }

  changeProcessed();
}

QString ContactsResource::baseDirectoryPath() const
{
  return Settings::self()->path();
}

void ContactsResource::initializeDirectory( const QString &path ) const
{
  QDir dir( path );

  // if folder does not exists, create it
  if ( !dir.exists() )
    QDir::root().mkpath( dir.absolutePath() );

  // check whether warning file is in place...
  QFile file( dir.absolutePath() + QDir::separator() + "WARNING_README.txt" );
  if ( !file.exists() ) {
    // ... if not, create it
    file.open( QIODevice::WriteOnly );
    file.write( "Important Warning!!!\n\n"
                "Don't create or copy vCards inside this folder manually, they are managed by the Akonadi framework!\n" );
    file.close();
  }
}

Collection::Rights ContactsResource::supportedRights() const
{
  Collection::Rights rights = Collection::ReadOnly;

  if ( !Settings::self()->readOnly() ) {
    rights |= Collection::CanChangeItem;
    rights |= Collection::CanCreateItem;
    rights |= Collection::CanDeleteItem;
    rights |= Collection::CanCreateCollection;
    rights |= Collection::CanChangeCollection;
    rights |= Collection::CanDeleteCollection;
  }

  return rights;
}

QString ContactsResource::directoryForCollection( const Collection& collection ) const
{
  if ( collection.remoteId().isEmpty() ) {
    kWarning() << "Got incomplete ancestor chain:" << collection;
    return QString();
  }

  if ( collection.parentCollection() == Collection::root() ) {
    kWarning( collection.remoteId() != baseDirectoryPath() ) << "RID mismatch, is " << collection.remoteId()
                                                             << " expected " << baseDirectoryPath();
    return collection.remoteId();
  }

  const QString parentDirectory = directoryForCollection( collection.parentCollection() );
  if ( parentDirectory.isNull() ) // invalid, != isEmpty() here!
    return QString();

  QString directory = parentDirectory;
  if ( !directory.endsWith( '/' ) )
    directory += QDir::separator() + collection.remoteId();
  else
    directory += collection.remoteId();

  return directory;
}

AKONADI_RESOURCE_MAIN( ContactsResource )

#include "contactsresource.moc"
<|endoftext|>


<commit_before>// RUN: %clang_cc1 -triple i386-apple-darwin9 -analyze -analyzer-experimental-internal-checks -checker-cfref -analyzer-store=region -verify -fblocks -analyzer-opt-analyze-nested-blocks %s
// RUN: %clang_cc1 -triple x86_64-apple-darwin9 -analyze -analyzer-experimental-internal-checks -checker-cfref -analyzer-store=region -verify -fblocks   -analyzer-opt-analyze-nested-blocks %s

// Test basic handling of references.
char &test1_aux();
char *test1() {
  return &test1_aux();
}

// Test test1_aux() evaluates to char &.
char test1_as_rvalue() {
  return test1_aux();
}

// Test passing a value as a reference.  The 'const' in test2_aux() adds
// an ImplicitCastExpr, which is evaluated as an lvalue.
int test2_aux(const int &n);
int test2(int n) {
  return test2_aux(n);
}

int test2_b_aux(const short &n);
int test2_b(int n) {
  return test2_b_aux(n);
}

// Test getting the lvalue of a derived and converting it to a base.  This
// previously crashed.
class Test3_Base {};
class Test3_Derived : public Test3_Base {};

int test3_aux(Test3_Base &x);
int test3(Test3_Derived x) {
  return test3_aux(x);
}

int test_init_in_condition_aux();
int test_init_in_condition() {
  if (int x = test_init_in_condition_aux()) { // no-warning
    return 1;
  }
  return 0;
}

int test_init_in_condition_switch() {
  switch (int x = test_init_in_condition_aux()) { // no-warning
    case 1:
      return 0;
    case 2:
      if (x == 2)
        return 0;
      else {
        // Unreachable.
        int *p = 0;
        *p = 0xDEADBEEF; // no-warning
      }
    default:
      break;
  }
  return 0;
}

int test_init_in_condition_while() {
  int z = 0;
  while (int x = ++z) { // no-warning
    if (x == 2)
      break;
  }

  if (z == 2)
    return 0;

  int *p = 0;
  *p = 0xDEADBEEF; // no-warning
  return 0;
}

<commit_msg>Add analyzer test case for 'ForStmt' with condition variable.<commit_after>// RUN: %clang_cc1 -triple i386-apple-darwin9 -analyze -analyzer-experimental-internal-checks -checker-cfref -analyzer-store=region -verify -fblocks -analyzer-opt-analyze-nested-blocks %s
// RUN: %clang_cc1 -triple x86_64-apple-darwin9 -analyze -analyzer-experimental-internal-checks -checker-cfref -analyzer-store=region -verify -fblocks   -analyzer-opt-analyze-nested-blocks %s

// Test basic handling of references.
char &test1_aux();
char *test1() {
  return &test1_aux();
}

// Test test1_aux() evaluates to char &.
char test1_as_rvalue() {
  return test1_aux();
}

// Test passing a value as a reference.  The 'const' in test2_aux() adds
// an ImplicitCastExpr, which is evaluated as an lvalue.
int test2_aux(const int &n);
int test2(int n) {
  return test2_aux(n);
}

int test2_b_aux(const short &n);
int test2_b(int n) {
  return test2_b_aux(n);
}

// Test getting the lvalue of a derived and converting it to a base.  This
// previously crashed.
class Test3_Base {};
class Test3_Derived : public Test3_Base {};

int test3_aux(Test3_Base &x);
int test3(Test3_Derived x) {
  return test3_aux(x);
}

int test_init_in_condition_aux();
int test_init_in_condition() {
  if (int x = test_init_in_condition_aux()) { // no-warning
    return 1;
  }
  return 0;
}

int test_init_in_condition_switch() {
  switch (int x = test_init_in_condition_aux()) { // no-warning
    case 1:
      return 0;
    case 2:
      if (x == 2)
        return 0;
      else {
        // Unreachable.
        int *p = 0;
        *p = 0xDEADBEEF; // no-warning
      }
    default:
      break;
  }
  return 0;
}

int test_init_in_condition_while() {
  int z = 0;
  while (int x = ++z) { // no-warning
    if (x == 2)
      break;
  }

  if (z == 2)
    return 0;

  int *p = 0;
  *p = 0xDEADBEEF; // no-warning
  return 0;
}

int test_init_in_condition_for() {
  int z = 0;
  for (int x = 0; int y = ++z; ++x) {
    if (x == y) // no-warning
      break;
  }
  if (z == 1)
    return 0;

  int *p = 0;
  *p = 0xDEADBEEF; // no-warning
  return 0;
}
<|endoftext|>


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

#ifndef _XMLOFF_XMLBASICEXPORTFILTER_HXX
#include "XMLBasicExportFilter.hxx"
#endif

using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;

// =============================================================================
// XMLBasicExportFilter
// =============================================================================

XMLBasicExportFilter::XMLBasicExportFilter( const Reference< xml::sax::XDocumentHandler >& rxHandler )
    :m_xHandler( rxHandler )
{
}

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

XMLBasicExportFilter::~XMLBasicExportFilter()
{
}

// -----------------------------------------------------------------------------
// XDocumentHandler
// -----------------------------------------------------------------------------

void XMLBasicExportFilter::startDocument()
    throw (xml::sax::SAXException, RuntimeException)
{
    // do nothing, filter this
}

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

void XMLBasicExportFilter::endDocument()
    throw (xml::sax::SAXException, RuntimeException)
{
    // do nothing, filter this
}

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

void XMLBasicExportFilter::startElement( const ::rtl::OUString& aName,
        const Reference< xml::sax::XAttributeList >& xAttribs )
    throw (xml::sax::SAXException, RuntimeException)
{
    if ( m_xHandler.is() )
        m_xHandler->startElement( aName, xAttribs );
}

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

void XMLBasicExportFilter::endElement( const ::rtl::OUString& aName )
    throw (xml::sax::SAXException, RuntimeException)
{
    if ( m_xHandler.is() )
        m_xHandler->endElement( aName );
}

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

void XMLBasicExportFilter::characters( const ::rtl::OUString& aChars )
    throw (xml::sax::SAXException, RuntimeException)
{
    if ( m_xHandler.is() )
        m_xHandler->characters( aChars );
}

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

void XMLBasicExportFilter::ignorableWhitespace( const ::rtl::OUString& aWhitespaces )
    throw (xml::sax::SAXException, RuntimeException)
{
    if ( m_xHandler.is() )
        m_xHandler->ignorableWhitespace( aWhitespaces );
}

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

void XMLBasicExportFilter::processingInstruction( const ::rtl::OUString& aTarget,
        const ::rtl::OUString& aData )
    throw (xml::sax::SAXException, RuntimeException)
{
    if ( m_xHandler.is() )
        m_xHandler->processingInstruction( aTarget, aData );
}

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

void XMLBasicExportFilter::setDocumentLocator( const Reference< xml::sax::XLocator >& xLocator )
    throw (xml::sax::SAXException, RuntimeException)
{
    if ( m_xHandler.is() )
        m_xHandler->setDocumentLocator( xLocator );
}

// -----------------------------------------------------------------------------
<commit_msg>INTEGRATION: CWS pchfix02 (1.3.160); FILE MERGED 2006/09/01 17:59:27 kaib 1.3.160.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: XMLBasicExportFilter.cxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-17 10:19:49 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_xmloff.hxx"

#ifndef _XMLOFF_XMLBASICEXPORTFILTER_HXX
#include "XMLBasicExportFilter.hxx"
#endif

using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;

// =============================================================================
// XMLBasicExportFilter
// =============================================================================

XMLBasicExportFilter::XMLBasicExportFilter( const Reference< xml::sax::XDocumentHandler >& rxHandler )
    :m_xHandler( rxHandler )
{
}

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

XMLBasicExportFilter::~XMLBasicExportFilter()
{
}

// -----------------------------------------------------------------------------
// XDocumentHandler
// -----------------------------------------------------------------------------

void XMLBasicExportFilter::startDocument()
    throw (xml::sax::SAXException, RuntimeException)
{
    // do nothing, filter this
}

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

void XMLBasicExportFilter::endDocument()
    throw (xml::sax::SAXException, RuntimeException)
{
    // do nothing, filter this
}

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

void XMLBasicExportFilter::startElement( const ::rtl::OUString& aName,
        const Reference< xml::sax::XAttributeList >& xAttribs )
    throw (xml::sax::SAXException, RuntimeException)
{
    if ( m_xHandler.is() )
        m_xHandler->startElement( aName, xAttribs );
}

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

void XMLBasicExportFilter::endElement( const ::rtl::OUString& aName )
    throw (xml::sax::SAXException, RuntimeException)
{
    if ( m_xHandler.is() )
        m_xHandler->endElement( aName );
}

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

void XMLBasicExportFilter::characters( const ::rtl::OUString& aChars )
    throw (xml::sax::SAXException, RuntimeException)
{
    if ( m_xHandler.is() )
        m_xHandler->characters( aChars );
}

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

void XMLBasicExportFilter::ignorableWhitespace( const ::rtl::OUString& aWhitespaces )
    throw (xml::sax::SAXException, RuntimeException)
{
    if ( m_xHandler.is() )
        m_xHandler->ignorableWhitespace( aWhitespaces );
}

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

void XMLBasicExportFilter::processingInstruction( const ::rtl::OUString& aTarget,
        const ::rtl::OUString& aData )
    throw (xml::sax::SAXException, RuntimeException)
{
    if ( m_xHandler.is() )
        m_xHandler->processingInstruction( aTarget, aData );
}

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

void XMLBasicExportFilter::setDocumentLocator( const Reference< xml::sax::XLocator >& xLocator )
    throw (xml::sax::SAXException, RuntimeException)
{
    if ( m_xHandler.is() )
        m_xHandler->setDocumentLocator( xLocator );
}

// -----------------------------------------------------------------------------
<|endoftext|>


<commit_before>// RUN: %clang_cc1 %s -fsyntax-only -verify

// PR11179
template <short T> class Type1 {};
template <short T> void Function1(Type1<T>& x) {} // expected-note{{candidate function [with T = -42] not viable: no known conversion from 'Type1<-42>' to 'Type1<-42> &' for 1st argument;}}

template <unsigned short T> class Type2 {};
template <unsigned short T> void Function2(Type2<T>& x) {} // expected-note{{candidate function [with T = 42] not viable: no known conversion from 'Type2<42>' to 'Type2<42> &' for 1st argument;}}

template <__int128_t T> class Type3 {};
template <__int128_t T> void Function3(Type3<T>& x) {} // expected-note{{candidate function [with T = -42] not viable: no known conversion from 'Type3<-42>' to 'Type3<-42i128> &' for 1st argument;}}

template <__uint128_t T> class Type4 {};
template <__uint128_t T> void Function4(Type4<T>& x) {} // expected-note{{candidate function [with T = 42] not viable: no known conversion from 'Type4<42>' to 'Type4<42Ui128> &' for 1st argument;}}

void Function() {
  Function1(Type1<-42>()); // expected-error{{no matching function for call to 'Function1'}}
  Function2(Type2<42>()); // expected-error{{no matching function for call to 'Function2'}}
  Function3(Type3<-42>()); // expected-error{{no matching function for call to 'Function3'}}
  Function4(Type4<42>()); // expected-error{{no matching function for call to 'Function4'}}
}
<commit_msg>Remove test with int128 printing since it breaks on some platforms.<commit_after>// RUN: %clang_cc1 %s -fsyntax-only -verify

// PR11179
template <short T> class Type1 {};
template <short T> void Function1(Type1<T>& x) {} // expected-note{{candidate function [with T = -42] not viable: no known conversion from 'Type1<-42>' to 'Type1<-42> &' for 1st argument;}}

template <unsigned short T> class Type2 {};
template <unsigned short T> void Function2(Type2<T>& x) {} // expected-note{{candidate function [with T = 42] not viable: no known conversion from 'Type2<42>' to 'Type2<42> &' for 1st argument;}}

void Function() {
  Function1(Type1<-42>()); // expected-error{{no matching function for call to 'Function1'}}
  Function2(Type2<42>()); // expected-error{{no matching function for call to 'Function2'}}
}
<|endoftext|>