<commit_before>/*
** transport-client.cpp
** Login : <hcuche@hcuche-de>
** Started on  Thu Jan  5 15:21:13 2012 Herve Cuche
** $Id$
**
** Author(s):
**  - Herve Cuche <hcuche@aldebaran-robotics.com>
**
** Copyright (C) 2012 Herve Cuche
*/

#include <iostream>
#include <cstring>
#include <map>
#include <stdint.h>

#include <qi/log.hpp>

#include <event2/util.h>
#include <event2/event.h>
#include <event2/buffer.h>
#include <event2/bufferevent.h>
#include <boost/thread.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>

#include <qimessaging/transport_socket.hpp>
#include "src/network_thread.hpp"
#include "src/message_p.hpp"
#include "src/buffer_p.hpp"

#include <qimessaging/session.hpp>
#include <qimessaging/message.hpp>
#include <qimessaging/datastream.hpp>
#include <qimessaging/buffer.hpp>
#include "src/session_p.hpp"

#define MAX_LINE 16384

namespace qi {

class TransportSocketPrivate
{
public:
  explicit TransportSocketPrivate(TransportSocket *socket)
    : tcd(NULL)
    , bev(NULL)
    , connected(false)
    , fd(-1)
    , readHdr(true)
    , msg(0)
    , _self(socket)
  {
  }

  TransportSocketPrivate(TransportSocket *socket, int fileDesc)
    : tcd(NULL)
    , bev(NULL)
    , connected(false)
    , fd(fileDesc)
    , readHdr(true)
    , msg(0)
    , _self(socket)
  {
  }

  ~TransportSocketPrivate()
  {
  }

  static void onBufferSent(const void *data, size_t datalen, void *buffer)
  {
    Buffer *b = static_cast<Buffer *>(buffer);
    delete b;
  }

  static void onMessageSent(const void *data, size_t datalen, void *msg)
  {
    Message *m = static_cast<Message *>(msg);
    delete m;
  }

  TransportSocketInterface            *tcd;
  struct bufferevent                  *bev;
  bool                                 connected;
  std::map<unsigned int, qi::Message*> msgSend;
  boost::mutex                         mtx;
  boost::condition_variable            cond;
  int                                  fd;
  void readcb(struct bufferevent *bev , void *context);
  void writecb(struct bufferevent* bev, void* context);
  void eventcb(struct bufferevent *bev, short error, void *context);

  // data to rebuild message
  bool                         readHdr;
  qi::Message                 *msg;
  qi::TransportSocket         *_self;
};

static void readcb(struct bufferevent *bev,
                   void *context)
{
  TransportSocketPrivate *tc = static_cast<TransportSocketPrivate*>(context);
  tc->readcb(bev, context);
}

static void writecb(struct bufferevent* bev,
                    void* context)
{
  TransportSocketPrivate *tc = static_cast<TransportSocketPrivate*>(context);
  tc->writecb(bev, context);
}

static void eventcb(struct bufferevent *bev,
                    short error,
                    void *context)
{
  TransportSocketPrivate *tc = static_cast<TransportSocketPrivate*>(context);
  tc->eventcb(bev, error, context);
}

void TransportSocketPrivate::readcb(struct bufferevent *bev,
                             void *context)
{
  struct evbuffer *input = bufferevent_get_input(bev);

  while (true)
  {
    if (msg == NULL)
    {
      msg = new qi::Message();
      readHdr = true;
    }

    if (readHdr)
    {
      if (evbuffer_get_length(input) < sizeof(MessagePrivate::MessageHeader))
        return;

      evbuffer_remove(input,
                      msg->_p->getHeader(),
                      sizeof(MessagePrivate::MessageHeader));
      readHdr = false;
    }

    if (evbuffer_get_length(input) <
          static_cast<MessagePrivate::MessageHeader*>(msg->_p->getHeader())->size)
      return;

    /* we have to let the Buffer know we are going to push some data inside */
    qi::Buffer buf;
    buf.reserve(static_cast<MessagePrivate::MessageHeader*>(msg->_p->getHeader())->size);
    msg->setBuffer(buf);

    evbuffer_remove(input,
                    buf.data(),
                    buf.size());
    assert(msg->isValid());

    {
      boost::mutex::scoped_lock l(mtx);
      msgSend[msg->id()] = msg;
      cond.notify_all();
    }
    if (tcd)
      tcd->onSocketReadyRead(_self, msg->id());

    msg = NULL;
  }
}

void TransportSocketPrivate::writecb(struct bufferevent* bev,
                              void* context)
{
  if (tcd)
    tcd->onSocketWriteDone(_self);
}

void TransportSocketPrivate::eventcb(struct bufferevent *bev,
                              short events,
                              void *context)
{
  if (events & BEV_EVENT_CONNECTED)
  {
    connected = true;
    if (tcd)
      tcd->onSocketConnected(_self);
  }
  else if (events & BEV_EVENT_EOF)
  {
    bufferevent_free(bev);
    bev = 0;
    connected = false;
    //for waitForId
    cond.notify_all();
    if (tcd)
      tcd->onSocketDisconnected(_self);
    // connection has been closed, do any clean up here
  }
  else if (events & BEV_EVENT_ERROR)
  {
    bufferevent_free(bev);
    bev = 0;
    connected = false;
    //for waitForId
    cond.notify_all();
    if (tcd)
      tcd->onSocketConnectionError(_self);
    // check errno to see what error occurred
    qiLogError("qimessaging.TransportSocket")  << "Cannnot connect" << std::endl;
  }
  else if (events & BEV_EVENT_TIMEOUT)
  {
    // must be a timeout event handle, handle it
    qiLogError("qimessaging.TransportSocket")  << "must be a timeout event handle, handle it" << std::endl;
  }
}

TransportSocketInterface::~TransportSocketInterface() {
}

TransportSocket::TransportSocket()
  :_p(new TransportSocketPrivate(this))
{

}

TransportSocket::TransportSocket(int fd, void *data)
  :_p(new TransportSocketPrivate(this, fd))
{
  struct event_base *base = static_cast<event_base *>(data);
  _p->bev = bufferevent_socket_new(base, _p->fd, BEV_OPT_CLOSE_ON_FREE);
  bufferevent_setcb(_p->bev, ::qi::readcb, ::qi::writecb, ::qi::eventcb, _p);
  bufferevent_setwatermark(_p->bev, EV_WRITE, 0, MAX_LINE);
  bufferevent_enable(_p->bev, EV_READ|EV_WRITE);
  _p->connected = true;
}

TransportSocket::~TransportSocket()
{
  if (isConnected())
  {
    disconnect();
  }
  delete _p;
}

bool TransportSocket::connect(qi::Session *session,
                              const qi::Url &url)
{
  const std::string &address = url.host();
  unsigned short port = url.port();

  if (!isConnected())
  {
    _p->bev = bufferevent_socket_new(session->_p->_networkThread->getEventBase(), -1, BEV_OPT_CLOSE_ON_FREE);
    bufferevent_setcb(_p->bev, ::qi::readcb, ::qi::writecb, ::qi::eventcb, _p);
    bufferevent_setwatermark(_p->bev, EV_WRITE, 0, MAX_LINE);
    bufferevent_enable(_p->bev, EV_READ|EV_WRITE);

    int result = bufferevent_socket_connect_hostname(_p->bev, NULL, AF_INET, address.c_str(), port);
    if (result == 0)
    {
      _p->connected = true;
      return true;
    }
  }
  else
  {
    qiLogError("qimessaging.TransportSocket") << "socket is already connected.";
  }

  return false;
}

bool TransportSocket::waitForConnected(int msecs)
{
  // no timeout
  if (msecs < 0)
  {
    while (!_p->connected)
      ;

    return true;
  }

  while (!_p->connected && msecs > 0)
  {
    qi::os::msleep(1);
    msecs--;
  }

  // timeout
  if (msecs == 0)
    return false;

  return true;
}

void TransportSocket::disconnect()
{
  if (isConnected())
  {
    bufferevent_free(_p->bev);
    _p->bev = NULL;
    _p->connected = false;
  }
  else
  {
    qiLogError("qimessaging.TransportSocket") << "socket is not connected.";
  }
}

bool TransportSocket::waitForDisconnected(int msecs)
{
  // no timeout
  if (msecs < 0)
  {
    while (_p->connected)
      ;

    return true;
  }

  while (_p->connected && msecs > 0)
  {
    qi::os::msleep(1);
    msecs--;
  }

  // timeout
  if (msecs == 0)
    return false;

  return true;
}

bool TransportSocket::waitForId(int id, int msecs)
{
  std::map<unsigned int, qi::Message*>::iterator it;
  {
    {
      boost::mutex::scoped_lock l(_p->mtx);
      it = _p->msgSend.find(id);
      if (it != _p->msgSend.end())
        return true;
      if (!_p->connected)
        return false;
      if (msecs > 0)
        _p->cond.timed_wait(l, boost::posix_time::milliseconds(msecs));
      else
        _p->cond.wait(l);
      it = _p->msgSend.find(id);
      if (it != _p->msgSend.end())
        return true;
    }
  }
  return false;
}

bool TransportSocket::read(int id, qi::Message *msg)
{
  if (!isConnected())
  {
    qiLogError("qimessaging.TransportSocket") << "socket is not connected.";
    return false;
  }

  std::map<unsigned int, qi::Message*>::iterator it;
  {
    boost::mutex::scoped_lock l(_p->mtx);
    it = _p->msgSend.find(id);
    if (it != _p->msgSend.end())
    {
      *msg = *it->second;
      delete it->second;
      _p->msgSend.erase(it);
      return true;
    }
  }

  qiLogError("qimessaging.TransportSocket") << "message #" << id
                                            << " could not be found.";

  return false;
}

bool TransportSocket::send(const qi::Message &msg)
{
  if (!isConnected())
  {
    qiLogError("qimessaging.TransportSocket") << "socket is not connected.";
    return false;
  }

  qi::Message *m = new qi::Message();
  *m = msg;
  m->_p->complete();
  assert(m->isValid());

  struct evbuffer *evb = bufferevent_get_output(_p->bev);

  // m might be deleted.
  qi::Buffer *b = new qi::Buffer(m->buffer());

  if (evbuffer_add_reference(evb,
                             m->_p->getHeader(),
                             sizeof(qi::MessagePrivate::MessageHeader),
                             qi::TransportSocketPrivate::onMessageSent,
                             static_cast<void *>(m)) != 0)
  {
    return false;
  }

  if (b->size() &&
      evbuffer_add_reference(evb,
                             b->data(),
                             b->size(),
                             qi::TransportSocketPrivate::onBufferSent,
                             static_cast<void *>(b)) != 0)
  {
    return false;
  }

  if (bufferevent_write_buffer(_p->bev, evb) != 0)
  {
    return false;
  }

  return true;
}

void TransportSocket::setCallbacks(TransportSocketInterface *delegate)
{
  _p->tcd = delegate;
}

bool TransportSocket::isConnected()
{
  return _p->connected;
}

}

<commit_msg>Handle unused parameters.<commit_after>/*
** transport-client.cpp
** Login : <hcuche@hcuche-de>
** Started on  Thu Jan  5 15:21:13 2012 Herve Cuche
** $Id$
**
** Author(s):
**  - Herve Cuche <hcuche@aldebaran-robotics.com>
**
** Copyright (C) 2012 Herve Cuche
*/

#include <iostream>
#include <cstring>
#include <map>
#include <stdint.h>

#include <qi/log.hpp>

#include <event2/util.h>
#include <event2/event.h>
#include <event2/buffer.h>
#include <event2/bufferevent.h>
#include <boost/thread.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>

#include <qimessaging/transport_socket.hpp>
#include "src/network_thread.hpp"
#include "src/message_p.hpp"
#include "src/buffer_p.hpp"

#include <qimessaging/session.hpp>
#include <qimessaging/message.hpp>
#include <qimessaging/datastream.hpp>
#include <qimessaging/buffer.hpp>
#include "src/session_p.hpp"

#define MAX_LINE 16384

namespace qi {

class TransportSocketPrivate
{
public:
  explicit TransportSocketPrivate(TransportSocket *socket)
    : tcd(NULL)
    , bev(NULL)
    , connected(false)
    , fd(-1)
    , readHdr(true)
    , msg(0)
    , _self(socket)
  {
  }

  TransportSocketPrivate(TransportSocket *socket, int fileDesc)
    : tcd(NULL)
    , bev(NULL)
    , connected(false)
    , fd(fileDesc)
    , readHdr(true)
    , msg(0)
    , _self(socket)
  {
  }

  ~TransportSocketPrivate()
  {
  }

  static void onBufferSent(const void *QI_UNUSED(data), size_t QI_UNUSED(datalen), void *buffer)
  {
    Buffer *b = static_cast<Buffer *>(buffer);
    delete b;
  }

  static void onMessageSent(const void *QI_UNUSED(data), size_t QI_UNUSED(datalen), void *msg)
  {
    Message *m = static_cast<Message *>(msg);
    delete m;
  }

  TransportSocketInterface            *tcd;
  struct bufferevent                  *bev;
  bool                                 connected;
  std::map<unsigned int, qi::Message*> msgSend;
  boost::mutex                         mtx;
  boost::condition_variable            cond;
  int                                  fd;
  void readcb(struct bufferevent *bev , void *context);
  void writecb(struct bufferevent* bev, void* context);
  void eventcb(struct bufferevent *bev, short error, void *context);

  // data to rebuild message
  bool                         readHdr;
  qi::Message                 *msg;
  qi::TransportSocket         *_self;
};

static void readcb(struct bufferevent *bev,
                   void *context)
{
  TransportSocketPrivate *tc = static_cast<TransportSocketPrivate*>(context);
  tc->readcb(bev, context);
}

static void writecb(struct bufferevent* bev,
                    void* context)
{
  TransportSocketPrivate *tc = static_cast<TransportSocketPrivate*>(context);
  tc->writecb(bev, context);
}

static void eventcb(struct bufferevent *bev,
                    short error,
                    void *context)
{
  TransportSocketPrivate *tc = static_cast<TransportSocketPrivate*>(context);
  tc->eventcb(bev, error, context);
}

void TransportSocketPrivate::readcb(struct bufferevent *bev,
                                    void               *QI_UNUSED(context))
{
  struct evbuffer *input = bufferevent_get_input(bev);

  while (true)
  {
    if (msg == NULL)
    {
      msg = new qi::Message();
      readHdr = true;
    }

    if (readHdr)
    {
      if (evbuffer_get_length(input) < sizeof(MessagePrivate::MessageHeader))
        return;

      evbuffer_remove(input,
                      msg->_p->getHeader(),
                      sizeof(MessagePrivate::MessageHeader));
      readHdr = false;
    }

    if (evbuffer_get_length(input) <
          static_cast<MessagePrivate::MessageHeader*>(msg->_p->getHeader())->size)
      return;

    /* we have to let the Buffer know we are going to push some data inside */
    qi::Buffer buf;
    buf.reserve(static_cast<MessagePrivate::MessageHeader*>(msg->_p->getHeader())->size);
    msg->setBuffer(buf);

    evbuffer_remove(input,
                    buf.data(),
                    buf.size());
    assert(msg->isValid());

    {
      boost::mutex::scoped_lock l(mtx);
      msgSend[msg->id()] = msg;
      cond.notify_all();
    }
    if (tcd)
      tcd->onSocketReadyRead(_self, msg->id());

    msg = NULL;
  }
}

void TransportSocketPrivate::writecb(struct bufferevent *QI_UNUSED(bev),
                                     void               *QI_UNUSED(context))
{
  if (tcd)
    tcd->onSocketWriteDone(_self);
}

void TransportSocketPrivate::eventcb(struct bufferevent *bev,
                                     short events,
                                     void *QI_UNUSED(context))
{
  if (events & BEV_EVENT_CONNECTED)
  {
    connected = true;
    if (tcd)
      tcd->onSocketConnected(_self);
  }
  else if (events & BEV_EVENT_EOF)
  {
    bufferevent_free(bev);
    bev = 0;
    connected = false;
    //for waitForId
    cond.notify_all();
    if (tcd)
      tcd->onSocketDisconnected(_self);
    // connection has been closed, do any clean up here
  }
  else if (events & BEV_EVENT_ERROR)
  {
    bufferevent_free(bev);
    bev = 0;
    connected = false;
    //for waitForId
    cond.notify_all();
    if (tcd)
      tcd->onSocketConnectionError(_self);
    // check errno to see what error occurred
    qiLogError("qimessaging.TransportSocket")  << "Cannnot connect" << std::endl;
  }
  else if (events & BEV_EVENT_TIMEOUT)
  {
    // must be a timeout event handle, handle it
    qiLogError("qimessaging.TransportSocket")  << "must be a timeout event handle, handle it" << std::endl;
  }
}

TransportSocketInterface::~TransportSocketInterface() {
}

TransportSocket::TransportSocket()
  :_p(new TransportSocketPrivate(this))
{

}

TransportSocket::TransportSocket(int fd, void *data)
  :_p(new TransportSocketPrivate(this, fd))
{
  struct event_base *base = static_cast<event_base *>(data);
  _p->bev = bufferevent_socket_new(base, _p->fd, BEV_OPT_CLOSE_ON_FREE);
  bufferevent_setcb(_p->bev, ::qi::readcb, ::qi::writecb, ::qi::eventcb, _p);
  bufferevent_setwatermark(_p->bev, EV_WRITE, 0, MAX_LINE);
  bufferevent_enable(_p->bev, EV_READ|EV_WRITE);
  _p->connected = true;
}

TransportSocket::~TransportSocket()
{
  if (isConnected())
  {
    disconnect();
  }
  delete _p;
}

bool TransportSocket::connect(qi::Session *session,
                              const qi::Url &url)
{
  const std::string &address = url.host();
  unsigned short port = url.port();

  if (!isConnected())
  {
    _p->bev = bufferevent_socket_new(session->_p->_networkThread->getEventBase(), -1, BEV_OPT_CLOSE_ON_FREE);
    bufferevent_setcb(_p->bev, ::qi::readcb, ::qi::writecb, ::qi::eventcb, _p);
    bufferevent_setwatermark(_p->bev, EV_WRITE, 0, MAX_LINE);
    bufferevent_enable(_p->bev, EV_READ|EV_WRITE);

    int result = bufferevent_socket_connect_hostname(_p->bev, NULL, AF_INET, address.c_str(), port);
    if (result == 0)
    {
      _p->connected = true;
      return true;
    }
  }
  else
  {
    qiLogError("qimessaging.TransportSocket") << "socket is already connected.";
  }

  return false;
}

bool TransportSocket::waitForConnected(int msecs)
{
  // no timeout
  if (msecs < 0)
  {
    while (!_p->connected)
      ;

    return true;
  }

  while (!_p->connected && msecs > 0)
  {
    qi::os::msleep(1);
    msecs--;
  }

  // timeout
  if (msecs == 0)
    return false;

  return true;
}

void TransportSocket::disconnect()
{
  if (isConnected())
  {
    bufferevent_free(_p->bev);
    _p->bev = NULL;
    _p->connected = false;
  }
  else
  {
    qiLogError("qimessaging.TransportSocket") << "socket is not connected.";
  }
}

bool TransportSocket::waitForDisconnected(int msecs)
{
  // no timeout
  if (msecs < 0)
  {
    while (_p->connected)
      ;

    return true;
  }

  while (_p->connected && msecs > 0)
  {
    qi::os::msleep(1);
    msecs--;
  }

  // timeout
  if (msecs == 0)
    return false;

  return true;
}

bool TransportSocket::waitForId(int id, int msecs)
{
  std::map<unsigned int, qi::Message*>::iterator it;
  {
    {
      boost::mutex::scoped_lock l(_p->mtx);
      it = _p->msgSend.find(id);
      if (it != _p->msgSend.end())
        return true;
      if (!_p->connected)
        return false;
      if (msecs > 0)
        _p->cond.timed_wait(l, boost::posix_time::milliseconds(msecs));
      else
        _p->cond.wait(l);
      it = _p->msgSend.find(id);
      if (it != _p->msgSend.end())
        return true;
    }
  }
  return false;
}

bool TransportSocket::read(int id, qi::Message *msg)
{
  if (!isConnected())
  {
    qiLogError("qimessaging.TransportSocket") << "socket is not connected.";
    return false;
  }

  std::map<unsigned int, qi::Message*>::iterator it;
  {
    boost::mutex::scoped_lock l(_p->mtx);
    it = _p->msgSend.find(id);
    if (it != _p->msgSend.end())
    {
      *msg = *it->second;
      delete it->second;
      _p->msgSend.erase(it);
      return true;
    }
  }

  qiLogError("qimessaging.TransportSocket") << "message #" << id
                                            << " could not be found.";

  return false;
}

bool TransportSocket::send(const qi::Message &msg)
{
  if (!isConnected())
  {
    qiLogError("qimessaging.TransportSocket") << "socket is not connected.";
    return false;
  }

  qi::Message *m = new qi::Message();
  *m = msg;
  m->_p->complete();
  assert(m->isValid());

  struct evbuffer *evb = bufferevent_get_output(_p->bev);

  // m might be deleted.
  qi::Buffer *b = new qi::Buffer(m->buffer());

  if (evbuffer_add_reference(evb,
                             m->_p->getHeader(),
                             sizeof(qi::MessagePrivate::MessageHeader),
                             qi::TransportSocketPrivate::onMessageSent,
                             static_cast<void *>(m)) != 0)
  {
    return false;
  }

  if (b->size() &&
      evbuffer_add_reference(evb,
                             b->data(),
                             b->size(),
                             qi::TransportSocketPrivate::onBufferSent,
                             static_cast<void *>(b)) != 0)
  {
    return false;
  }

  if (bufferevent_write_buffer(_p->bev, evb) != 0)
  {
    return false;
  }

  return true;
}

void TransportSocket::setCallbacks(TransportSocketInterface *delegate)
{
  _p->tcd = delegate;
}

bool TransportSocket::isConnected()
{
  return _p->connected;
}

}

<|endoftext|>


<commit_before>/**************************************************************************
 * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
 *                                                                        *
 * Author: The ALICE Off-line Project.                                    *
 * Contributors are mentioned in the code where appropriate.              *
 *                                                                        *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
 **************************************************************************/

///////////////////////////////////////////////////////////////////////////////
//                                                                           //
// ANALYSIS task to perrorm TPC calibration                                  //

//                                                                           //
///////////////////////////////////////////////////////////////////////////////
#include "AliTPCAnalysisTaskcalib.h"
#include "TChain.h"
#include "AliTPCcalibBase.h"
#include "AliESDEvent.h"
#include "AliESDfriend.h"
#include "AliESDtrack.h"
#include "AliESDfriendTrack.h"
#include "AliTPCseed.h"
#include "AliESDInputHandler.h"
#include "AliAnalysisManager.h"
#include "TFile.h"
#include "TSystem.h"
#include "TTimeStamp.h"

ClassImp(AliTPCAnalysisTaskcalib)

AliTPCAnalysisTaskcalib::AliTPCAnalysisTaskcalib()
  :AliAnalysisTask(),
   fCalibJobs(0),
   fESD(0),
   fESDfriend(0),
   fDebugOutputPath("")
{
  //
  // default constructor
  //

}

AliTPCAnalysisTaskcalib::AliTPCAnalysisTaskcalib(const char *name)
  :AliAnalysisTask(name,""),
   fCalibJobs(0),
   fESD(0),
   fESDfriend(0),
   fDebugOutputPath("")
{
  //
  // Constructor
  //
  DefineInput(0, TChain::Class());
  DefineOutput(0, TObjArray::Class());
  fCalibJobs = new TObjArray(0);
  fCalibJobs->SetOwner(kTRUE);
}

AliTPCAnalysisTaskcalib::~AliTPCAnalysisTaskcalib() {
  //
  // destructor
  //
  printf("AliTPCAnalysisTaskcalib::~AliTPCAnalysisTaskcalib");
  fCalibJobs->Delete();
}

void AliTPCAnalysisTaskcalib::Exec(Option_t *) {
  //
  // Exec function
  // Loop over tracks and call  Process function
  if (!fESD) {
    //Printf("ERROR: fESD not available");
    return;
  }
  fESDfriend=static_cast<AliESDfriend*>(fESD->FindListObject("AliESDfriend"));
  if (!fESDfriend) {
    //Printf("ERROR: fESDfriend not available");
    return;
  }
  Int_t n=fESD->GetNumberOfTracks();
  Process(fESD);
  Int_t run = fESD->GetRunNumber();
  for (Int_t i=0;i<n;++i) {
    AliESDfriendTrack *friendTrack=fESDfriend->GetTrack(i);
    AliESDtrack *track=fESD->GetTrack(i);
    TObject *calibObject=0;
    AliTPCseed *seed=0;
    if (!friendTrack) continue;
    for (Int_t j=0;(calibObject=friendTrack->GetCalibObject(j));++j)
      if ((seed=dynamic_cast<AliTPCseed*>(calibObject)))
	break;
    if (track) Process(track, run);
    if (seed)
      Process(seed);
  }
  PostData(0,fCalibJobs);
}

void AliTPCAnalysisTaskcalib::ConnectInputData(Option_t *) {
  //
  //
  //
  TTree* tree=dynamic_cast<TTree*>(GetInputData(0));
  if (!tree) {
    //Printf("ERROR: Could not read chain from input slot 0");
  }
  else {
    AliESDInputHandler *esdH = dynamic_cast<AliESDInputHandler*> (AliAnalysisManager::GetAnalysisManager()->GetInputEventHandler());
    if (!esdH) {
      //Printf("ERROR: Could not get ESDInputHandler");
    }
    else {
      fESD = esdH->GetEvent();
      //Printf("*** CONNECTED NEW EVENT ****");
    }
  }
}

void AliTPCAnalysisTaskcalib::CreateOutputObjects() {
  //
  //
  //
  //OpenFile(0, "RECREATE");
}
void AliTPCAnalysisTaskcalib::Terminate(Option_t */*option*/) {
  //
  // Terminate
  //
  AliTPCcalibBase *job=0;
  Int_t njobs = fCalibJobs->GetEntriesFast();
  for (Int_t i=0;i<njobs;i++){
    job = (AliTPCcalibBase*)fCalibJobs->UncheckedAt(i);
    if (job) job->Terminate();
  }

}

void AliTPCAnalysisTaskcalib::FinishTaskOutput()
{
  //
  // According description in AliAnalisysTask this method is call
  // on the slaves before sending data
  //
  Terminate("slave");
  if(!fDebugOutputPath.IsNull()) {
    RegisterDebugOutput();
  }

}

void AliTPCAnalysisTaskcalib::Process(AliESDEvent *event) {
  //
  // Process ESD event
  //
  AliTPCcalibBase *job=0;
  Int_t njobs = fCalibJobs->GetEntriesFast();
  for (Int_t i=0;i<njobs;i++){
    job = (AliTPCcalibBase*)fCalibJobs->UncheckedAt(i);
    if (job) {
      job->UpdateEventInfo(event);
      if (job->AcceptTrigger())
	job->Process(event);
    }
  }
}

void AliTPCAnalysisTaskcalib::Process(AliTPCseed *track) {
  //
  // Process TPC track
  //
  AliTPCcalibBase *job=0;
  Int_t njobs = fCalibJobs->GetEntriesFast();
  for (Int_t i=0;i<njobs;i++){
    job = (AliTPCcalibBase*)fCalibJobs->UncheckedAt(i);
    if (job)
      if (job->AcceptTrigger())
	job->Process(track);
  }
}

void AliTPCAnalysisTaskcalib::Process(AliESDtrack *track, Int_t run) {
  //
  // Process ESD track
  //
  AliTPCcalibBase *job=0;
  Int_t njobs = fCalibJobs->GetEntriesFast();
  for (Int_t i=0;i<njobs;i++){
    job = (AliTPCcalibBase*)fCalibJobs->UncheckedAt(i);
    if (job)
      if (job->AcceptTrigger())
	job->Process(track,run);
  }
}

Long64_t AliTPCAnalysisTaskcalib::Merge(TCollection *li) {
  TIterator *i=fCalibJobs->MakeIterator();
  AliTPCcalibBase *job;
  Long64_t n=0;
  while ((job=dynamic_cast<AliTPCcalibBase*>(i->Next())))
    n+=job->Merge(li);
  return n;
}

void AliTPCAnalysisTaskcalib::Analyze() {
  //
  // Analyze the content of the task
  //
  AliTPCcalibBase *job=0;
  Int_t njobs = fCalibJobs->GetEntriesFast();
  for (Int_t i=0;i<njobs;i++){
    job = (AliTPCcalibBase*)fCalibJobs->UncheckedAt(i);
    if (job) job->Analyze();
  }
}

void AliTPCAnalysisTaskcalib::RegisterDebugOutput(){
  //
  //
  //
  AliTPCcalibBase *job=0;
  Int_t njobs = fCalibJobs->GetEntriesFast();
  for (Int_t i=0;i<njobs;i++){
    job = (AliTPCcalibBase*)fCalibJobs->UncheckedAt(i);
    if (job) job->RegisterDebugOutput(fDebugOutputPath.Data());
  }
  TString dsName=GetName();
  dsName+=".root";
  TFile fff(dsName.Data(),"recreate");
  fCalibJobs->Write("TPCCalib",TObject::kSingleKey);
  fff.Close();
  //
  // store  - copy debug output to the destination position
  // currently ONLY for local copy
  TString dsName2=fDebugOutputPath.Data();
  gSystem->MakeDirectory(dsName2.Data());
  dsName2+=gSystem->HostName();
  gSystem->MakeDirectory(dsName2.Data());
  dsName2+="/";
  TTimeStamp s;
  dsName2+=Int_t(s.GetNanoSec());
  dsName2+="/";
  gSystem->MakeDirectory(dsName2.Data());
  dsName2+=dsName;
  AliInfo(Form("copy %s\t%s\n",dsName.Data(),dsName2.Data()));
  printf("copy %s\t%s\n",dsName.Data(),dsName2.Data());
  TFile::Cp(dsName.Data(),dsName2.Data());

}
<commit_msg>removing AnalisysManager warning<commit_after>/**************************************************************************
 * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
 *                                                                        *
 * Author: The ALICE Off-line Project.                                    *
 * Contributors are mentioned in the code where appropriate.              *
 *                                                                        *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
 **************************************************************************/

///////////////////////////////////////////////////////////////////////////////
//                                                                           //
// ANALYSIS task to perrorm TPC calibration                                  //

//                                                                           //
///////////////////////////////////////////////////////////////////////////////
#include "AliTPCAnalysisTaskcalib.h"
#include "TChain.h"
#include "AliTPCcalibBase.h"
#include "AliESDEvent.h"
#include "AliESDfriend.h"
#include "AliESDtrack.h"
#include "AliESDfriendTrack.h"
#include "AliTPCseed.h"
#include "AliESDInputHandler.h"
#include "AliAnalysisManager.h"
#include "TFile.h"
#include "TSystem.h"
#include "TTimeStamp.h"

ClassImp(AliTPCAnalysisTaskcalib)

AliTPCAnalysisTaskcalib::AliTPCAnalysisTaskcalib()
  :AliAnalysisTask(),
   fCalibJobs(0),
   fESD(0),
   fESDfriend(0),
   fDebugOutputPath("")
{
  //
  // default constructor
  //

}

AliTPCAnalysisTaskcalib::AliTPCAnalysisTaskcalib(const char *name)
  :AliAnalysisTask(name,""),
   fCalibJobs(0),
   fESD(0),
   fESDfriend(0),
   fDebugOutputPath("")
{
  //
  // Constructor
  //
  DefineInput(0, TChain::Class());
  DefineOutput(0, TObjArray::Class());
  fCalibJobs = new TObjArray(0);
  fCalibJobs->SetOwner(kTRUE);
}

AliTPCAnalysisTaskcalib::~AliTPCAnalysisTaskcalib() {
  //
  // destructor
  //
  printf("AliTPCAnalysisTaskcalib::~AliTPCAnalysisTaskcalib");
  fCalibJobs->Delete();
}

void AliTPCAnalysisTaskcalib::Exec(Option_t *) {
  //
  // Exec function
  // Loop over tracks and call  Process function
  if (!fESD) {
    //Printf("ERROR: fESD not available");
    return;
  }
  fESDfriend=static_cast<AliESDfriend*>(fESD->FindListObject("AliESDfriend"));
  if (!fESDfriend) {
    //Printf("ERROR: fESDfriend not available");
    return;
  }
  Int_t n=fESD->GetNumberOfTracks();
  Process(fESD);
  Int_t run = fESD->GetRunNumber();
  for (Int_t i=0;i<n;++i) {
    AliESDfriendTrack *friendTrack=fESDfriend->GetTrack(i);
    AliESDtrack *track=fESD->GetTrack(i);
    TObject *calibObject=0;
    AliTPCseed *seed=0;
    if (!friendTrack) continue;
    for (Int_t j=0;(calibObject=friendTrack->GetCalibObject(j));++j)
      if ((seed=dynamic_cast<AliTPCseed*>(calibObject)))
	break;
    if (track) Process(track, run);
    if (seed)
      Process(seed);
  }
  PostData(0,fCalibJobs);
}

void AliTPCAnalysisTaskcalib::ConnectInputData(Option_t *) {
  //
  //
  //
  TTree* tree=dynamic_cast<TTree*>(GetInputData(0));
  if (!tree) {
    //Printf("ERROR: Could not read chain from input slot 0");
  }
  else {
    AliESDInputHandler *esdH = dynamic_cast<AliESDInputHandler*> (AliAnalysisManager::GetAnalysisManager()->GetInputEventHandler());
    if (!esdH) {
      //Printf("ERROR: Could not get ESDInputHandler");
    }
    else {
      fESD = esdH->GetEvent();
      //Printf("*** CONNECTED NEW EVENT ****");
    }
  }
}

void AliTPCAnalysisTaskcalib::CreateOutputObjects() {
  //
  //
  //
  //OpenFile(0, "RECREATE");

  PostData(0,fCalibJobs);
}

void AliTPCAnalysisTaskcalib::Terminate(Option_t */*option*/) {
  //
  // Terminate
  //
  AliTPCcalibBase *job=0;
  Int_t njobs = fCalibJobs->GetEntriesFast();
  for (Int_t i=0;i<njobs;i++){
    job = (AliTPCcalibBase*)fCalibJobs->UncheckedAt(i);
    if (job) job->Terminate();
  }

}

void AliTPCAnalysisTaskcalib::FinishTaskOutput()
{
  //
  // According description in AliAnalisysTask this method is call
  // on the slaves before sending data
  //
  Terminate("slave");
  if(!fDebugOutputPath.IsNull()) {
    RegisterDebugOutput();
  }

}

void AliTPCAnalysisTaskcalib::Process(AliESDEvent *event) {
  //
  // Process ESD event
  //
  AliTPCcalibBase *job=0;
  Int_t njobs = fCalibJobs->GetEntriesFast();
  for (Int_t i=0;i<njobs;i++){
    job = (AliTPCcalibBase*)fCalibJobs->UncheckedAt(i);
    if (job) {
      job->UpdateEventInfo(event);
      if (job->AcceptTrigger())
	job->Process(event);
    }
  }
}

void AliTPCAnalysisTaskcalib::Process(AliTPCseed *track) {
  //
  // Process TPC track
  //
  AliTPCcalibBase *job=0;
  Int_t njobs = fCalibJobs->GetEntriesFast();
  for (Int_t i=0;i<njobs;i++){
    job = (AliTPCcalibBase*)fCalibJobs->UncheckedAt(i);
    if (job)
      if (job->AcceptTrigger())
	job->Process(track);
  }
}

void AliTPCAnalysisTaskcalib::Process(AliESDtrack *track, Int_t run) {
  //
  // Process ESD track
  //
  AliTPCcalibBase *job=0;
  Int_t njobs = fCalibJobs->GetEntriesFast();
  for (Int_t i=0;i<njobs;i++){
    job = (AliTPCcalibBase*)fCalibJobs->UncheckedAt(i);
    if (job)
      if (job->AcceptTrigger())
	job->Process(track,run);
  }
}

Long64_t AliTPCAnalysisTaskcalib::Merge(TCollection *li) {
  TIterator *i=fCalibJobs->MakeIterator();
  AliTPCcalibBase *job;
  Long64_t n=0;
  while ((job=dynamic_cast<AliTPCcalibBase*>(i->Next())))
    n+=job->Merge(li);
  return n;
}

void AliTPCAnalysisTaskcalib::Analyze() {
  //
  // Analyze the content of the task
  //
  AliTPCcalibBase *job=0;
  Int_t njobs = fCalibJobs->GetEntriesFast();
  for (Int_t i=0;i<njobs;i++){
    job = (AliTPCcalibBase*)fCalibJobs->UncheckedAt(i);
    if (job) job->Analyze();
  }
}

void AliTPCAnalysisTaskcalib::RegisterDebugOutput(){
  //
  //
  //
  AliTPCcalibBase *job=0;
  Int_t njobs = fCalibJobs->GetEntriesFast();
  for (Int_t i=0;i<njobs;i++){
    job = (AliTPCcalibBase*)fCalibJobs->UncheckedAt(i);
    if (job) job->RegisterDebugOutput(fDebugOutputPath.Data());
  }
  TString dsName=GetName();
  dsName+=".root";
  TFile fff(dsName.Data(),"recreate");
  fCalibJobs->Write("TPCCalib",TObject::kSingleKey);
  fff.Close();
  //
  // store  - copy debug output to the destination position
  // currently ONLY for local copy
  TString dsName2=fDebugOutputPath.Data();
  gSystem->MakeDirectory(dsName2.Data());
  dsName2+=gSystem->HostName();
  gSystem->MakeDirectory(dsName2.Data());
  dsName2+="/";
  TTimeStamp s;
  dsName2+=Int_t(s.GetNanoSec());
  dsName2+="/";
  gSystem->MakeDirectory(dsName2.Data());
  dsName2+=dsName;
  AliInfo(Form("copy %s\t%s\n",dsName.Data(),dsName2.Data()));
  printf("copy %s\t%s\n",dsName.Data(),dsName2.Data());
  TFile::Cp(dsName.Data(),dsName2.Data());

}
<|endoftext|>


<commit_before>/*
 * This file is part of meego-keyboard
 *
 * Copyright (C) 2010-2011 Nokia Corporation and/or its subsidiary(-ies). All rights reserved.
 *
 * Contact: Mohammad Anwari <Mohammad.Anwari@nokia.com>
 *
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice, this list
 * of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright notice, this list
 * of conditions and the following disclaimer in the documentation and/or other materials
 * provided with the distribution.
 * Neither the name of Nokia Corporation nor the names of its contributors may be
 * used to endorse or promote products derived from this software without specific
 * prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
 * THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

 */
#include "notificationarea.h"
#include "notificationpanparameters.h"
#include "mplainwindow.h"
#include "notification.h"

#include <QDebug>
#include <QPainter>
#include <QPropertyAnimation>

#include <MSceneManager>
#include <MScalableImage>
#include <float.h>

NotificationArea::NotificationArea(QGraphicsItem *parent)
    : MStylableWidget(parent),
      outgoingNotification(new Notification(this)),
      incomingNotification(new Notification(this)),
      assistantNotification(new Notification(this)),
      outgoingNotificationParameters(new NotificationPanParameters(this)),
      incomingNotificationParameters(new NotificationPanParameters(this)),
      assistantNotificationParameters(new NotificationPanParameters(this)),
      hideAnimationGroup(this),
      showAnimation(this, "opacity")
{
    outgoingNotification->connectPanParameters(outgoingNotificationParameters);
    incomingNotification->connectPanParameters(incomingNotificationParameters);
    assistantNotification->connectPanParameters(assistantNotificationParameters);

    connect(&hideAnimationGroup, SIGNAL(finished()),
            this, SLOT(onNotificationAnimationFinished()));

    connect(&hideAnimationGroup, SIGNAL(finished()),
            this, SLOT(reset()));
}

NotificationArea::~NotificationArea()
{
}

void NotificationArea::prepareNotifications(PanGesture::PanDirection direction)
{
    qDebug() << __PRETTY_FUNCTION__;

    onNotificationAnimationFinished();

    const int screenWidth
        = (MPlainWindow::instance()->sceneManager()->orientation() == M::Portrait)
          ? MPlainWindow::instance()->visibleSceneSize(M::Landscape).height()
          : MPlainWindow::instance()->visibleSceneSize(M::Landscape).width();

    // prepare notifications
    qreal notificationMaximumWidth
        = style()->notificationMaximumWidth();

    outgoingNotification->setMaximumTextWidth(notificationMaximumWidth);
    incomingNotification->setMaximumTextWidth(notificationMaximumWidth);
    assistantNotification->setMaximumTextWidth(notificationMaximumWidth);

    qreal outgoingNotificationFromScale
        = qBound<qreal>(0, qreal(notificationMaximumWidth / outgoingNotification->preferredWidth()), 1.0);

    qreal outgoingNotificationToScale
        = style()->smallSizeScaleFactor();

    QPointF outgoingNotificationFromPos
        = QPointF((screenWidth - outgoingNotification->preferredWidth()
                   * outgoingNotificationFromScale) / 2,
                  preferredHeight()
                  - outgoingNotification->preferredHeight()
                  * outgoingNotificationFromScale);

    qreal outgoingNotificationToPosX
        = (direction == PanGesture::PanRight)
          ? screenWidth
          : - outgoingNotification->preferredWidth()
            * outgoingNotificationToScale;

    qreal outgoingNotificationToPosY
        = preferredHeight()
          - outgoingNotification->preferredHeight() * outgoingNotificationToScale;

    QPointF outgoingNotificationToPos
        = QPointF(outgoingNotificationToPosX, outgoingNotificationToPosY);

    outgoingNotification->updateScale(outgoingNotificationFromScale);
    outgoingNotification->updateOpacity(1.0);
    outgoingNotification->updatePos(outgoingNotificationFromPos);
    outgoingNotification->setVisible(true);
    outgoingNotificationParameters->setPositionRange(
        outgoingNotificationFromPos, outgoingNotificationToPos);
    outgoingNotificationParameters->setScaleRange(outgoingNotificationFromScale,
                                                  outgoingNotificationToScale);
    outgoingNotificationParameters->setOpacityRange(1.0, 0.0);
    outgoingNotificationParameters->setPositionProgressRange(
            style()->positionStartProgress(),
            style()->positionEndProgress());
    outgoingNotificationParameters->setScaleProgressRange(
            style()->scaleStartProgress(),
            style()->scaleEndProgress());
    outgoingNotificationParameters->setOpacityProgressRange(
            style()->opacityStartProgress(),
            style()->opacityEndProgress());

    qreal leftAndRightSpace
        = (outgoingNotification->preferredWidth()
           < screenWidth * (1 - style()->initialEdgeMaximumVisibleWidth() * 2))
          ? screenWidth * style()->initialEdgeMaximumVisibleWidth()
          : (screenWidth - notificationMaximumWidth) / 2;
    // prepare left and right notifications
    if (direction == PanGesture::PanRight) {
        incomingNotification->setText(mLeftLayoutTitle);
        assistantNotification->setText(mRightLayoutTitle);
    } else {
        incomingNotification->setText(mRightLayoutTitle);
        assistantNotification->setText(mLeftLayoutTitle);
    }

    qreal incomingNotificationFromScale = outgoingNotificationToScale;

    qreal incomingNotificationToScale
        = qBound<qreal>(0, qreal(notificationMaximumWidth / incomingNotification->preferredWidth()), 1.0);

    qreal incomingNotificationFromPosX = 0;
    if (incomingNotification->preferredWidth() * incomingNotificationFromScale
        > leftAndRightSpace) {

       incomingNotificationFromPosX
        = (direction == PanGesture::PanRight)
          ? leftAndRightSpace
            - incomingNotification->preferredWidth() * incomingNotificationFromScale
          : screenWidth - leftAndRightSpace;
    } else {

       incomingNotificationFromPosX
        = (direction == PanGesture::PanRight)
          ? 0
          : screenWidth - incomingNotification->preferredWidth() * incomingNotificationFromScale;
    }

    qreal incomingNotificationFromPosY
        = preferredHeight()
          - incomingNotification->preferredHeight() * incomingNotificationFromScale;
    QPointF incomingNotificationFromPos
        = QPointF(incomingNotificationFromPosX, incomingNotificationFromPosY);

    QPointF incomingNotificationToPos
        = QPointF((screenWidth - incomingNotification->preferredWidth()
                   * incomingNotificationToScale) / 2,
                  preferredHeight()
                  - incomingNotification->preferredHeight()
                  * incomingNotificationToScale);

    incomingNotification->updateScale(incomingNotificationFromScale);
    incomingNotification->updatePos(incomingNotificationFromPos);
    incomingNotification->updateOpacity(style()->initialEdgeOpacity());
    incomingNotification->setVisible(true);
    incomingNotificationParameters->setPositionRange(
        incomingNotificationFromPos, incomingNotificationToPos);
    incomingNotificationParameters->setScaleRange(incomingNotificationFromScale,
                                                  incomingNotificationToScale);
    incomingNotificationParameters->setOpacityRange(style()->initialEdgeOpacity(),
                                                    1.0);

    incomingNotificationParameters->setPositionProgressRange(
            style()->positionStartProgress(),
            style()->positionEndProgress());
    incomingNotificationParameters->setScaleProgressRange(
            style()->scaleStartProgress(),
            style()->scaleEndProgress());
    incomingNotificationParameters->setOpacityProgressRange(
            style()->opacityStartProgress(),
            style()->opacityEndProgress());

    qreal assistantNotificationFromScale = outgoingNotificationToScale;

    qreal assistantNotificationFromPosX = 0;

    if (assistantNotification->preferredWidth() * assistantNotificationFromScale
        > leftAndRightSpace) {

       assistantNotificationFromPosX
        = (direction == PanGesture::PanRight)
          ? screenWidth - leftAndRightSpace
          : leftAndRightSpace
            - assistantNotification->preferredWidth() * assistantNotificationFromScale;
    } else {

       assistantNotificationFromPosX
        = (direction == PanGesture::PanRight)
          ? screenWidth - assistantNotification->preferredWidth() * assistantNotificationFromScale
          : 0;
    }

    qreal assistantNotificationFromPosY
        = preferredHeight()
          - assistantNotification->preferredHeight() * assistantNotificationFromScale;
    qreal assistantNotificationToPosY
        = preferredHeight()
          - assistantNotification->preferredHeight() * outgoingNotificationToScale;

    QPointF assistantNotificationFromPos
        = QPointF(assistantNotificationFromPosX, assistantNotificationFromPosY);

    qreal outgoingNotificationXMoveMent
        = outgoingNotificationToPos.x() - outgoingNotificationFromPos.x();
    QPointF assistantNotificationToPos
        = QPointF(assistantNotificationFromPos.x() + outgoingNotificationXMoveMent,
                  assistantNotificationToPosY);

    assistantNotification->updateScale(assistantNotificationFromScale);
    assistantNotification->updateOpacity(style()->initialEdgeOpacity());
    assistantNotification->updatePos(assistantNotificationFromPos);
    assistantNotification->setVisible(true);
    assistantNotificationParameters->setPositionRange(
        assistantNotificationFromPos, assistantNotificationToPos);
    assistantNotificationParameters->setScaleRange(assistantNotificationFromScale,
                                               assistantNotificationFromScale * outgoingNotificationToScale);
    assistantNotificationParameters->setOpacityRange(style()->initialEdgeOpacity(),
                                                 0.0);

    assistantNotificationParameters->setPositionProgressRange(
            style()->positionStartProgress(),
            style()->positionEndProgress());
    assistantNotificationParameters->setScaleProgressRange(
            style()->scaleStartProgress(),
            style()->scaleEndProgress());
    assistantNotificationParameters->setOpacityProgressRange(
            style()->opacityStartProgress(),
            style()->opacityEndProgress());
}

void NotificationArea::setOutgoingLayoutTitle(const QString &title)
{
    mOutgoingLayoutTitle = title;
    outgoingNotification->setText(title);
}

QString NotificationArea::outgoingLayoutTitle() const
{
    return mOutgoingLayoutTitle;
}

void NotificationArea::setIncomingLayoutTitle(PanGesture::PanDirection direction,
                                            const QString &title)
{
    if (direction == PanGesture::PanRight)
        mRightLayoutTitle = title;
    else
        mLeftLayoutTitle = title;
}

QString NotificationArea::setIncomingLayoutTitle(PanGesture::PanDirection direction) const
{
    if (direction == PanGesture::PanRight)
        return mRightLayoutTitle;
    else
        return mLeftLayoutTitle;
}

void NotificationArea::playShowAnimation()
{
    setOpacity(style()->initialOpacity());
    setVisible(true);
    showAnimation.start();
}

void NotificationArea::playHideAnimation(PanGesture::PanDirection result)
{
    showAnimation.stop();

    Notification *resultNotification = incomingNotification;
    if (result == PanGesture::PanNone) {
        incomingNotification->setVisible(false);
        assistantNotification->setVisible(false);
        resultNotification = outgoingNotification;
    }
    setVisible(true);
    hideAnimationGroup.clear();

    QPropertyAnimation *bgAnimation = new QPropertyAnimation(this);
    bgAnimation->setTargetObject(this);
    bgAnimation->setPropertyName("opacity");
    bgAnimation->setStartValue(1.0);
    bgAnimation->setEndValue(0.0);
    bgAnimation->setEasingCurve(style()->hideAnimationCurve());
    bgAnimation->setDuration(style()->hideAnimationDuration());

    QPropertyAnimation *itemAnimation = new QPropertyAnimation(this);
    itemAnimation->setTargetObject(resultNotification);
    itemAnimation->setPropertyName("opacity");
    itemAnimation->setStartValue(this->opacity());
    itemAnimation->setEndValue(0.0);
    itemAnimation->setEasingCurve(style()->hideAnimationCurve());
    itemAnimation->setDuration(style()->hideAnimationDuration());

    hideAnimationGroup.addAnimation(bgAnimation);
    hideAnimationGroup.addAnimation(itemAnimation);

    hideAnimationGroup.start();
}

void NotificationArea::onNotificationAnimationFinished()
{
    qDebug() << __PRETTY_FUNCTION__;
    showAnimation.stop();
    hideAnimationGroup.stop();
    hideAnimationGroup.clear();
    setVisible(false);
}

void NotificationArea::cancel()
{
    onNotificationAnimationFinished();
}

void NotificationArea::setProgress(qreal progress)
{
    outgoingNotificationParameters->setProgress(progress);
    incomingNotificationParameters->setProgress(progress);
    assistantNotificationParameters->setProgress(progress);
}

void NotificationArea::applyStyle()
{
    showAnimation.setEasingCurve(style()->showAnimationCurve());
    showAnimation.setDuration(style()->showAnimationDuration());
    showAnimation.setStartValue(style()->initialOpacity());
    showAnimation.setEndValue(style()->visibleOpacity());
}

void NotificationArea::reset()
{
    setOutgoingLayoutTitle("");
    setIncomingLayoutTitle(PanGesture::PanLeft, "");
    setIncomingLayoutTitle(PanGesture::PanRight, "");
}
<commit_msg>Changes: notification can smoothly change animation between hide and show<commit_after>/*
 * This file is part of meego-keyboard
 *
 * Copyright (C) 2010-2011 Nokia Corporation and/or its subsidiary(-ies). All rights reserved.
 *
 * Contact: Mohammad Anwari <Mohammad.Anwari@nokia.com>
 *
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice, this list
 * of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright notice, this list
 * of conditions and the following disclaimer in the documentation and/or other materials
 * provided with the distribution.
 * Neither the name of Nokia Corporation nor the names of its contributors may be
 * used to endorse or promote products derived from this software without specific
 * prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
 * THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

 */
#include "notificationarea.h"
#include "notificationpanparameters.h"
#include "mplainwindow.h"
#include "notification.h"

#include <QDebug>
#include <QPainter>
#include <QPropertyAnimation>

#include <MSceneManager>
#include <MScalableImage>
#include <float.h>

NotificationArea::NotificationArea(QGraphicsItem *parent)
    : MStylableWidget(parent),
      outgoingNotification(new Notification(this)),
      incomingNotification(new Notification(this)),
      assistantNotification(new Notification(this)),
      outgoingNotificationParameters(new NotificationPanParameters(this)),
      incomingNotificationParameters(new NotificationPanParameters(this)),
      assistantNotificationParameters(new NotificationPanParameters(this)),
      hideAnimationGroup(this),
      showAnimation(this, "opacity")
{
    outgoingNotification->connectPanParameters(outgoingNotificationParameters);
    incomingNotification->connectPanParameters(incomingNotificationParameters);
    assistantNotification->connectPanParameters(assistantNotificationParameters);

    connect(&hideAnimationGroup, SIGNAL(finished()),
            this, SLOT(onNotificationAnimationFinished()));

    connect(&hideAnimationGroup, SIGNAL(finished()),
            this, SLOT(reset()));

    setVisible(false);
}

NotificationArea::~NotificationArea()
{
}

void NotificationArea::prepareNotifications(PanGesture::PanDirection direction)
{
    qDebug() << __PRETTY_FUNCTION__;

    const int screenWidth
        = (MPlainWindow::instance()->sceneManager()->orientation() == M::Portrait)
          ? MPlainWindow::instance()->visibleSceneSize(M::Landscape).height()
          : MPlainWindow::instance()->visibleSceneSize(M::Landscape).width();

    // prepare notifications
    qreal notificationMaximumWidth
        = style()->notificationMaximumWidth();

    outgoingNotification->setMaximumTextWidth(notificationMaximumWidth);
    incomingNotification->setMaximumTextWidth(notificationMaximumWidth);
    assistantNotification->setMaximumTextWidth(notificationMaximumWidth);

    qreal outgoingNotificationFromScale
        = qBound<qreal>(0, qreal(notificationMaximumWidth / outgoingNotification->preferredWidth()), 1.0);

    qreal outgoingNotificationToScale
        = style()->smallSizeScaleFactor();

    QPointF outgoingNotificationFromPos
        = QPointF((screenWidth - outgoingNotification->preferredWidth()
                   * outgoingNotificationFromScale) / 2,
                  preferredHeight()
                  - outgoingNotification->preferredHeight()
                  * outgoingNotificationFromScale);

    qreal outgoingNotificationToPosX
        = (direction == PanGesture::PanRight)
          ? screenWidth
          : - outgoingNotification->preferredWidth()
            * outgoingNotificationToScale;

    qreal outgoingNotificationToPosY
        = preferredHeight()
          - outgoingNotification->preferredHeight() * outgoingNotificationToScale;

    QPointF outgoingNotificationToPos
        = QPointF(outgoingNotificationToPosX, outgoingNotificationToPosY);

    outgoingNotification->updateScale(outgoingNotificationFromScale);
    outgoingNotification->updateOpacity(1.0);
    outgoingNotification->updatePos(outgoingNotificationFromPos);
    outgoingNotification->setVisible(true);
    outgoingNotificationParameters->setPositionRange(
        outgoingNotificationFromPos, outgoingNotificationToPos);
    outgoingNotificationParameters->setScaleRange(outgoingNotificationFromScale,
                                                  outgoingNotificationToScale);
    outgoingNotificationParameters->setOpacityRange(1.0, 0.0);
    outgoingNotificationParameters->setPositionProgressRange(
            style()->positionStartProgress(),
            style()->positionEndProgress());
    outgoingNotificationParameters->setScaleProgressRange(
            style()->scaleStartProgress(),
            style()->scaleEndProgress());
    outgoingNotificationParameters->setOpacityProgressRange(
            style()->opacityStartProgress(),
            style()->opacityEndProgress());

    qreal leftAndRightSpace
        = (outgoingNotification->preferredWidth()
           < screenWidth * (1 - style()->initialEdgeMaximumVisibleWidth() * 2))
          ? screenWidth * style()->initialEdgeMaximumVisibleWidth()
          : (screenWidth - notificationMaximumWidth) / 2;
    // prepare left and right notifications
    if (direction == PanGesture::PanRight) {
        incomingNotification->setText(mLeftLayoutTitle);
        assistantNotification->setText(mRightLayoutTitle);
    } else {
        incomingNotification->setText(mRightLayoutTitle);
        assistantNotification->setText(mLeftLayoutTitle);
    }

    qreal incomingNotificationFromScale = outgoingNotificationToScale;

    qreal incomingNotificationToScale
        = qBound<qreal>(0, qreal(notificationMaximumWidth / incomingNotification->preferredWidth()), 1.0);

    qreal incomingNotificationFromPosX = 0;
    if (incomingNotification->preferredWidth() * incomingNotificationFromScale
        > leftAndRightSpace) {

       incomingNotificationFromPosX
        = (direction == PanGesture::PanRight)
          ? leftAndRightSpace
            - incomingNotification->preferredWidth() * incomingNotificationFromScale
          : screenWidth - leftAndRightSpace;
    } else {

       incomingNotificationFromPosX
        = (direction == PanGesture::PanRight)
          ? 0
          : screenWidth - incomingNotification->preferredWidth() * incomingNotificationFromScale;
    }

    qreal incomingNotificationFromPosY
        = preferredHeight()
          - incomingNotification->preferredHeight() * incomingNotificationFromScale;
    QPointF incomingNotificationFromPos
        = QPointF(incomingNotificationFromPosX, incomingNotificationFromPosY);

    QPointF incomingNotificationToPos
        = QPointF((screenWidth - incomingNotification->preferredWidth()
                   * incomingNotificationToScale) / 2,
                  preferredHeight()
                  - incomingNotification->preferredHeight()
                  * incomingNotificationToScale);

    incomingNotification->updateScale(incomingNotificationFromScale);
    incomingNotification->updatePos(incomingNotificationFromPos);
    incomingNotification->updateOpacity(style()->initialEdgeOpacity());
    incomingNotification->setVisible(true);
    incomingNotificationParameters->setPositionRange(
        incomingNotificationFromPos, incomingNotificationToPos);
    incomingNotificationParameters->setScaleRange(incomingNotificationFromScale,
                                                  incomingNotificationToScale);
    incomingNotificationParameters->setOpacityRange(style()->initialEdgeOpacity(),
                                                    1.0);

    incomingNotificationParameters->setPositionProgressRange(
            style()->positionStartProgress(),
            style()->positionEndProgress());
    incomingNotificationParameters->setScaleProgressRange(
            style()->scaleStartProgress(),
            style()->scaleEndProgress());
    incomingNotificationParameters->setOpacityProgressRange(
            style()->opacityStartProgress(),
            style()->opacityEndProgress());

    qreal assistantNotificationFromScale = outgoingNotificationToScale;

    qreal assistantNotificationFromPosX = 0;

    if (assistantNotification->preferredWidth() * assistantNotificationFromScale
        > leftAndRightSpace) {

       assistantNotificationFromPosX
        = (direction == PanGesture::PanRight)
          ? screenWidth - leftAndRightSpace
          : leftAndRightSpace
            - assistantNotification->preferredWidth() * assistantNotificationFromScale;
    } else {

       assistantNotificationFromPosX
        = (direction == PanGesture::PanRight)
          ? screenWidth - assistantNotification->preferredWidth() * assistantNotificationFromScale
          : 0;
    }

    qreal assistantNotificationFromPosY
        = preferredHeight()
          - assistantNotification->preferredHeight() * assistantNotificationFromScale;
    qreal assistantNotificationToPosY
        = preferredHeight()
          - assistantNotification->preferredHeight() * outgoingNotificationToScale;

    QPointF assistantNotificationFromPos
        = QPointF(assistantNotificationFromPosX, assistantNotificationFromPosY);

    qreal outgoingNotificationXMoveMent
        = outgoingNotificationToPos.x() - outgoingNotificationFromPos.x();
    QPointF assistantNotificationToPos
        = QPointF(assistantNotificationFromPos.x() + outgoingNotificationXMoveMent,
                  assistantNotificationToPosY);

    assistantNotification->updateScale(assistantNotificationFromScale);
    assistantNotification->updateOpacity(style()->initialEdgeOpacity());
    assistantNotification->updatePos(assistantNotificationFromPos);
    assistantNotification->setVisible(true);
    assistantNotificationParameters->setPositionRange(
        assistantNotificationFromPos, assistantNotificationToPos);
    assistantNotificationParameters->setScaleRange(assistantNotificationFromScale,
                                               assistantNotificationFromScale * outgoingNotificationToScale);
    assistantNotificationParameters->setOpacityRange(style()->initialEdgeOpacity(),
                                                 0.0);

    assistantNotificationParameters->setPositionProgressRange(
            style()->positionStartProgress(),
            style()->positionEndProgress());
    assistantNotificationParameters->setScaleProgressRange(
            style()->scaleStartProgress(),
            style()->scaleEndProgress());
    assistantNotificationParameters->setOpacityProgressRange(
            style()->opacityStartProgress(),
            style()->opacityEndProgress());
}

void NotificationArea::setOutgoingLayoutTitle(const QString &title)
{
    mOutgoingLayoutTitle = title;
    outgoingNotification->setText(title);
}

QString NotificationArea::outgoingLayoutTitle() const
{
    return mOutgoingLayoutTitle;
}

void NotificationArea::setIncomingLayoutTitle(PanGesture::PanDirection direction,
                                            const QString &title)
{
    if (direction == PanGesture::PanRight)
        mRightLayoutTitle = title;
    else
        mLeftLayoutTitle = title;
}

QString NotificationArea::setIncomingLayoutTitle(PanGesture::PanDirection direction) const
{
    if (direction == PanGesture::PanRight)
        return mRightLayoutTitle;
    else
        return mLeftLayoutTitle;
}

void NotificationArea::playShowAnimation()
{
    if (!isVisible()) {
        setVisible(true);
        setOpacity(style()->initialOpacity());
    }
    hideAnimationGroup.stop();
    hideAnimationGroup.clear();
    // show animation start from current opacity
    showAnimation.setStartValue(opacity());
    showAnimation.setEndValue(style()->visibleOpacity());
    showAnimation.start();
}

void NotificationArea::playHideAnimation(PanGesture::PanDirection result)
{
    showAnimation.stop();

    Notification *resultNotification = incomingNotification;
    if (result == PanGesture::PanNone) {
        incomingNotification->setVisible(false);
        assistantNotification->setVisible(false);
        resultNotification = outgoingNotification;
    }
    setVisible(true);
    hideAnimationGroup.clear();

    QPropertyAnimation *bgAnimation = new QPropertyAnimation(this);
    bgAnimation->setTargetObject(this);
    bgAnimation->setPropertyName("opacity");
    bgAnimation->setStartValue(opacity());
    bgAnimation->setEndValue(0.0);
    bgAnimation->setEasingCurve(style()->hideAnimationCurve());
    bgAnimation->setDuration(style()->hideAnimationDuration());

    QPropertyAnimation *itemAnimation = new QPropertyAnimation(this);
    itemAnimation->setTargetObject(resultNotification);
    itemAnimation->setPropertyName("opacity");
    itemAnimation->setStartValue(opacity());
    itemAnimation->setEndValue(0.0);
    itemAnimation->setEasingCurve(style()->hideAnimationCurve());
    itemAnimation->setDuration(style()->hideAnimationDuration());

    hideAnimationGroup.addAnimation(bgAnimation);
    hideAnimationGroup.addAnimation(itemAnimation);

    hideAnimationGroup.start();
}

void NotificationArea::onNotificationAnimationFinished()
{
    qDebug() << __PRETTY_FUNCTION__;
    showAnimation.stop();
    hideAnimationGroup.stop();
    hideAnimationGroup.clear();
    setVisible(false);
}

void NotificationArea::cancel()
{
    onNotificationAnimationFinished();
}

void NotificationArea::setProgress(qreal progress)
{
    outgoingNotificationParameters->setProgress(progress);
    incomingNotificationParameters->setProgress(progress);
    assistantNotificationParameters->setProgress(progress);
}

void NotificationArea::applyStyle()
{
    showAnimation.setEasingCurve(style()->showAnimationCurve());
    showAnimation.setDuration(style()->showAnimationDuration());
    showAnimation.setEndValue(style()->visibleOpacity());
}

void NotificationArea::reset()
{
    setOutgoingLayoutTitle("");
    setIncomingLayoutTitle(PanGesture::PanLeft, "");
    setIncomingLayoutTitle(PanGesture::PanRight, "");
}
<|endoftext|>


<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you 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 .
 */

#include <sal/main.h>
#include <tools/extendapplicationenvironment.hxx>

#include <cppuhelper/bootstrap.hxx>
#include <comphelper/processfactory.hxx>

#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#include <com/sun/star/uno/XComponentContext.hpp>

#include <vcl/event.hxx>
#include <vcl/svapp.hxx>
#include <vcl/wrkwin.hxx>
#include <vcl/gradient.hxx>
#include <vcl/lineinfo.hxx>
#include <vcl/bitmap.hxx>
#include <vcl/bmpacc.hxx>
#include <vcl/metric.hxx>

#include <rtl/ustrbuf.hxx>

#include <math.h>

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

// Forward declaration
void Main();

SAL_IMPLEMENT_MAIN()
{
    tools::extendApplicationEnvironment();

    Reference< XComponentContext > xContext = defaultBootstrap_InitialComponentContext();
    Reference< XMultiServiceFactory > xServiceManager( xContext->getServiceManager(), UNO_QUERY );

    if( !xServiceManager.is() )
        Application::Abort( "Failed to bootstrap" );

    comphelper::setProcessServiceFactory( xServiceManager );

    InitVCL();
    ::Main();
    DeInitVCL();

    return 0;
}

class MyWin : public WorkWindow
{
    Bitmap      m_aBitmap;
public:
                 MyWin( vcl::Window* pParent, WinBits nWinStyle );

    virtual void MouseMove( const MouseEvent& rMEvt ) SAL_OVERRIDE;
    virtual void MouseButtonDown( const MouseEvent& rMEvt ) SAL_OVERRIDE;
    virtual void MouseButtonUp( const MouseEvent& rMEvt ) SAL_OVERRIDE;
    virtual void KeyInput( const KeyEvent& rKEvt ) SAL_OVERRIDE;
    virtual void KeyUp( const KeyEvent& rKEvt ) SAL_OVERRIDE;
    virtual void Paint( const Rectangle& rRect ) SAL_OVERRIDE;
    virtual void Resize() SAL_OVERRIDE;
};

void Main()
{
    MyWin aMainWin( NULL, WB_APP | WB_STDWORK );
    aMainWin.SetText( OUString( "VCL - Workbench" ) );
    aMainWin.Show();

    Application::Execute();
}

MyWin::MyWin( vcl::Window* pParent, WinBits nWinStyle ) :
    WorkWindow( pParent, nWinStyle ),
    m_aBitmap( Size( 256, 256 ), 32 )
{
    // prepare an alpha mask
    BitmapWriteAccess* pAcc = m_aBitmap.AcquireWriteAccess();
    for( int nX = 0; nX < 256; nX++ )
    {
        for( int nY = 0; nY < 256; nY++ )
        {
            double fRed = 255.0-1.5*sqrt((double)(nX*nX+nY*nY));
            if( fRed < 0.0 )
                fRed = 0.0;
            double fGreen = 255.0-1.5*sqrt((double)(((255-nX)*(255-nX)+nY*nY)));
            if( fGreen < 0.0 )
                fGreen = 0.0;
            double fBlue = 255.0-1.5*sqrt((double)((128-nX)*(128-nX)+(255-nY)*(255-nY)));
            if( fBlue < 0.0 )
                fBlue = 0.0;
            pAcc->SetPixel( nY, nX, BitmapColor( sal_uInt8(fRed), sal_uInt8(fGreen), sal_uInt8(fBlue) ) );
        }
    }
    m_aBitmap.ReleaseAccess( pAcc );
}

void MyWin::MouseMove( const MouseEvent& rMEvt )
{
    WorkWindow::MouseMove( rMEvt );
}

void MyWin::MouseButtonDown( const MouseEvent& rMEvt )
{
    WorkWindow::MouseButtonDown( rMEvt );
}

void MyWin::MouseButtonUp( const MouseEvent& rMEvt )
{
    WorkWindow::MouseButtonUp( rMEvt );
}

void MyWin::KeyInput( const KeyEvent& rKEvt )
{
    WorkWindow::KeyInput( rKEvt );
}

void MyWin::KeyUp( const KeyEvent& rKEvt )
{
    WorkWindow::KeyUp( rKEvt );
}

static Point project( const Point& rPoint )
{
    const double angle_x = M_PI / 6.0;
    const double angle_z = M_PI / 6.0;

    // transform planar coordinates to 3d
    double x = rPoint.X();
    double y = rPoint.Y();

    // rotate around X axis
    double x1 = x;
    double y1 = y * cos( angle_x );
    double z1 = y * sin( angle_x );

    // rotate around Z axis
    double x2 = x1 * cos( angle_z ) + y1 * sin( angle_z );
    //double y2 = y1 * cos( angle_z ) - x1 * sin( angle_z );
    double z2 = z1;

    return Point( (sal_Int32)x2, (sal_Int32)z2 );
}

static Color approachColor( const Color& rFrom, const Color& rTo )
{
    Color aColor;
    sal_uInt8 nDiff;
    // approach red
    if( rFrom.GetRed() < rTo.GetRed() )
    {
        nDiff = rTo.GetRed() - rFrom.GetRed();
        aColor.SetRed( rFrom.GetRed() + ( nDiff < 10 ? nDiff : 10 ) );
    }
    else if( rFrom.GetRed() > rTo.GetRed() )
    {
        nDiff = rFrom.GetRed() - rTo.GetRed();
        aColor.SetRed( rFrom.GetRed() - ( nDiff < 10 ? nDiff : 10 ) );
    }
    else
        aColor.SetRed( rFrom.GetRed() );

    // approach Green
    if( rFrom.GetGreen() < rTo.GetGreen() )
    {
        nDiff = rTo.GetGreen() - rFrom.GetGreen();
        aColor.SetGreen( rFrom.GetGreen() + ( nDiff < 10 ? nDiff : 10 ) );
    }
    else if( rFrom.GetGreen() > rTo.GetGreen() )
    {
        nDiff = rFrom.GetGreen() - rTo.GetGreen();
        aColor.SetGreen( rFrom.GetGreen() - ( nDiff < 10 ? nDiff : 10 ) );
    }
    else
        aColor.SetGreen( rFrom.GetGreen() );

    // approach blue
    if( rFrom.GetBlue() < rTo.GetBlue() )
    {
        nDiff = rTo.GetBlue() - rFrom.GetBlue();
        aColor.SetBlue( rFrom.GetBlue() + ( nDiff < 10 ? nDiff : 10 ) );
    }
    else if( rFrom.GetBlue() > rTo.GetBlue() )
    {
        nDiff = rFrom.GetBlue() - rTo.GetBlue();
        aColor.SetBlue( rFrom.GetBlue() - ( nDiff < 10 ? nDiff : 10 ) );
    }
    else
        aColor.SetBlue( rFrom.GetBlue() );

    return aColor;
}

#define DELTA 5.0
void MyWin::Paint( const Rectangle& rRect )
{
    WorkWindow::Paint( rRect );

    Push( PushFlags::ALL );
    MapMode aMapMode( MAP_100TH_MM );

    SetMapMode( aMapMode );

    Size aPaperSize = GetOutputSize();
    Point aCenter( aPaperSize.Width()/2-300,
                   (aPaperSize.Height() - 8400)/2 + 8400 );
    Point aP1( aPaperSize.Width()/48, 0), aP2( aPaperSize.Width()/40, 0 ), aPoint;

    DrawRect( Rectangle( Point( 0,0 ), aPaperSize ) );
    DrawRect( Rectangle( Point( 100,100 ),
                         Size( aPaperSize.Width()-200,
                               aPaperSize.Height()-200 ) ) );
    DrawRect( Rectangle( Point( 200,200 ),
                         Size( aPaperSize.Width()-400,
                               aPaperSize.Height()-400 ) ) );
    DrawRect( Rectangle( Point( 300,300 ),
                         Size( aPaperSize.Width()-600,
                               aPaperSize.Height()-600 ) ) );

    const int nFontCount = GetDevFontCount();
    const int nFontSamples = (nFontCount<15) ? nFontCount : 15;
    for( int i = 0; i < nFontSamples; ++i )
    {

        vcl::FontInfo aFont = GetDevFont( (i*nFontCount) / nFontSamples );
        aFont.SetHeight( 400 + (i%7) * 100 );
        aFont.SetOrientation( i * (3600 / nFontSamples) );
        SetFont( aFont );

        sal_uInt8 nRed   = (i << 6) & 0xC0;
        sal_uInt8 nGreen = (i << 4) & 0xC0;
        sal_uInt8 nBlue  = (i << 2) & 0xC0;
        SetTextColor( Color( nRed, nGreen, nBlue ) );

        OUStringBuffer aPrintText(1024);
        long nMaxWidth = 0;

        aPrintText.appendAscii( "SVP test program" );

        DrawText( Rectangle( Point( (aPaperSize.Width() - 4000) / 2, 2000 ),
                            Size( aPaperSize.Width() - 2100 - nMaxWidth,
                                aPaperSize.Height() - 4000 ) ),
                aPrintText.makeStringAndClear(),
                TEXT_DRAW_MULTILINE );
    }

    SetFillColor();
    DrawRect( Rectangle( Point( aPaperSize.Width() - 4000, 1000 ),
                         Size( 3000,3000 ) ) );
    DrawBitmap( Point( aPaperSize.Width() - 4000, 1000 ),
                Size( 3000,3000 ),
                m_aBitmap );

    Color aWhite( 0xff, 0xff, 0xff );
    Color aBlack( 0, 0, 0 );
    Color aLightRed( 0xff, 0, 0 );
    Color aDarkRed( 0x40, 0, 0 );
    Color aLightBlue( 0, 0, 0xff );
    Color aDarkBlue( 0,0,0x40 );
    Color aLightGreen( 0, 0xff, 0 );
    Color aDarkGreen( 0, 0x40, 0 );

    Gradient aGradient( GradientStyle_LINEAR, aBlack, aWhite );
    aGradient.SetAngle( 900 );
    DrawGradient( Rectangle( Point( 1000, 4500 ),
                             Size( aPaperSize.Width() - 2000,
                                   500 ) ), aGradient );
    aGradient.SetStartColor( aDarkRed );
    aGradient.SetEndColor( aLightBlue );
    DrawGradient( Rectangle( Point( 1000, 5300 ),
                             Size( aPaperSize.Width() - 2000,
                                   500 ) ), aGradient );
    aGradient.SetStartColor( aDarkBlue );
    aGradient.SetEndColor( aLightGreen );
    DrawGradient( Rectangle( Point( 1000, 6100 ),
                             Size( aPaperSize.Width() - 2000,
                                   500 ) ), aGradient );
    aGradient.SetStartColor( aDarkGreen );
    aGradient.SetEndColor( aLightRed );
    DrawGradient( Rectangle( Point( 1000, 6900 ),
                             Size( aPaperSize.Width() - 2000,
                                   500 ) ), aGradient );

    LineInfo aLineInfo( LINE_SOLID, 200 );
    double sind = sin( DELTA*M_PI/180.0 );
    double cosd = cos( DELTA*M_PI/180.0 );
    double factor = 1 + (DELTA/1000.0);
    int n=0;
    Color aLineColor( 0, 0, 0 );
    Color aApproachColor( 0, 0, 200 );
    while ( aP2.X() < aCenter.X() && n++ < 680 )
    {
        aLineInfo.SetWidth( n/3 );
        aLineColor = approachColor( aLineColor, aApproachColor );
        SetLineColor( aLineColor );

        // switch aproach color
        if( aApproachColor.IsRGBEqual( aLineColor ) )
        {
            if( aApproachColor.GetRed() )
                aApproachColor = Color( 0, 0, 200 );
            else if( aApproachColor.GetGreen() )
                aApproachColor = Color( 200, 0, 0 );
            else
                aApproachColor = Color( 0, 200, 0 );
        }

        DrawLine( project( aP1 ) + aCenter,
                  project( aP2 ) + aCenter,
                  aLineInfo );
        aPoint.X() = (int)((((double)aP1.X())*cosd - ((double)aP1.Y())*sind)*factor);
        aPoint.Y() = (int)((((double)aP1.Y())*cosd + ((double)aP1.X())*sind)*factor);
        aP1 = aPoint;
        aPoint.X() = (int)((((double)aP2.X())*cosd - ((double)aP2.Y())*sind)*factor);
        aPoint.Y() = (int)((((double)aP2.Y())*cosd + ((double)aP2.X())*sind)*factor);
        aP2 = aPoint;
    }
    Pop();
}

void MyWin::Resize()
{
    WorkWindow::Resize();
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>coverity#1215391 Uncaught exception<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you 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 .
 */

#include <sal/main.h>
#include <tools/extendapplicationenvironment.hxx>

#include <cppuhelper/bootstrap.hxx>
#include <comphelper/processfactory.hxx>

#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#include <com/sun/star/uno/XComponentContext.hpp>

#include <vcl/event.hxx>
#include <vcl/svapp.hxx>
#include <vcl/wrkwin.hxx>
#include <vcl/gradient.hxx>
#include <vcl/lineinfo.hxx>
#include <vcl/bitmap.hxx>
#include <vcl/bmpacc.hxx>
#include <vcl/metric.hxx>

#include <rtl/ustrbuf.hxx>

#include <math.h>

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

// Forward declaration
void Main();

SAL_IMPLEMENT_MAIN()
{
    try
    {
        tools::extendApplicationEnvironment();

        Reference< XComponentContext > xContext = defaultBootstrap_InitialComponentContext();
        Reference< XMultiServiceFactory > xServiceManager( xContext->getServiceManager(), UNO_QUERY );

        if( !xServiceManager.is() )
            Application::Abort( "Failed to bootstrap" );

        comphelper::setProcessServiceFactory( xServiceManager );

        InitVCL();
        ::Main();
        DeInitVCL();
    }
    catch (const Exception& e)
    {
        SAL_WARN("vcl.app", "Fatal exception: " << e.Message);
        return 1;
    }

    return 0;
}

class MyWin : public WorkWindow
{
    Bitmap      m_aBitmap;
public:
                 MyWin( vcl::Window* pParent, WinBits nWinStyle );

    virtual void MouseMove( const MouseEvent& rMEvt ) SAL_OVERRIDE;
    virtual void MouseButtonDown( const MouseEvent& rMEvt ) SAL_OVERRIDE;
    virtual void MouseButtonUp( const MouseEvent& rMEvt ) SAL_OVERRIDE;
    virtual void KeyInput( const KeyEvent& rKEvt ) SAL_OVERRIDE;
    virtual void KeyUp( const KeyEvent& rKEvt ) SAL_OVERRIDE;
    virtual void Paint( const Rectangle& rRect ) SAL_OVERRIDE;
    virtual void Resize() SAL_OVERRIDE;
};

void Main()
{
    MyWin aMainWin( NULL, WB_APP | WB_STDWORK );
    aMainWin.SetText( OUString( "VCL - Workbench" ) );
    aMainWin.Show();

    Application::Execute();
}

MyWin::MyWin( vcl::Window* pParent, WinBits nWinStyle ) :
    WorkWindow( pParent, nWinStyle ),
    m_aBitmap( Size( 256, 256 ), 32 )
{
    // prepare an alpha mask
    BitmapWriteAccess* pAcc = m_aBitmap.AcquireWriteAccess();
    for( int nX = 0; nX < 256; nX++ )
    {
        for( int nY = 0; nY < 256; nY++ )
        {
            double fRed = 255.0-1.5*sqrt((double)(nX*nX+nY*nY));
            if( fRed < 0.0 )
                fRed = 0.0;
            double fGreen = 255.0-1.5*sqrt((double)(((255-nX)*(255-nX)+nY*nY)));
            if( fGreen < 0.0 )
                fGreen = 0.0;
            double fBlue = 255.0-1.5*sqrt((double)((128-nX)*(128-nX)+(255-nY)*(255-nY)));
            if( fBlue < 0.0 )
                fBlue = 0.0;
            pAcc->SetPixel( nY, nX, BitmapColor( sal_uInt8(fRed), sal_uInt8(fGreen), sal_uInt8(fBlue) ) );
        }
    }
    m_aBitmap.ReleaseAccess( pAcc );
}

void MyWin::MouseMove( const MouseEvent& rMEvt )
{
    WorkWindow::MouseMove( rMEvt );
}

void MyWin::MouseButtonDown( const MouseEvent& rMEvt )
{
    WorkWindow::MouseButtonDown( rMEvt );
}

void MyWin::MouseButtonUp( const MouseEvent& rMEvt )
{
    WorkWindow::MouseButtonUp( rMEvt );
}

void MyWin::KeyInput( const KeyEvent& rKEvt )
{
    WorkWindow::KeyInput( rKEvt );
}

void MyWin::KeyUp( const KeyEvent& rKEvt )
{
    WorkWindow::KeyUp( rKEvt );
}

static Point project( const Point& rPoint )
{
    const double angle_x = M_PI / 6.0;
    const double angle_z = M_PI / 6.0;

    // transform planar coordinates to 3d
    double x = rPoint.X();
    double y = rPoint.Y();

    // rotate around X axis
    double x1 = x;
    double y1 = y * cos( angle_x );
    double z1 = y * sin( angle_x );

    // rotate around Z axis
    double x2 = x1 * cos( angle_z ) + y1 * sin( angle_z );
    //double y2 = y1 * cos( angle_z ) - x1 * sin( angle_z );
    double z2 = z1;

    return Point( (sal_Int32)x2, (sal_Int32)z2 );
}

static Color approachColor( const Color& rFrom, const Color& rTo )
{
    Color aColor;
    sal_uInt8 nDiff;
    // approach red
    if( rFrom.GetRed() < rTo.GetRed() )
    {
        nDiff = rTo.GetRed() - rFrom.GetRed();
        aColor.SetRed( rFrom.GetRed() + ( nDiff < 10 ? nDiff : 10 ) );
    }
    else if( rFrom.GetRed() > rTo.GetRed() )
    {
        nDiff = rFrom.GetRed() - rTo.GetRed();
        aColor.SetRed( rFrom.GetRed() - ( nDiff < 10 ? nDiff : 10 ) );
    }
    else
        aColor.SetRed( rFrom.GetRed() );

    // approach Green
    if( rFrom.GetGreen() < rTo.GetGreen() )
    {
        nDiff = rTo.GetGreen() - rFrom.GetGreen();
        aColor.SetGreen( rFrom.GetGreen() + ( nDiff < 10 ? nDiff : 10 ) );
    }
    else if( rFrom.GetGreen() > rTo.GetGreen() )
    {
        nDiff = rFrom.GetGreen() - rTo.GetGreen();
        aColor.SetGreen( rFrom.GetGreen() - ( nDiff < 10 ? nDiff : 10 ) );
    }
    else
        aColor.SetGreen( rFrom.GetGreen() );

    // approach blue
    if( rFrom.GetBlue() < rTo.GetBlue() )
    {
        nDiff = rTo.GetBlue() - rFrom.GetBlue();
        aColor.SetBlue( rFrom.GetBlue() + ( nDiff < 10 ? nDiff : 10 ) );
    }
    else if( rFrom.GetBlue() > rTo.GetBlue() )
    {
        nDiff = rFrom.GetBlue() - rTo.GetBlue();
        aColor.SetBlue( rFrom.GetBlue() - ( nDiff < 10 ? nDiff : 10 ) );
    }
    else
        aColor.SetBlue( rFrom.GetBlue() );

    return aColor;
}

#define DELTA 5.0
void MyWin::Paint( const Rectangle& rRect )
{
    WorkWindow::Paint( rRect );

    Push( PushFlags::ALL );
    MapMode aMapMode( MAP_100TH_MM );

    SetMapMode( aMapMode );

    Size aPaperSize = GetOutputSize();
    Point aCenter( aPaperSize.Width()/2-300,
                   (aPaperSize.Height() - 8400)/2 + 8400 );
    Point aP1( aPaperSize.Width()/48, 0), aP2( aPaperSize.Width()/40, 0 ), aPoint;

    DrawRect( Rectangle( Point( 0,0 ), aPaperSize ) );
    DrawRect( Rectangle( Point( 100,100 ),
                         Size( aPaperSize.Width()-200,
                               aPaperSize.Height()-200 ) ) );
    DrawRect( Rectangle( Point( 200,200 ),
                         Size( aPaperSize.Width()-400,
                               aPaperSize.Height()-400 ) ) );
    DrawRect( Rectangle( Point( 300,300 ),
                         Size( aPaperSize.Width()-600,
                               aPaperSize.Height()-600 ) ) );

    const int nFontCount = GetDevFontCount();
    const int nFontSamples = (nFontCount<15) ? nFontCount : 15;
    for( int i = 0; i < nFontSamples; ++i )
    {

        vcl::FontInfo aFont = GetDevFont( (i*nFontCount) / nFontSamples );
        aFont.SetHeight( 400 + (i%7) * 100 );
        aFont.SetOrientation( i * (3600 / nFontSamples) );
        SetFont( aFont );

        sal_uInt8 nRed   = (i << 6) & 0xC0;
        sal_uInt8 nGreen = (i << 4) & 0xC0;
        sal_uInt8 nBlue  = (i << 2) & 0xC0;
        SetTextColor( Color( nRed, nGreen, nBlue ) );

        OUStringBuffer aPrintText(1024);
        long nMaxWidth = 0;

        aPrintText.appendAscii( "SVP test program" );

        DrawText( Rectangle( Point( (aPaperSize.Width() - 4000) / 2, 2000 ),
                            Size( aPaperSize.Width() - 2100 - nMaxWidth,
                                aPaperSize.Height() - 4000 ) ),
                aPrintText.makeStringAndClear(),
                TEXT_DRAW_MULTILINE );
    }

    SetFillColor();
    DrawRect( Rectangle( Point( aPaperSize.Width() - 4000, 1000 ),
                         Size( 3000,3000 ) ) );
    DrawBitmap( Point( aPaperSize.Width() - 4000, 1000 ),
                Size( 3000,3000 ),
                m_aBitmap );

    Color aWhite( 0xff, 0xff, 0xff );
    Color aBlack( 0, 0, 0 );
    Color aLightRed( 0xff, 0, 0 );
    Color aDarkRed( 0x40, 0, 0 );
    Color aLightBlue( 0, 0, 0xff );
    Color aDarkBlue( 0,0,0x40 );
    Color aLightGreen( 0, 0xff, 0 );
    Color aDarkGreen( 0, 0x40, 0 );

    Gradient aGradient( GradientStyle_LINEAR, aBlack, aWhite );
    aGradient.SetAngle( 900 );
    DrawGradient( Rectangle( Point( 1000, 4500 ),
                             Size( aPaperSize.Width() - 2000,
                                   500 ) ), aGradient );
    aGradient.SetStartColor( aDarkRed );
    aGradient.SetEndColor( aLightBlue );
    DrawGradient( Rectangle( Point( 1000, 5300 ),
                             Size( aPaperSize.Width() - 2000,
                                   500 ) ), aGradient );
    aGradient.SetStartColor( aDarkBlue );
    aGradient.SetEndColor( aLightGreen );
    DrawGradient( Rectangle( Point( 1000, 6100 ),
                             Size( aPaperSize.Width() - 2000,
                                   500 ) ), aGradient );
    aGradient.SetStartColor( aDarkGreen );
    aGradient.SetEndColor( aLightRed );
    DrawGradient( Rectangle( Point( 1000, 6900 ),
                             Size( aPaperSize.Width() - 2000,
                                   500 ) ), aGradient );

    LineInfo aLineInfo( LINE_SOLID, 200 );
    double sind = sin( DELTA*M_PI/180.0 );
    double cosd = cos( DELTA*M_PI/180.0 );
    double factor = 1 + (DELTA/1000.0);
    int n=0;
    Color aLineColor( 0, 0, 0 );
    Color aApproachColor( 0, 0, 200 );
    while ( aP2.X() < aCenter.X() && n++ < 680 )
    {
        aLineInfo.SetWidth( n/3 );
        aLineColor = approachColor( aLineColor, aApproachColor );
        SetLineColor( aLineColor );

        // switch aproach color
        if( aApproachColor.IsRGBEqual( aLineColor ) )
        {
            if( aApproachColor.GetRed() )
                aApproachColor = Color( 0, 0, 200 );
            else if( aApproachColor.GetGreen() )
                aApproachColor = Color( 200, 0, 0 );
            else
                aApproachColor = Color( 0, 200, 0 );
        }

        DrawLine( project( aP1 ) + aCenter,
                  project( aP2 ) + aCenter,
                  aLineInfo );
        aPoint.X() = (int)((((double)aP1.X())*cosd - ((double)aP1.Y())*sind)*factor);
        aPoint.Y() = (int)((((double)aP1.Y())*cosd + ((double)aP1.X())*sind)*factor);
        aP1 = aPoint;
        aPoint.X() = (int)((((double)aP2.X())*cosd - ((double)aP2.Y())*sind)*factor);
        aPoint.Y() = (int)((((double)aP2.Y())*cosd + ((double)aP2.X())*sind)*factor);
        aP2 = aPoint;
    }
    Pop();
}

void MyWin::Resize()
{
    WorkWindow::Resize();
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: vcldemo.cxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: rt $ $Date: 2007-07-05 15:56:47 $
 *
 *  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_vcl.hxx"

#include <sal/main.h>
#include <com/sun/star/lang/XMultiServiceFactory.hpp>

#include <vcl/event.hxx>
#include <vcl/svapp.hxx>
#include <vcl/wrkwin.hxx>
#include <vcl/msgbox.hxx>
#include <vcl/introwin.hxx>
#include <vcl/msgbox.hxx>

#include <comphelper/processfactory.hxx>
#include <cppuhelper/servicefactory.hxx>
#include <cppuhelper/bootstrap.hxx>

#include <unistd.h>
#include <stdio.h>

using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;
// -----------------------------------------------------------------------

// Forward declaration
void Main();

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

SAL_IMPLEMENT_MAIN()
{
    Reference< XMultiServiceFactory > xMS;
    xMS = cppu::createRegistryServiceFactory( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "applicat.rdb" ) ), sal_True );

    InitVCL( xMS );
    ::Main();
    DeInitVCL();

    return 0;
}

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

class MyWin : public WorkWindow
{
public:
                MyWin( Window* pParent, WinBits nWinStyle );

    void        MouseMove( const MouseEvent& rMEvt );
    void        MouseButtonDown( const MouseEvent& rMEvt );
    void        MouseButtonUp( const MouseEvent& rMEvt );
    void        KeyInput( const KeyEvent& rKEvt );
    void        KeyUp( const KeyEvent& rKEvt );
    void        Paint( const Rectangle& rRect );
    void        Resize();
};

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

void Main()
{
    /*
    IntroWindow splash;
    splash.Show();
    sleep(5);
    splash.Hide();
    */

    MyWin aMainWin( NULL, WB_APP | WB_STDWORK );
    aMainWin.SetText( XubString( RTL_CONSTASCII_USTRINGPARAM( "VCLDemo - VCL Workbench" ) ) );
    aMainWin.Show();

    /*
    InfoBox ib(NULL, String((sal_Char*)"Test", sizeof("Test")));
    ib.Execute();
    */

    Application::Execute();
}

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

MyWin::MyWin( Window* pParent, WinBits nWinStyle ) :
    WorkWindow( pParent, nWinStyle )
{
}

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

void MyWin::MouseMove( const MouseEvent& rMEvt )
{
    WorkWindow::MouseMove( rMEvt );
}

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

void MyWin::MouseButtonDown( const MouseEvent& rMEvt )
{
    Rectangle aRect(0,0,4,4);
    aRect.SetPos( rMEvt.GetPosPixel() );
    SetFillColor(Color(COL_RED));
    DrawRect( aRect );
}

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

void MyWin::MouseButtonUp( const MouseEvent& rMEvt )
{
    WorkWindow::MouseButtonUp( rMEvt );
}

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

void MyWin::KeyInput( const KeyEvent& rKEvt )
{
    WorkWindow::KeyInput( rKEvt );
}

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

void MyWin::KeyUp( const KeyEvent& rKEvt )
{
    WorkWindow::KeyUp( rKEvt );
}

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

void MyWin::Paint( const Rectangle& rRect )
{
    fprintf(stderr, "MyWin::Paint(%ld,%ld,%ld,%ld)\n", rRect.getX(), rRect.getY(), rRect.getWidth(), rRect.getHeight());

    Size aSz(GetSizePixel());
    Point aPt;
    Rectangle r(aPt, aSz);

    SetFillColor(Color(COL_BLUE));
    SetLineColor(Color(COL_YELLOW));

    DrawRect( r );

    for(int i=0; i<aSz.Height(); i+=15)
        DrawLine( Point(r.nLeft, r.nTop+i), Point(r.nRight, r.nBottom-i) );
    for(int i=0; i<aSz.Width(); i+=15)
        DrawLine( Point(r.nLeft+i, r.nBottom), Point(r.nRight-i, r.nTop) );
}

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

void MyWin::Resize()
{
    WorkWindow::Resize();
}
<commit_msg>INTEGRATION: CWS aquavcl03 (1.3.4); FILE MERGED 2007/07/26 11:02:27 pl 1.3.4.1: #i80025# initial checking for carbon to cocoa migration<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: vcldemo.cxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: kz $ $Date: 2007-10-09 15:22:43 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

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

#include <sal/main.h>
#include <com/sun/star/lang/XMultiServiceFactory.hpp>

#include <vcl/event.hxx>
#include <vcl/svapp.hxx>
#include <vcl/wrkwin.hxx>
#include <vcl/msgbox.hxx>
#include <vcl/introwin.hxx>
#include <vcl/msgbox.hxx>

#include <comphelper/processfactory.hxx>
#include <cppuhelper/servicefactory.hxx>
#include <cppuhelper/bootstrap.hxx>

#include <unistd.h>
#include <stdio.h>

using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;
// -----------------------------------------------------------------------

// Forward declaration
void Main();

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

SAL_IMPLEMENT_MAIN()
{
    Reference< XMultiServiceFactory > xMS;
    xMS = cppu::createRegistryServiceFactory( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "applicat.rdb" ) ), sal_True );

    InitVCL( xMS );
    ::Main();
    DeInitVCL();

    return 0;
}

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

class MyWin : public WorkWindow
{
public:
                MyWin( Window* pParent, WinBits nWinStyle );

    void        MouseMove( const MouseEvent& rMEvt );
    void        MouseButtonDown( const MouseEvent& rMEvt );
    void        MouseButtonUp( const MouseEvent& rMEvt );
    void        KeyInput( const KeyEvent& rKEvt );
    void        KeyUp( const KeyEvent& rKEvt );
    void        Paint( const Rectangle& rRect );
    void        Resize();
};

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

void Main()
{
    /*
    IntroWindow splash;
    splash.Show();
    sleep(5);
    splash.Hide();
    */

    MyWin aMainWin( NULL, WB_APP | WB_STDWORK );
    aMainWin.SetText( XubString( RTL_CONSTASCII_USTRINGPARAM( "VCLDemo - VCL Workbench" ) ) );
    aMainWin.Show();

    /*
    InfoBox ib(NULL, String((sal_Char*)"Test", sizeof("Test")));
    ib.Execute();
    */

    Application::Execute();
}

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

MyWin::MyWin( Window* pParent, WinBits nWinStyle ) :
    WorkWindow( pParent, nWinStyle )
{
}

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

void MyWin::MouseMove( const MouseEvent& rMEvt )
{
    WorkWindow::MouseMove( rMEvt );
}

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

void MyWin::MouseButtonDown( const MouseEvent& rMEvt )
{
    Rectangle aRect(0,0,4,4);
    aRect.SetPos( rMEvt.GetPosPixel() );
    SetFillColor(Color(COL_RED));
    DrawRect( aRect );
}

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

void MyWin::MouseButtonUp( const MouseEvent& rMEvt )
{
    WorkWindow::MouseButtonUp( rMEvt );
}

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

void MyWin::KeyInput( const KeyEvent& rKEvt )
{
    WorkWindow::KeyInput( rKEvt );
}

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

void MyWin::KeyUp( const KeyEvent& rKEvt )
{
    WorkWindow::KeyUp( rKEvt );
}

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

void MyWin::Paint( const Rectangle& rRect )
{
    fprintf(stderr, "MyWin::Paint(%ld,%ld,%ld,%ld)\n", rRect.getX(), rRect.getY(), rRect.getWidth(), rRect.getHeight());

    Size aSz(GetSizePixel());
    Point aPt;
    Rectangle r(aPt, aSz);

    SetFillColor(Color(COL_BLUE));
    SetLineColor(Color(COL_YELLOW));

    DrawRect( r );

    for(int i=0; i<aSz.Height(); i+=15)
        DrawLine( Point(r.nLeft, r.nTop+i), Point(r.nRight, r.nBottom-i) );
    for(int i=0; i<aSz.Width(); i+=15)
        DrawLine( Point(r.nLeft+i, r.nBottom), Point(r.nRight-i, r.nTop) );

    SetTextColor( Color( COL_WHITE ) );
    Font aFont( String( RTL_CONSTASCII_USTRINGPARAM( "Times" ) ), Size( 0, 25 ) );
    SetFont( aFont );
    DrawText( Point( 20, 30 ), String( RTL_CONSTASCII_USTRINGPARAM( "Just a simple test text" ) ) );
}

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

void MyWin::Resize()
{
    WorkWindow::Resize();
}
<|endoftext|>


<commit_before><commit_msg>use different line and fill colors<commit_after><|endoftext|>