<commit_before>/*************************************************************************
 *
 *  $RCSfile: cusshow.cxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: aw $ $Date: 2001-08-06 08:34:08 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 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
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#pragma hdrstop

#ifndef _COM_SUN_STAR_LANG_XCOMPONENT_HPP_
#include <com/sun/star/lang/XComponent.hpp>
#endif

#include "sdiocmpt.hxx"
#include "cusshow.hxx"
#include "sdpage.hxx"
#include "drawdoc.hxx"

// #90477#
#ifndef _TOOLS_TENCCVT_HXX
#include <tools/tenccvt.hxx>
#endif

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

/*************************************************************************
|*
|* Ctor
|*
\************************************************************************/
SdCustomShow::SdCustomShow(SdDrawDocument* pDrawDoc)
  : List(),
  pDoc(pDrawDoc)
{
}

/*************************************************************************
|*
|* Copy-Ctor
|*
\************************************************************************/
SdCustomShow::SdCustomShow( const SdCustomShow& rShow )
    : List( rShow )
{
    aName = rShow.GetName();
    pDoc = rShow.GetDoc();
}

SdCustomShow::SdCustomShow(SdDrawDocument* pDrawDoc, ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > xShow )
  : List(),
  pDoc(pDrawDoc),
  mxUnoCustomShow( xShow )
{
}

/*************************************************************************
|*
|* Dtor
|*
\************************************************************************/
SdCustomShow::~SdCustomShow()
{
    uno::Reference< uno::XInterface > xShow( mxUnoCustomShow );
    uno::Reference< lang::XComponent > xComponent( xShow, uno::UNO_QUERY );
    if( xComponent.is() )
        xComponent->dispose();
}

/*************************************************************************
|*
|* Inserter fuer SvStream zum Speichern
|*
\************************************************************************/
SvStream& operator << (SvStream& rOut, const SdCustomShow& rCustomShow)
{
    // Letzter Parameter ist die aktuelle Versionsnummer des Codes
    SdIOCompat aIO(rOut, STREAM_WRITE, 0);

    // Name
    // #90477# rOut.WriteByteString( rCustomShow.aName, ::GetStoreCharSet( gsl_getSystemTextEncoding() ) );
    rOut.WriteByteString(rCustomShow.aName,
        GetSOStoreTextEncoding(gsl_getSystemTextEncoding(), (sal_uInt16)rOut.GetVersion()));

    // Anzahl Seiten
    UINT32 nCount = rCustomShow.Count();
    rOut << nCount;

    for (UINT32 i = 0; i < nCount; i++)
    {
        // Seite aus Liste holen
        SdPage* pPage = (SdPage*) rCustomShow.GetObject(i);

        if (pPage)
        {
            // SdPage-Seitennummer
            UINT16 nPageNum = (pPage->GetPageNum() - 1) / 2;
            rOut << nPageNum;
        }
    }

    return rOut;
}

/*************************************************************************
|*
|* Extractor fuer SvStream zum Laden
|*
\************************************************************************/
SvStream& operator >> (SvStream& rIn, SdCustomShow& rCustomShow)
{
    SdIOCompat aIO(rIn, STREAM_READ);

    // Name
    // #90477# rIn.ReadByteString( rCustomShow.aName, ::GetStoreCharSet( gsl_getSystemTextEncoding() ) );
    rIn.ReadByteString(rCustomShow.aName,
        GetSOLoadTextEncoding(gsl_getSystemTextEncoding(), (sal_uInt16)rIn.GetVersion()));

    // Anzahl Seiten
    UINT32 nCount = 0;
    rIn >> nCount;

    rCustomShow.Clear();

    for (UINT32 i = 0; i < nCount; i++)
    {
        // Seitennummer
        UINT16 nPageNum;
        rIn >> nPageNum;

        // Seite in Liste einfuegen
        SdPage* pPage = (SdPage*) rCustomShow.pDoc->GetSdPage(nPageNum, PK_STANDARD);
        rCustomShow.Insert(pPage, LIST_APPEND);
    }

    return rIn;
}

extern uno::Reference< uno::XInterface > createUnoCustomShow( SdCustomShow* pShow );

uno::Reference< uno::XInterface > SdCustomShow::getUnoCustomShow()
{
    // try weak reference first
    uno::Reference< uno::XInterface > xShow( mxUnoCustomShow );

    if( !xShow.is() )
    {
        xShow = createUnoCustomShow( this );
    }

    return xShow;
}
<commit_msg>INTEGRATION: CWS aw019 (1.4.564); FILE MERGED 2004/09/29 14:30:12 aw 1.4.564.1: #i11190#<commit_after>/*************************************************************************
 *
 *  $RCSfile: cusshow.cxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: pjunck $ $Date: 2004-11-03 08:52:59 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 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
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#pragma hdrstop

#ifndef _COM_SUN_STAR_LANG_XCOMPONENT_HPP_
#include <com/sun/star/lang/XComponent.hpp>
#endif

#include "sdiocmpt.hxx"
#include "cusshow.hxx"
#include "sdpage.hxx"
#include "drawdoc.hxx"

// #90477#
#ifndef _TOOLS_TENCCVT_HXX
#include <tools/tenccvt.hxx>
#endif

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

/*************************************************************************
|*
|* Ctor
|*
\************************************************************************/
SdCustomShow::SdCustomShow(SdDrawDocument* pDrawDoc)
  : List(),
  pDoc(pDrawDoc)
{
}

/*************************************************************************
|*
|* Copy-Ctor
|*
\************************************************************************/
SdCustomShow::SdCustomShow( const SdCustomShow& rShow )
    : List( rShow )
{
    aName = rShow.GetName();
    pDoc = rShow.GetDoc();
}

SdCustomShow::SdCustomShow(SdDrawDocument* pDrawDoc, ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > xShow )
  : List(),
  pDoc(pDrawDoc),
  mxUnoCustomShow( xShow )
{
}

/*************************************************************************
|*
|* Dtor
|*
\************************************************************************/
SdCustomShow::~SdCustomShow()
{
    uno::Reference< uno::XInterface > xShow( mxUnoCustomShow );
    uno::Reference< lang::XComponent > xComponent( xShow, uno::UNO_QUERY );
    if( xComponent.is() )
        xComponent->dispose();
}

/*************************************************************************
|*
|* Inserter fuer SvStream zum Speichern
|*
\************************************************************************/
//BFS02SvStream& operator << (SvStream& rOut, const SdCustomShow& rCustomShow)
//BFS02{
//BFS02 // Letzter Parameter ist die aktuelle Versionsnummer des Codes
//BFS02 SdIOCompat aIO(rOut, STREAM_WRITE, 0);
//BFS02
//BFS02 // Name
//BFS02 // #90477# rOut.WriteByteString( rCustomShow.aName, ::GetStoreCharSet( gsl_getSystemTextEncoding() ) );
//BFS02 rOut.WriteByteString(rCustomShow.aName,
//BFS02     GetSOStoreTextEncoding(gsl_getSystemTextEncoding(), (sal_uInt16)rOut.GetVersion()));
//BFS02
//BFS02 // Anzahl Seiten
//BFS02 UINT32 nCount = rCustomShow.Count();
//BFS02 rOut << nCount;
//BFS02
//BFS02 for (UINT32 i = 0; i < nCount; i++)
//BFS02 {
//BFS02     // Seite aus Liste holen
//BFS02     SdPage* pPage = (SdPage*) rCustomShow.GetObject(i);
//BFS02
//BFS02     if (pPage)
//BFS02     {
//BFS02         // SdPage-Seitennummer
//BFS02         UINT16 nPageNum = (pPage->GetPageNum() - 1) / 2;
//BFS02         rOut << nPageNum;
//BFS02     }
//BFS02 }
//BFS02
//BFS02 return rOut;
//BFS02}

/*************************************************************************
|*
|* Extractor fuer SvStream zum Laden
|*
\************************************************************************/
//BFS02SvStream& operator >> (SvStream& rIn, SdCustomShow& rCustomShow)
//BFS02{
//BFS02 SdIOCompat aIO(rIn, STREAM_READ);
//BFS02
//BFS02 // Name
//BFS02 // #90477# rIn.ReadByteString( rCustomShow.aName, ::GetStoreCharSet( gsl_getSystemTextEncoding() ) );
//BFS02 rIn.ReadByteString(rCustomShow.aName,
//BFS02     GetSOLoadTextEncoding(gsl_getSystemTextEncoding(), (sal_uInt16)rIn.GetVersion()));
//BFS02
//BFS02 // Anzahl Seiten
//BFS02 UINT32 nCount = 0;
//BFS02 rIn >> nCount;
//BFS02
//BFS02 rCustomShow.Clear();
//BFS02
//BFS02 for (UINT32 i = 0; i < nCount; i++)
//BFS02 {
//BFS02     // Seitennummer
//BFS02     UINT16 nPageNum;
//BFS02     rIn >> nPageNum;
//BFS02
//BFS02     // Seite in Liste einfuegen
//BFS02     SdPage* pPage = (SdPage*) rCustomShow.pDoc->GetSdPage(nPageNum, PK_STANDARD);
//BFS02     rCustomShow.Insert(pPage, LIST_APPEND);
//BFS02 }
//BFS02
//BFS02 return rIn;
//BFS02}

extern uno::Reference< uno::XInterface > createUnoCustomShow( SdCustomShow* pShow );

uno::Reference< uno::XInterface > SdCustomShow::getUnoCustomShow()
{
    // try weak reference first
    uno::Reference< uno::XInterface > xShow( mxUnoCustomShow );

    if( !xShow.is() )
    {
        xShow = createUnoCustomShow( this );
    }

    return xShow;
}
<|endoftext|>


<commit_before>#include "application.h"

// POSIX++
#include <cstring> // for strerror()
#include <cstdlib> // for exit

// STL
#include <atomic>
#include <list>

// PUT
#include <cxxutils/vterm.h>

// atomic vars are to avoid race conditions
static std::atomic_int  s_return_value;
static std::atomic_bool s_run; // quit signal

posix::lockable<std::queue<vfunc>> Application::ms_signal_queue;

static posix::fd_t s_pipeio[2] = { posix::invalid_descriptor }; //  execution stepper pipe

enum {
  Read = 0,
  Write = 1,
};

Application::Application(void) noexcept
{
  if(s_pipeio[Read] == posix::invalid_descriptor) // if execution stepper pipe  hasn't been initialized yet
  {
    flaw(!posix::pipe(s_pipeio),
         terminal::critical,
         std::exit(errno),,
         "Unable to create pipe for execution stepper: %s", std::strerror(errno))
    posix::fcntl(s_pipeio[Read], F_SETFD, FD_CLOEXEC); // close on exec*()
    posix::donotblock(s_pipeio[Read]); // don't block

    flaw(!EventBackend::add(s_pipeio[Read], EventBackend::SimplePollReadFlags, read),
         terminal::critical,
         std::exit(errno),, // watch for when execution stepper pipe has been triggered
         "Unable to watch execution stepper to backend: %s", std::strerror(errno))
  }
}

void Application::step(void) noexcept
{
  static const uint8_t dummydata = 0; // dummy content
  flaw(posix::write(s_pipeio[Write], &dummydata, 1) != 1,
       terminal::critical,
       std::exit(errno),, // triggers execution stepper FD
       "Unable to trigger Object signal queue processor: %s", std::strerror(errno))
}

// this is the callback function for the signal queue
void Application::read(posix::fd_t fd, native_flags_t) noexcept
{
  uint64_t discard;
  while(posix::read(fd, &discard, sizeof(discard)) != posix::error_response);

  // execute queue of object signal calls
  static std::queue<vfunc> exec_queue;
  if(exec_queue.empty()) // if not currently executing (recursive or multithread exec() calls?)
  {
    ms_signal_queue.lock(); // get exclusive access (make thread-safe)
    exec_queue.swap(ms_signal_queue); // swap the queues
    ms_signal_queue.unlock(); // access is no longer needed

    while(!exec_queue.empty()) // while still have object signals to execute
    {
      exec_queue.front()(); // execute current object signal/callback
      exec_queue.pop(); // discard current object signal
    }
  }
}

int Application::exec(void) noexcept // non-static function to ensure an instance of Application exists
{
  s_return_value = 0; // reinit return value
  s_run = true; // reinit execution status
  while(s_run) // while not quitting
  {
    EventBackend::poll(); // get event queue results

    for(std::pair<posix::fd_t, native_flags_t>& pair : EventBackend::results) // process results
    {
      EventBackend::queue.lock(); // get exclusive access (make thread-safe)
      auto entries = EventBackend::queue.equal_range(pair.first); // get all the entries for that FD
      std::list<std::pair<posix::fd_t, EventBackend::callback_info_t>> exec_fds(entries.first, entries.second); // copy entries
      EventBackend::queue.unlock(); // access is no longer needed

      for(std::pair<posix::fd_t, EventBackend::callback_info_t>& entry : exec_fds) // for each FD
        if(entry.second.flags & pair.second) // check if there is a matching flag
          entry.second.function(pair.first, pair.second); // invoke the callback function with the FD and triggering Flag
    }
  }
  return s_return_value; // quit() has been called, return value specified
}

void Application::quit(int return_value) noexcept // soft application exit (allows event queues to complete)
{
  if(s_run) // if not already quitting
  {
    s_return_value = return_value; // set application return value
    s_run = false; // indicate program must quit
  }
}
<commit_msg>changed my mind<commit_after>#include "application.h"

// POSIX++
#include <cstring> // for strerror()
#include <cstdlib> // for exit

// STL
#include <atomic>
#include <list>

// PUT
#include <cxxutils/vterm.h>

// atomic vars are to avoid race conditions
static std::atomic_int  s_return_value(0);
static std::atomic_bool s_run(true); // quit signal

posix::lockable<std::queue<vfunc>> Application::ms_signal_queue;

static posix::fd_t s_pipeio[2] = { posix::invalid_descriptor }; //  execution stepper pipe

enum {
  Read = 0,
  Write = 1,
};

Application::Application(void) noexcept
{
  if(s_pipeio[Read] == posix::invalid_descriptor) // if execution stepper pipe  hasn't been initialized yet
  {
    flaw(!posix::pipe(s_pipeio),
         terminal::critical,
         std::exit(errno),,
         "Unable to create pipe for execution stepper: %s", std::strerror(errno))
    posix::fcntl(s_pipeio[Read], F_SETFD, FD_CLOEXEC); // close on exec*()
    posix::donotblock(s_pipeio[Read]); // don't block

    flaw(!EventBackend::add(s_pipeio[Read], EventBackend::SimplePollReadFlags, read),
         terminal::critical,
         std::exit(errno),, // watch for when execution stepper pipe has been triggered
         "Unable to watch execution stepper to backend: %s", std::strerror(errno))
  }
}

void Application::step(void) noexcept
{
  static const uint8_t dummydata = 0; // dummy content
  flaw(posix::write(s_pipeio[Write], &dummydata, 1) != 1,
       terminal::critical,
       std::exit(errno),, // triggers execution stepper FD
       "Unable to trigger Object signal queue processor: %s", std::strerror(errno))
}

// this is the callback function for the signal queue
void Application::read(posix::fd_t fd, native_flags_t) noexcept
{
  uint64_t discard;
  while(posix::read(fd, &discard, sizeof(discard)) != posix::error_response);

  // execute queue of object signal calls
  static std::queue<vfunc> exec_queue;
  if(exec_queue.empty()) // if not currently executing (recursive or multithread exec() calls?)
  {
    ms_signal_queue.lock(); // get exclusive access (make thread-safe)
    exec_queue.swap(ms_signal_queue); // swap the queues
    ms_signal_queue.unlock(); // access is no longer needed

    while(!exec_queue.empty()) // while still have object signals to execute
    {
      exec_queue.front()(); // execute current object signal/callback
      exec_queue.pop(); // discard current object signal
    }
  }
}

int Application::exec(void) noexcept // non-static function to ensure an instance of Application exists
{
  while(s_run) // while not quitting
  {
    EventBackend::poll(); // get event queue results

    for(std::pair<posix::fd_t, native_flags_t>& pair : EventBackend::results) // process results
    {
      EventBackend::queue.lock(); // get exclusive access (make thread-safe)
      auto entries = EventBackend::queue.equal_range(pair.first); // get all the entries for that FD
      std::list<std::pair<posix::fd_t, EventBackend::callback_info_t>> exec_fds(entries.first, entries.second); // copy entries
      EventBackend::queue.unlock(); // access is no longer needed

      for(std::pair<posix::fd_t, EventBackend::callback_info_t>& entry : exec_fds) // for each FD
        if(entry.second.flags & pair.second) // check if there is a matching flag
          entry.second.function(pair.first, pair.second); // invoke the callback function with the FD and triggering Flag
    }
  }
  return s_return_value; // quit() has been called, return value specified
}

void Application::quit(int return_value) noexcept // soft application exit (allows event queues to complete)
{
  if(s_run) // if not already quitting
  {
    s_return_value = return_value; // set application return value
    s_run = false; // indicate program must quit
  }
}
<|endoftext|>


<commit_before>//
// Matirx.hpp
// ~~~~~~~~~~
//
// Copyright (c) 2014 Rick Yang (rick68 at gmail dot com)
//
// 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/.
//

#ifndef EIGENJS_MATRIX_HPP
#define EIGENJS_MATRIX_HPP

#include <node.h>
#include <v8.h>

#include <nan.h>

#include <eigen3/Eigen/Dense>

#include <sstream>

#define EIGENJS_MATRIX_BINARY_OPERATOR( NAME, OP )                             \
static NAN_METHOD( NAME ) {                                                    \
  const Matrix* obj = node::ObjectWrap::Unwrap<Matrix>( args.This() );         \
  NanScope();                                                                  \
                                                                               \
  if ( args.Length() == 1 && HasInstance( args[0] ) ) {                        \
    const Matrix* rhs_obj =                                                    \
        node::ObjectWrap::Unwrap<Matrix>( args[0]->ToObject() );               \
                                                                               \
    if ( is_nonconformate_arguments( obj, rhs_obj ) ) {                        \
      NanReturnUndefined();                                                    \
    }                                                                          \
                                                                               \
    const typename matrix_type::Index& rows = obj->matrix_.rows();             \
    const typename matrix_type::Index& cols = obj->matrix_.cols();             \
                                                                               \
    v8::Local<v8::Function> ctr = NanNew( constructor );                       \
    v8::Local<v8::Value> argv[] = {                                            \
        NanNew<v8::Integer>( rows )                                            \
      , NanNew<v8::Integer>( cols )                                            \
    };                                                                         \
                                                                               \
    v8::Local<v8::Object> new_matrix = ctr->NewInstance(                       \
        sizeof( argv ) / sizeof( v8::Local<v8::Value> )                        \
      , argv                                                                   \
    );                                                                         \
                                                                               \
    Matrix* new_obj = node::ObjectWrap::Unwrap<Matrix>( new_matrix );          \
    new_obj->matrix_ = obj->matrix_ OP rhs_obj->matrix_;                       \
                                                                               \
    NanReturnValue( new_matrix );                                              \
  }                                                                            \
                                                                               \
  NanReturnUndefined();                                                        \
}                                                                              \
/**/

#define EIGENJS_MATRIX_BINARY_OPERATOR_COMMUTATIVE( NAME, OP )                 \
static NAN_METHOD( NAME ) {                                                    \
  Matrix* obj = node::ObjectWrap::Unwrap<Matrix>( args.This() );               \
  NanScope();                                                                  \
                                                                               \
  if ( args.Length() == 1 && HasInstance( args[0] ) ) {                        \
    const Matrix* rhs_obj =                                                    \
        node::ObjectWrap::Unwrap<Matrix>( args[0]->ToObject() );               \
                                                                               \
    if ( is_nonconformate_arguments( obj, rhs_obj ) ) {                        \
      NanReturnUndefined();                                                    \
    }                                                                          \
                                                                               \
    obj->matrix_ OP##= rhs_obj->matrix_;                                       \
                                                                               \
    NanReturnValue( args.This() );                                             \
  }                                                                            \
                                                                               \
  NanReturnUndefined();                                                        \
}                                                                              \
/**/

namespace EigenJS {

template <typename ValueType, const char* ClassName>
class Matrix : public node::ObjectWrap {
  typedef ValueType element_type;

  typedef Eigen::Matrix<
      element_type
    , Eigen::Dynamic
    , Eigen::Dynamic
  > matrix_type;

 public:
  static void Init(v8::Handle<v8::Object> exports) {
    NanScope();

    v8::Local<v8::FunctionTemplate> tpl = NanNew<v8::FunctionTemplate>(New);
    tpl->SetClassName(NanNew(ClassName));
    tpl->InstanceTemplate()->SetInternalFieldCount(1);

    NODE_SET_PROTOTYPE_METHOD(tpl, "rows", rows);
    NODE_SET_PROTOTYPE_METHOD(tpl, "cols", cols);
    NODE_SET_PROTOTYPE_METHOD(tpl, "set", set);
    NODE_SET_PROTOTYPE_METHOD(tpl, "get", get);

    NODE_SET_PROTOTYPE_METHOD(tpl, "add", add);
    NODE_SET_PROTOTYPE_METHOD(tpl, "adda", adda);
    NODE_SET_PROTOTYPE_METHOD(tpl, "sub", sub);
    NODE_SET_PROTOTYPE_METHOD(tpl, "suba", suba);

    NODE_SET_PROTOTYPE_METHOD(tpl, "mul", mul);
    NODE_SET_PROTOTYPE_METHOD(tpl, "mula", mula);

    NODE_SET_PROTOTYPE_METHOD(tpl, "div", div);
    NODE_SET_PROTOTYPE_METHOD(tpl, "diva", diva);

    NODE_SET_PROTOTYPE_METHOD(tpl, "toString", toString);

    NanAssignPersistent(constructor, tpl->GetFunction());
    exports->Set(NanNew(ClassName), tpl->GetFunction());

    NanAssignPersistent(function_template, tpl);
  }

  static NAN_METHOD(rows) {
    const Matrix* obj = node::ObjectWrap::Unwrap<Matrix>(args.This());
    NanScope();

    NanReturnValue(NanNew<v8::Integer>(obj->matrix_.rows()));
  }

  static NAN_METHOD(cols) {
    const Matrix* obj = node::ObjectWrap::Unwrap<Matrix>(args.This());
    NanScope();

    NanReturnValue(NanNew<v8::Integer>(obj->matrix_.cols()));
  }

  static NAN_METHOD(set) {
    Matrix* obj = node::ObjectWrap::Unwrap<Matrix>(args.This());
    NanScope();

    if (args.Length() == 1 && args[0]->IsArray()) {
      v8::Local<v8::Array> array = args[0].As<v8::Array>();
      uint32_t len = array->Length();
      const typename matrix_type::Index& rows = obj->matrix_.rows();
      const typename matrix_type::Index& cols = obj->matrix_.cols();
      const typename matrix_type::Index& elems = rows * cols;

      if (len != elems) {
        len < rows * cols
          ? NanThrowError("Too few coefficients passed to Matrix")
          : NanThrowError("Too many coefficients passed to Matrix");
        NanReturnUndefined();
      }

      for (uint32_t i = 0; i < len; ++i) {
        v8::Local<v8::Value> elem = array->Get(i);
        obj->matrix_(i / cols, i % cols) = elem->NumberValue();
      }
    } else if (
        args.Length() == 3 &&
        args[0]->IsNumber() &&
        args[1]->IsNumber() &&
        args[2]->IsNumber()) {
      const typename matrix_type::Index& row = args[0]->Uint32Value();
      const typename matrix_type::Index& col = args[1]->Uint32Value();
      const element_type& value = args[2]->NumberValue();

      if (is_out_of_range(obj->matrix_, row, col))
        NanReturnUndefined();

      obj->matrix_(row, col) = value;
    }

    NanReturnValue(args.This());
  }

  static NAN_METHOD(get) {
    const Matrix* obj = node::ObjectWrap::Unwrap<Matrix>(args.This());
    NanScope();

    if (args.Length() == 2 &&
        args[0]->IsNumber() &&
        args[1]->IsNumber()) {
      typename matrix_type::Index row = args[0]->Uint32Value();
      typename matrix_type::Index col = args[1]->Uint32Value();

      if (is_out_of_range(obj->matrix_, row, col))
        NanReturnUndefined();

      element_type value = obj->matrix_(row, col);
      NanReturnValue(NanNew(value));
    }

    NanReturnUndefined();
  }

  EIGENJS_MATRIX_BINARY_OPERATOR(add, +)
  EIGENJS_MATRIX_BINARY_OPERATOR_COMMUTATIVE(adda, +)

  EIGENJS_MATRIX_BINARY_OPERATOR(sub, -)
  EIGENJS_MATRIX_BINARY_OPERATOR_COMMUTATIVE(suba, -)

  static NAN_METHOD(mul) {
    const Matrix* obj = node::ObjectWrap::Unwrap<Matrix>( args.This() );
    const typename matrix_type::Index& rows = obj->matrix_.rows();
    const typename matrix_type::Index& cols = obj->matrix_.cols();
    NanScope();

    if (args.Length() == 1 && HasInstance(args[0])) {
      const Matrix* rhs_obj =
          node::ObjectWrap::Unwrap<Matrix>(args[0]->ToObject());

      if (is_invalid_matrix_product(obj, rhs_obj)) {
        NanReturnUndefined();
      }

      v8::Local<v8::Function> ctr = NanNew(constructor);
      v8::Local<v8::Value> argv[] = {
          NanNew<v8::Integer>(rows)
        , NanNew<v8::Integer>(cols)
      };

      v8::Local<v8::Object> new_matrix = ctr->NewInstance(
          sizeof(argv) / sizeof(v8::Local<v8::Value>)
        , argv
      );

      Matrix* new_obj = node::ObjectWrap::Unwrap<Matrix>(new_matrix);
      new_obj->matrix_ = obj->matrix_ * rhs_obj->matrix_;

      NanReturnValue(new_matrix);
    } else if (args.Length() == 1 && args[0]->IsNumber()) {
      v8::Local<v8::Function> ctr = NanNew(constructor);
      v8::Local<v8::Value> argv[] = {
          NanNew<v8::Integer>(rows)
        , NanNew<v8::Integer>(cols)
      };

      v8::Local<v8::Object> new_matrix = ctr->NewInstance(
          sizeof(argv) / sizeof(v8::Local<v8::Value>)
        , argv
      );

      Matrix* new_obj = node::ObjectWrap::Unwrap<Matrix>(new_matrix);
      new_obj->matrix_ = obj->matrix_ * args[0]->NumberValue();

      NanReturnValue(new_matrix);
    }

    NanReturnUndefined();
  }

  static NAN_METHOD(mula) {
    Matrix* obj = node::ObjectWrap::Unwrap<Matrix>(args.This());
    NanScope();

    if (args.Length() == 1 && HasInstance(args[0])) {
      const Matrix* rhs_obj =
          node::ObjectWrap::Unwrap<Matrix>(args[0]->ToObject());

      if (is_invalid_matrix_product(obj, rhs_obj)) {
        NanReturnUndefined();
      }

      obj->matrix_ *= rhs_obj->matrix_;

      NanReturnValue(args.This());
    } else if (args.Length() == 1 && args[0]->IsNumber()) {
      obj->matrix_ *= args[0]->NumberValue();

      NanReturnValue(args.This());
    }

    NanReturnUndefined();
  }

  static NAN_METHOD(div) {
    const Matrix* obj = node::ObjectWrap::Unwrap<Matrix>( args.This() );
    const typename matrix_type::Index& rows = obj->matrix_.rows();
    const typename matrix_type::Index& cols = obj->matrix_.cols();
    NanScope();

    if (args.Length() == 1 && args[0]->IsNumber()) {
      v8::Local<v8::Function> ctr = NanNew(constructor);
      v8::Local<v8::Value> argv[] = {
          NanNew<v8::Integer>(rows)
        , NanNew<v8::Integer>(cols)
      };

      v8::Local<v8::Object> new_matrix = ctr->NewInstance(
          sizeof(argv) / sizeof(v8::Local<v8::Value>)
        , argv
      );

      Matrix* new_obj = node::ObjectWrap::Unwrap<Matrix>(new_matrix);
      new_obj->matrix_ = obj->matrix_ / args[0]->NumberValue();

      NanReturnValue(new_matrix);
    }

    NanReturnUndefined();
  }

  static NAN_METHOD(diva) {
    Matrix* obj = node::ObjectWrap::Unwrap<Matrix>(args.This());
    NanScope();

    if (args.Length() == 1 && args[0]->IsNumber()) {
      obj->matrix_ /= args[0]->NumberValue();

      NanReturnValue(args.This());
    }

    NanReturnUndefined();
  }

  static NAN_METHOD(toString) {
    const Matrix* obj = node::ObjectWrap::Unwrap<Matrix>(args.This());
    NanScope();

    std::ostringstream result;
    result << obj->matrix_;

    NanReturnValue(NanNew(result.str().c_str()));
  }

 private:
  Matrix(
      const typename matrix_type::Index& rows
    , const typename matrix_type::Index& cols)
    : matrix_(matrix_type::Zero(rows, cols))
  {}
  ~Matrix() {}

  static NAN_METHOD(New) {
    NanScope();

    if (args.Length() < 2) {
      NanThrowError("Tried creating matrix without rows and columns arguments");
      NanReturnUndefined();
    }

    if (args.IsConstructCall()) {
      typename matrix_type::Index rows = args[0]->Uint32Value();
      typename matrix_type::Index columns = args[1]->Uint32Value();
      Matrix* obj = new Matrix(rows, columns);
      obj->Wrap(args.This());
      NanReturnValue(args.This());
    } else {
      v8::Local<v8::Function> ctr = NanNew(constructor);
      v8::Local<v8::Value> argv[] = {args[0], args[1]};
      NanReturnValue(
        ctr->NewInstance(
            sizeof(argv) / sizeof(v8::Local<v8::Value>)
          , argv
        )
      );
    }
  }

  static bool HasInstance(const v8::Handle<v8::Value>& value) {
    v8::Local<v8::FunctionTemplate> tpl = NanNew(function_template);
    return tpl->HasInstance(value);
  }

  static v8::Persistent<v8::FunctionTemplate> function_template;
  static v8::Persistent<v8::Function> constructor;

 private:
  static bool is_out_of_range(
      const matrix_type& matrix
    , const typename matrix_type::Index& row
    , const typename matrix_type::Index& col) {
    return row < 0 || row >= matrix.rows() || col < 0 || col >= matrix.cols()
      ? NanThrowError("Row or column numbers are out of range"), true
      : false;
  }

  static bool is_nonconformate_arguments(
      const Matrix* const& op1
    , const Matrix* const& op2) {
    return op1->matrix_.rows() != op2->matrix_.rows() ||
           op1->matrix_.cols() != op2->matrix_.cols()
      ? NanThrowError("Nonconformant arguments"), true
      : false;
  }

  static bool is_invalid_matrix_product(
      const Matrix* const& op1
    , const Matrix* const& op2) {
    return op1->matrix_.cols() != op2->matrix_.rows()
      ? NanThrowError("Invalid matrix product"), true
      : false;
  }

 private:
  matrix_type matrix_;
};

template<typename ValueType, const char* ClassName>
v8::Persistent<v8::FunctionTemplate>
Matrix<ValueType, ClassName>::function_template;

template<typename ValueType, const char* ClassName>
v8::Persistent<v8::Function> Matrix<ValueType, ClassName>::constructor;

}  // namespace EigenJS

#undef EIGENJS_MATRIX_BINARY_OPERATOR
#undef EIGENJS_MATRIX_BINARY_OPERATOR_COMMUTATIVE

#endif  // EIGENJS_MATRIX_HPP
<commit_msg>src: fixed a bug<commit_after>//
// Matirx.hpp
// ~~~~~~~~~~
//
// Copyright (c) 2014 Rick Yang (rick68 at gmail dot com)
//
// 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/.
//

#ifndef EIGENJS_MATRIX_HPP
#define EIGENJS_MATRIX_HPP

#include <node.h>
#include <v8.h>

#include <nan.h>

#include <eigen3/Eigen/Dense>

#include <sstream>

#define EIGENJS_MATRIX_BINARY_OPERATOR( NAME, OP )                             \
static NAN_METHOD( NAME ) {                                                    \
  const Matrix* obj = node::ObjectWrap::Unwrap<Matrix>( args.This() );         \
  NanScope();                                                                  \
                                                                               \
  if ( args.Length() == 1 && HasInstance( args[0] ) ) {                        \
    const Matrix* rhs_obj =                                                    \
        node::ObjectWrap::Unwrap<Matrix>( args[0]->ToObject() );               \
                                                                               \
    if ( is_nonconformate_arguments( obj, rhs_obj ) ) {                        \
      NanReturnUndefined();                                                    \
    }                                                                          \
                                                                               \
    const typename matrix_type::Index& rows = obj->matrix_.rows();             \
    const typename matrix_type::Index& cols = obj->matrix_.cols();             \
                                                                               \
    v8::Local<v8::Function> ctr = NanNew( constructor );                       \
    v8::Local<v8::Value> argv[] = {                                            \
        NanNew<v8::Integer>( rows )                                            \
      , NanNew<v8::Integer>( cols )                                            \
    };                                                                         \
                                                                               \
    v8::Local<v8::Object> new_matrix = ctr->NewInstance(                       \
        sizeof( argv ) / sizeof( v8::Local<v8::Value> )                        \
      , argv                                                                   \
    );                                                                         \
                                                                               \
    Matrix* new_obj = node::ObjectWrap::Unwrap<Matrix>( new_matrix );          \
    new_obj->matrix_ = obj->matrix_ OP rhs_obj->matrix_;                       \
                                                                               \
    NanReturnValue( new_matrix );                                              \
  }                                                                            \
                                                                               \
  NanReturnUndefined();                                                        \
}                                                                              \
/**/

#define EIGENJS_MATRIX_BINARY_OPERATOR_COMMUTATIVE( NAME, OP )                 \
static NAN_METHOD( NAME ) {                                                    \
  Matrix* obj = node::ObjectWrap::Unwrap<Matrix>( args.This() );               \
  NanScope();                                                                  \
                                                                               \
  if ( args.Length() == 1 && HasInstance( args[0] ) ) {                        \
    const Matrix* rhs_obj =                                                    \
        node::ObjectWrap::Unwrap<Matrix>( args[0]->ToObject() );               \
                                                                               \
    if ( is_nonconformate_arguments( obj, rhs_obj ) ) {                        \
      NanReturnUndefined();                                                    \
    }                                                                          \
                                                                               \
    obj->matrix_ OP##= rhs_obj->matrix_;                                       \
                                                                               \
    NanReturnValue( args.This() );                                             \
  }                                                                            \
                                                                               \
  NanReturnUndefined();                                                        \
}                                                                              \
/**/

namespace EigenJS {

template <typename ValueType, const char* ClassName>
class Matrix : public node::ObjectWrap {
  typedef ValueType element_type;

  typedef Eigen::Matrix<
      element_type
    , Eigen::Dynamic
    , Eigen::Dynamic
  > matrix_type;

 public:
  static void Init(v8::Handle<v8::Object> exports) {
    NanScope();

    v8::Local<v8::FunctionTemplate> tpl = NanNew<v8::FunctionTemplate>(New);
    tpl->SetClassName(NanNew(ClassName));
    tpl->InstanceTemplate()->SetInternalFieldCount(1);

    NODE_SET_PROTOTYPE_METHOD(tpl, "rows", rows);
    NODE_SET_PROTOTYPE_METHOD(tpl, "cols", cols);
    NODE_SET_PROTOTYPE_METHOD(tpl, "set", set);
    NODE_SET_PROTOTYPE_METHOD(tpl, "get", get);

    NODE_SET_PROTOTYPE_METHOD(tpl, "add", add);
    NODE_SET_PROTOTYPE_METHOD(tpl, "adda", adda);
    NODE_SET_PROTOTYPE_METHOD(tpl, "sub", sub);
    NODE_SET_PROTOTYPE_METHOD(tpl, "suba", suba);

    NODE_SET_PROTOTYPE_METHOD(tpl, "mul", mul);
    NODE_SET_PROTOTYPE_METHOD(tpl, "mula", mula);

    NODE_SET_PROTOTYPE_METHOD(tpl, "div", div);
    NODE_SET_PROTOTYPE_METHOD(tpl, "diva", diva);

    NODE_SET_PROTOTYPE_METHOD(tpl, "toString", toString);

    NanAssignPersistent(constructor, tpl->GetFunction());
    exports->Set(NanNew(ClassName), tpl->GetFunction());

    NanAssignPersistent(function_template, tpl);
  }

  static NAN_METHOD(rows) {
    const Matrix* obj = node::ObjectWrap::Unwrap<Matrix>(args.This());
    NanScope();

    NanReturnValue(NanNew<v8::Integer>(obj->matrix_.rows()));
  }

  static NAN_METHOD(cols) {
    const Matrix* obj = node::ObjectWrap::Unwrap<Matrix>(args.This());
    NanScope();

    NanReturnValue(NanNew<v8::Integer>(obj->matrix_.cols()));
  }

  static NAN_METHOD(set) {
    Matrix* obj = node::ObjectWrap::Unwrap<Matrix>(args.This());
    NanScope();

    if (args.Length() == 1 && args[0]->IsArray()) {
      v8::Local<v8::Array> array = args[0].As<v8::Array>();
      uint32_t len = array->Length();
      const typename matrix_type::Index& rows = obj->matrix_.rows();
      const typename matrix_type::Index& cols = obj->matrix_.cols();
      const typename matrix_type::Index& elems = rows * cols;

      if (len != elems) {
        len < rows * cols
          ? NanThrowError("Too few coefficients passed to Matrix")
          : NanThrowError("Too many coefficients passed to Matrix");
        NanReturnUndefined();
      }

      for (uint32_t i = 0; i < len; ++i) {
        v8::Local<v8::Value> elem = array->Get(i);
        obj->matrix_(i / cols, i % cols) = elem->NumberValue();
      }
    } else if (
        args.Length() == 3 &&
        args[0]->IsNumber() &&
        args[1]->IsNumber() &&
        args[2]->IsNumber()) {
      const typename matrix_type::Index& row = args[0]->Uint32Value();
      const typename matrix_type::Index& col = args[1]->Uint32Value();
      const element_type& value = args[2]->NumberValue();

      if (is_out_of_range(obj->matrix_, row, col))
        NanReturnUndefined();

      obj->matrix_(row, col) = value;
    }

    NanReturnValue(args.This());
  }

  static NAN_METHOD(get) {
    const Matrix* obj = node::ObjectWrap::Unwrap<Matrix>(args.This());
    NanScope();

    if (args.Length() == 2 &&
        args[0]->IsNumber() &&
        args[1]->IsNumber()) {
      typename matrix_type::Index row = args[0]->Uint32Value();
      typename matrix_type::Index col = args[1]->Uint32Value();

      if (is_out_of_range(obj->matrix_, row, col))
        NanReturnUndefined();

      element_type value = obj->matrix_(row, col);
      NanReturnValue(NanNew(value));
    }

    NanReturnUndefined();
  }

  EIGENJS_MATRIX_BINARY_OPERATOR(add, +)
  EIGENJS_MATRIX_BINARY_OPERATOR_COMMUTATIVE(adda, +)

  EIGENJS_MATRIX_BINARY_OPERATOR(sub, -)
  EIGENJS_MATRIX_BINARY_OPERATOR_COMMUTATIVE(suba, -)

  static NAN_METHOD(mul) {
    const Matrix* obj = node::ObjectWrap::Unwrap<Matrix>( args.This() );
    const typename matrix_type::Index& rows = obj->matrix_.rows();
    const typename matrix_type::Index& cols = obj->matrix_.cols();
    NanScope();

    if (args.Length() == 1 && HasInstance(args[0])) {
      const Matrix* rhs_obj =
          node::ObjectWrap::Unwrap<Matrix>(args[0]->ToObject());

      if (is_invalid_matrix_product(obj, rhs_obj)) {
        NanReturnUndefined();
      }

      v8::Local<v8::Function> ctr = NanNew(constructor);
      v8::Local<v8::Value> argv[] = {
          NanNew<v8::Integer>(rows)
        , NanNew<v8::Integer>(cols)
      };

      v8::Local<v8::Object> new_matrix = ctr->NewInstance(
          sizeof(argv) / sizeof(v8::Local<v8::Value>)
        , argv
      );

      Matrix* new_obj = node::ObjectWrap::Unwrap<Matrix>(new_matrix);
      new_obj->matrix_ = obj->matrix_ * rhs_obj->matrix_;

      NanReturnValue(new_matrix);
    } else if (args.Length() == 1 && args[0]->IsNumber()) {
      v8::Local<v8::Function> ctr = NanNew(constructor);
      v8::Local<v8::Value> argv[] = {
          NanNew<v8::Integer>(rows)
        , NanNew<v8::Integer>(cols)
      };

      v8::Local<v8::Object> new_matrix = ctr->NewInstance(
          sizeof(argv) / sizeof(v8::Local<v8::Value>)
        , argv
      );

      Matrix* new_obj = node::ObjectWrap::Unwrap<Matrix>(new_matrix);
      new_obj->matrix_ = obj->matrix_ * args[0]->NumberValue();

      NanReturnValue(new_matrix);
    }

    NanReturnUndefined();
  }

  static NAN_METHOD(mula) {
    Matrix* obj = node::ObjectWrap::Unwrap<Matrix>(args.This());
    NanScope();

    if (args.Length() == 1 && HasInstance(args[0])) {
      const Matrix* rhs_obj =
          node::ObjectWrap::Unwrap<Matrix>(args[0]->ToObject());

      if (is_invalid_matrix_product(obj, rhs_obj)) {
        NanReturnUndefined();
      }

      obj->matrix_ *= rhs_obj->matrix_;

      NanReturnValue(args.This());
    } else if (args.Length() == 1 && args[0]->IsNumber()) {
      obj->matrix_ *= args[0]->NumberValue();

      NanReturnValue(args.This());
    }

    NanReturnUndefined();
  }

  static NAN_METHOD(div) {
    const Matrix* obj = node::ObjectWrap::Unwrap<Matrix>( args.This() );
    const typename matrix_type::Index& rows = obj->matrix_.rows();
    const typename matrix_type::Index& cols = obj->matrix_.cols();
    NanScope();

    if (args.Length() == 1 && args[0]->IsNumber()) {
      v8::Local<v8::Function> ctr = NanNew(constructor);
      v8::Local<v8::Value> argv[] = {
          NanNew<v8::Integer>(rows)
        , NanNew<v8::Integer>(cols)
      };

      v8::Local<v8::Object> new_matrix = ctr->NewInstance(
          sizeof(argv) / sizeof(v8::Local<v8::Value>)
        , argv
      );

      Matrix* new_obj = node::ObjectWrap::Unwrap<Matrix>(new_matrix);
      new_obj->matrix_ = obj->matrix_ / args[0]->NumberValue();

      NanReturnValue(new_matrix);
    }

    NanReturnUndefined();
  }

  static NAN_METHOD(diva) {
    Matrix* obj = node::ObjectWrap::Unwrap<Matrix>(args.This());
    NanScope();

    if (args.Length() == 1 && args[0]->IsNumber()) {
      obj->matrix_ /= args[0]->NumberValue();

      NanReturnValue(args.This());
    }

    NanReturnUndefined();
  }

  static NAN_METHOD(toString) {
    const Matrix* obj = node::ObjectWrap::Unwrap<Matrix>(args.This());
    NanScope();

    std::ostringstream result;
    result << obj->matrix_;

    NanReturnValue(NanNew(result.str().c_str()));
  }

 private:
  Matrix(
      const typename matrix_type::Index& rows
    , const typename matrix_type::Index& cols)
    : matrix_(matrix_type::Zero(rows, cols))
  {}
  ~Matrix() {}

  static NAN_METHOD(New) {
    NanScope();

    if (args.Length() < 2) {
      NanThrowError("Tried creating matrix without rows and columns arguments");
      NanReturnUndefined();
    }

    if (args.IsConstructCall()) {
      typename matrix_type::Index rows = args[0]->Uint32Value();
      typename matrix_type::Index columns = args[1]->Uint32Value();
      Matrix* obj = new Matrix(rows, columns);
      obj->Wrap(args.This());
      NanReturnValue(args.This());
    } else {
      v8::Local<v8::Function> ctr = NanNew(constructor);
      v8::Local<v8::Value> argv[] = {args[0], args[1]};
      NanReturnValue(
        ctr->NewInstance(
            sizeof(argv) / sizeof(v8::Local<v8::Value>)
          , argv
        )
      );
    }
  }

  static bool HasInstance(const v8::Handle<v8::Value>& value) {
    NanScope();
    v8::Local<v8::FunctionTemplate> tpl = NanNew(function_template);
    return tpl->HasInstance(value);
  }

  static v8::Persistent<v8::FunctionTemplate> function_template;
  static v8::Persistent<v8::Function> constructor;

 private:
  static bool is_out_of_range(
      const matrix_type& matrix
    , const typename matrix_type::Index& row
    , const typename matrix_type::Index& col) {
    return row < 0 || row >= matrix.rows() || col < 0 || col >= matrix.cols()
      ? NanThrowError("Row or column numbers are out of range"), true
      : false;
  }

  static bool is_nonconformate_arguments(
      const Matrix* const& op1
    , const Matrix* const& op2) {
    return op1->matrix_.rows() != op2->matrix_.rows() ||
           op1->matrix_.cols() != op2->matrix_.cols()
      ? NanThrowError("Nonconformant arguments"), true
      : false;
  }

  static bool is_invalid_matrix_product(
      const Matrix* const& op1
    , const Matrix* const& op2) {
    return op1->matrix_.cols() != op2->matrix_.rows()
      ? NanThrowError("Invalid matrix product"), true
      : false;
  }

 private:
  matrix_type matrix_;
};

template<typename ValueType, const char* ClassName>
v8::Persistent<v8::FunctionTemplate>
Matrix<ValueType, ClassName>::function_template;

template<typename ValueType, const char* ClassName>
v8::Persistent<v8::Function> Matrix<ValueType, ClassName>::constructor;

}  // namespace EigenJS

#undef EIGENJS_MATRIX_BINARY_OPERATOR
#undef EIGENJS_MATRIX_BINARY_OPERATOR_COMMUTATIVE

#endif  // EIGENJS_MATRIX_HPP
<|endoftext|>


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

#include "chrome/browser/browser.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/extensions/extension_browsertest.h"
#include "chrome/browser/extensions/extensions_service.h"
#include "chrome/browser/extensions/theme_installed_infobar_delegate.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/test/ui_test_utils.h"

namespace {

// Theme ID used for testing.
const char* const theme_crx = "iamefpfkojoapidjnbafmgkgncegbkad";

}  // namespace

class ExtensionInstallUIBrowserTest : public ExtensionBrowserTest {
 public:
  // Checks that a theme info bar is currently visible and issues an undo to
  // revert to the previous theme.
  void VerifyThemeInfoBarAndUndoInstall() {
    TabContents* tab_contents = browser()->GetSelectedTabContents();
    ASSERT_TRUE(tab_contents);
    ASSERT_EQ(1, tab_contents->infobar_delegate_count());
    ThemeInstalledInfoBarDelegate* delegate = tab_contents->
        GetInfoBarDelegateAt(0)->AsThemePreviewInfobarDelegate();
    ASSERT_TRUE(delegate);
    delegate->Cancel();
    ASSERT_EQ(0, tab_contents->infobar_delegate_count());
  }
};

// Flaky, http://crbug.com/43441.
// Crashy, http://crbug.com/44548.
IN_PROC_BROWSER_TEST_F(ExtensionInstallUIBrowserTest,
                       DISABLED_TestThemeInstallUndoResetsToDefault) {
  // Install theme once and undo to verify we go back to default theme.
  FilePath theme_path = test_data_dir_.AppendASCII("theme.crx");
  ASSERT_TRUE(InstallExtensionWithUI(theme_path, 1));
  Extension* theme = browser()->profile()->GetTheme();
  ASSERT_TRUE(theme);
  ASSERT_EQ(theme_crx, theme->id());
  VerifyThemeInfoBarAndUndoInstall();
  ASSERT_EQ(NULL, browser()->profile()->GetTheme());

  // Set the same theme twice and undo to verify we go back to default theme.
  // We set the |expected_change| to zero in these 'InstallExtensionWithUI'
  // calls since the theme has already been installed above and this is an
  // overinstall to set the active theme.
  ASSERT_TRUE(InstallExtensionWithUI(theme_path, 0));
  theme = browser()->profile()->GetTheme();
  ASSERT_TRUE(theme);
  ASSERT_EQ(theme_crx, theme->id());
  ASSERT_TRUE(InstallExtensionWithUI(theme_path, 0));
  theme = browser()->profile()->GetTheme();
  ASSERT_TRUE(theme);
  ASSERT_EQ(theme_crx, theme->id());
  VerifyThemeInfoBarAndUndoInstall();
  ASSERT_EQ(NULL, browser()->profile()->GetTheme());
}
<commit_msg>TBR: phajdan.jr<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/browser.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/extensions/extension_browsertest.h"
#include "chrome/browser/extensions/extensions_service.h"
#include "chrome/browser/extensions/theme_installed_infobar_delegate.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/test/ui_test_utils.h"

namespace {

// Theme ID used for testing.
const char* const theme_crx = "iamefpfkojoapidjnbafmgkgncegbkad";

}  // namespace

class ExtensionInstallUIBrowserTest : public ExtensionBrowserTest {
 public:
  // Checks that a theme info bar is currently visible and issues an undo to
  // revert to the previous theme.
  void VerifyThemeInfoBarAndUndoInstall() {
    TabContents* tab_contents = browser()->GetSelectedTabContents();
    ASSERT_TRUE(tab_contents);
    ASSERT_EQ(1, tab_contents->infobar_delegate_count());
    ThemeInstalledInfoBarDelegate* delegate = tab_contents->
        GetInfoBarDelegateAt(0)->AsThemePreviewInfobarDelegate();
    ASSERT_TRUE(delegate);
    delegate->Cancel();
    ASSERT_EQ(0, tab_contents->infobar_delegate_count());
  }
};

// Flaky, http://crbug.com/43441.
// Crashy, http://crbug.com/44548.
IN_PROC_BROWSER_TEST_F(ExtensionInstallUIBrowserTest,
                       TestThemeInstallUndoResetsToDefault) {
  // Install theme once and undo to verify we go back to default theme.
  FilePath theme_path = test_data_dir_.AppendASCII("theme.crx");
  ASSERT_TRUE(InstallExtensionWithUI(theme_path, 1));
  Extension* theme = browser()->profile()->GetTheme();
  ASSERT_TRUE(theme);
  ASSERT_EQ(theme_crx, theme->id());
  VerifyThemeInfoBarAndUndoInstall();
  ASSERT_EQ(NULL, browser()->profile()->GetTheme());

  // Set the same theme twice and undo to verify we go back to default theme.
  // We set the |expected_change| to zero in these 'InstallExtensionWithUI'
  // calls since the theme has already been installed above and this is an
  // overinstall to set the active theme.
  ASSERT_TRUE(InstallExtensionWithUI(theme_path, 0));
  theme = browser()->profile()->GetTheme();
  ASSERT_TRUE(theme);
  ASSERT_EQ(theme_crx, theme->id());
  ASSERT_TRUE(InstallExtensionWithUI(theme_path, 0));
  theme = browser()->profile()->GetTheme();
  ASSERT_TRUE(theme);
  ASSERT_EQ(theme_crx, theme->id());
  VerifyThemeInfoBarAndUndoInstall();
  ASSERT_EQ(NULL, browser()->profile()->GetTheme());
}
<|endoftext|>


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

#include "chrome/test/live_sync/live_extensions_sync_test.h"

#include "base/basictypes.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/common/extensions/extension.h"

class TwoClientLiveExtensionsSyncTest : public LiveExtensionsSyncTest {
 public:
  TwoClientLiveExtensionsSyncTest()
      : LiveExtensionsSyncTest(TWO_CLIENT) {}

  virtual ~TwoClientLiveExtensionsSyncTest() {}

 private:
  DISALLOW_COPY_AND_ASSIGN(TwoClientLiveExtensionsSyncTest);
};

IN_PROC_BROWSER_TEST_F(TwoClientLiveExtensionsSyncTest,
                       StartWithNoExtensions) {
  ASSERT_TRUE(SetupSync());

  ASSERT_TRUE(AllProfilesHaveSameExtensionsAsVerifier());
}

IN_PROC_BROWSER_TEST_F(TwoClientLiveExtensionsSyncTest,
                       StartWithSameExtensions) {
  ASSERT_TRUE(SetupClients());

  const int kNumExtensions = 5;
  for (int i = 0; i < kNumExtensions; ++i) {
    InstallExtension(GetProfile(0), GetExtension(i));
    InstallExtension(GetProfile(1), GetExtension(i));
    InstallExtension(verifier(), GetExtension(i));
  }

  ASSERT_TRUE(SetupSync());

  ASSERT_TRUE(AwaitQuiescence());

  ASSERT_TRUE(AllProfilesHaveSameExtensionsAsVerifier());
}

// TODO(rsimha): Remove FAILS_ prefix after http://crbug.com/66925 is fixed.
IN_PROC_BROWSER_TEST_F(TwoClientLiveExtensionsSyncTest,
                       FAILS_StartWithDifferentExtensions) {
  ASSERT_TRUE(SetupClients());

  int i = 0;

  const int kNumCommonExtensions = 5;
  for (int j = 0; j < kNumCommonExtensions; ++i, ++j) {
    InstallExtension(GetProfile(0), GetExtension(i));
    InstallExtension(GetProfile(1), GetExtension(i));
    InstallExtension(verifier(), GetExtension(i));
  }

  const int kNumProfile0Extensions = 10;
  for (int j = 0; j < kNumProfile0Extensions; ++i, ++j) {
    InstallExtension(GetProfile(0), GetExtension(i));
    InstallExtension(verifier(), GetExtension(i));
  }

  const int kNumProfile1Extensions = 10;
  for (int j = 0; j < kNumProfile1Extensions; ++i, ++j) {
    InstallExtension(GetProfile(1), GetExtension(i));
    InstallExtension(verifier(), GetExtension(i));
  }

  ASSERT_TRUE(SetupSync());

  ASSERT_TRUE(AwaitQuiescence());

  InstallAllPendingExtensions(GetProfile(0));
  InstallAllPendingExtensions(GetProfile(1));

  ASSERT_TRUE(AllProfilesHaveSameExtensionsAsVerifier());
}

// TODO(rsimha): Remove FAILS_ prefix after http://crbug.com/66925 is fixed.
IN_PROC_BROWSER_TEST_F(TwoClientLiveExtensionsSyncTest,
                       FAILS_InstallDifferentExtensions) {
  ASSERT_TRUE(SetupClients());

  int i = 0;

  const int kNumCommonExtensions = 5;
  for (int j = 0; j < kNumCommonExtensions; ++i, ++j) {
    InstallExtension(GetProfile(0), GetExtension(i));
    InstallExtension(GetProfile(1), GetExtension(i));
    InstallExtension(verifier(), GetExtension(i));
  }

  ASSERT_TRUE(SetupSync());

  ASSERT_TRUE(AwaitQuiescence());

  const int kNumProfile0Extensions = 10;
  for (int j = 0; j < kNumProfile0Extensions; ++i, ++j) {
    InstallExtension(GetProfile(0), GetExtension(i));
    InstallExtension(verifier(), GetExtension(i));
  }

  const int kNumProfile1Extensions = 10;
  for (int j = 0; j < kNumProfile1Extensions; ++i, ++j) {
    InstallExtension(GetProfile(1), GetExtension(i));
    InstallExtension(verifier(), GetExtension(i));
  }

  ASSERT_TRUE(AwaitQuiescence());

  InstallAllPendingExtensions(GetProfile(0));
  InstallAllPendingExtensions(GetProfile(1));

  ASSERT_TRUE(AllProfilesHaveSameExtensionsAsVerifier());
}

// TODO(akalin): Add tests exercising:
//   - Extensions enabled/disabled state sync behavior
//   - Extension uninstallation
//   - Offline installation/uninstallation behavior
<commit_msg>Marking crashing tests as DISABLED instead of FAILS<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/test/live_sync/live_extensions_sync_test.h"

#include "base/basictypes.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/common/extensions/extension.h"

class TwoClientLiveExtensionsSyncTest : public LiveExtensionsSyncTest {
 public:
  TwoClientLiveExtensionsSyncTest()
      : LiveExtensionsSyncTest(TWO_CLIENT) {}

  virtual ~TwoClientLiveExtensionsSyncTest() {}

 private:
  DISALLOW_COPY_AND_ASSIGN(TwoClientLiveExtensionsSyncTest);
};

IN_PROC_BROWSER_TEST_F(TwoClientLiveExtensionsSyncTest,
                       StartWithNoExtensions) {
  ASSERT_TRUE(SetupSync());

  ASSERT_TRUE(AllProfilesHaveSameExtensionsAsVerifier());
}

IN_PROC_BROWSER_TEST_F(TwoClientLiveExtensionsSyncTest,
                       StartWithSameExtensions) {
  ASSERT_TRUE(SetupClients());

  const int kNumExtensions = 5;
  for (int i = 0; i < kNumExtensions; ++i) {
    InstallExtension(GetProfile(0), GetExtension(i));
    InstallExtension(GetProfile(1), GetExtension(i));
    InstallExtension(verifier(), GetExtension(i));
  }

  ASSERT_TRUE(SetupSync());

  ASSERT_TRUE(AwaitQuiescence());

  ASSERT_TRUE(AllProfilesHaveSameExtensionsAsVerifier());
}

// TODO(rsimha): Remove DISABLED_ prefix after http://crbug.com/66925 is fixed.
IN_PROC_BROWSER_TEST_F(TwoClientLiveExtensionsSyncTest,
                       DISABLED_StartWithDifferentExtensions) {
  ASSERT_TRUE(SetupClients());

  int i = 0;

  const int kNumCommonExtensions = 5;
  for (int j = 0; j < kNumCommonExtensions; ++i, ++j) {
    InstallExtension(GetProfile(0), GetExtension(i));
    InstallExtension(GetProfile(1), GetExtension(i));
    InstallExtension(verifier(), GetExtension(i));
  }

  const int kNumProfile0Extensions = 10;
  for (int j = 0; j < kNumProfile0Extensions; ++i, ++j) {
    InstallExtension(GetProfile(0), GetExtension(i));
    InstallExtension(verifier(), GetExtension(i));
  }

  const int kNumProfile1Extensions = 10;
  for (int j = 0; j < kNumProfile1Extensions; ++i, ++j) {
    InstallExtension(GetProfile(1), GetExtension(i));
    InstallExtension(verifier(), GetExtension(i));
  }

  ASSERT_TRUE(SetupSync());

  ASSERT_TRUE(AwaitQuiescence());

  InstallAllPendingExtensions(GetProfile(0));
  InstallAllPendingExtensions(GetProfile(1));

  ASSERT_TRUE(AllProfilesHaveSameExtensionsAsVerifier());
}

// TODO(rsimha): Remove DISABLED_ prefix after http://crbug.com/66925 is fixed.
IN_PROC_BROWSER_TEST_F(TwoClientLiveExtensionsSyncTest,
                       DISABLED_InstallDifferentExtensions) {
  ASSERT_TRUE(SetupClients());

  int i = 0;

  const int kNumCommonExtensions = 5;
  for (int j = 0; j < kNumCommonExtensions; ++i, ++j) {
    InstallExtension(GetProfile(0), GetExtension(i));
    InstallExtension(GetProfile(1), GetExtension(i));
    InstallExtension(verifier(), GetExtension(i));
  }

  ASSERT_TRUE(SetupSync());

  ASSERT_TRUE(AwaitQuiescence());

  const int kNumProfile0Extensions = 10;
  for (int j = 0; j < kNumProfile0Extensions; ++i, ++j) {
    InstallExtension(GetProfile(0), GetExtension(i));
    InstallExtension(verifier(), GetExtension(i));
  }

  const int kNumProfile1Extensions = 10;
  for (int j = 0; j < kNumProfile1Extensions; ++i, ++j) {
    InstallExtension(GetProfile(1), GetExtension(i));
    InstallExtension(verifier(), GetExtension(i));
  }

  ASSERT_TRUE(AwaitQuiescence());

  InstallAllPendingExtensions(GetProfile(0));
  InstallAllPendingExtensions(GetProfile(1));

  ASSERT_TRUE(AllProfilesHaveSameExtensionsAsVerifier());
}

// TODO(akalin): Add tests exercising:
//   - Extensions enabled/disabled state sync behavior
//   - Extension uninstallation
//   - Offline installation/uninstallation behavior
<|endoftext|>


<commit_before>#pragma once
#include "config.hpp"
#include <inttypes.h>

struct Buzzer
{
  Buzzer()
  {
    // fast PWM mode
    TCCR0A |= _BV(WGM01) | _BV(WGM00);
    // 1->0 PWM's output compare
    TCCR0A |= _BV(COM0B1);
    // volume 0-255
    OCR0B = 2;
    // output mode
    DDRB |= _BV(PB1);
  }

  void on()
  {
    // ~586 [Hz]
    TCCR0B |= _BV(CS01); // prescaler = 8
  }

  void off()
  {
    TCCR0B &= ~ ( _BV(CS02) | _BV(CS01) | _BV(CS00) );  // prescaler = 0 (i.e. stop clock)
  }
};
<commit_msg>fixed comment about an actual volume range<commit_after>#pragma once
#include "config.hpp"
#include <inttypes.h>

struct Buzzer
{
  Buzzer()
  {
    // fast PWM mode
    TCCR0A |= _BV(WGM01) | _BV(WGM00);
    // 1->0 PWM's output compare
    TCCR0A |= _BV(COM0B1);
    // volume 0-128
    OCR0B = 2;
    // output mode
    DDRB |= _BV(PB1);
  }

  void on()
  {
    // ~586 [Hz]
    TCCR0B |= _BV(CS01); // prescaler = 8
  }

  void off()
  {
    TCCR0B &= ~ ( _BV(CS02) | _BV(CS01) | _BV(CS00) );  // prescaler = 0 (i.e. stop clock)
  }
};
<|endoftext|>


<commit_before>/*
  This file is part of the Groupware/KOrganizer integration.

  Requires the Qt and KDE widget libraries, available at no cost at
  http://www.trolltech.com and http://www.kde.org respectively

  Copyright (c) 2002-2004 Klarälvdalens Datakonsult AB
        <info@klaralvdalens-datakonsult.se>

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

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

  You should have received a copy of the GNU General Public License
  along with this program; if not, write to the Free Software
  Foundation, Inc., 59 Temple Place - Suite 330, Boston,
  MA  02111-1307, USA.

  In addition, as a special exception, the copyright holders give
  permission to link the code of this program with any edition of
  the Qt library by Trolltech AS, Norway (or with modified versions
  of Qt that use the same license as Qt), and distribute linked
  combinations including the two.  You must obey the GNU General
  Public License in all respects for all of the code used other than
  Qt.  If you modify this file, you may extend this exception to
  your version of the file, but you are not obligated to do so.  If
  you do not wish to do so, delete this exception statement from
  your version.
*/

#include "kogroupware.h"
#include "freebusymanager.h"
#include "calendarview.h"
#include "mailscheduler.h"
#include "koprefs.h"
#include <libkdepim/email.h>
#include <libkcal/attendee.h>
#include <libkcal/journal.h>
#include <kdebug.h>
#include <kmessagebox.h>
#include <kstandarddirs.h>
#include <kdirwatch.h>
#include <qfile.h>
#include <qregexp.h>
#include <qdir.h>
#include <qtimer.h>

FreeBusyManager *KOGroupware::mFreeBusyManager = 0;

KOGroupware *KOGroupware::mInstance = 0;

KOGroupware *KOGroupware::create( CalendarView *view,
                                  KCal::CalendarResources *calendar )
{
  if( !mInstance )
    mInstance = new KOGroupware( view, calendar );
  return mInstance;
}

KOGroupware *KOGroupware::instance()
{
  // Doesn't create, that is the task of create()
  Q_ASSERT( mInstance );
  return mInstance;
}

KOGroupware::KOGroupware( CalendarView* view, KCal::CalendarResources* cal )
  : QObject( 0, "kmgroupware_instance" ), mView( view ), mCalendar( cal )
{
  // Temporary hack: Wait one minute before starting the scheduling handling
  // This is because we need the full calendars to be loaded first
  // TODO: GET RID OF THIS!!! The real fix is to listen for the resources
  // being all done loading and start the scheduling after that. Even
  // better fix would be that we would be able to locate the resource
  // an event is saved in even though the resource is deactivated
  QTimer::singleShot( 60000, this, SLOT( slotStartScheduling() ) );
}

FreeBusyManager *KOGroupware::freeBusyManager()
{
  if ( !mFreeBusyManager ) {
    mFreeBusyManager = new FreeBusyManager( this, "freebusymanager" );
    mFreeBusyManager->setCalendar( mCalendar );
    connect( mCalendar, SIGNAL( calendarChanged() ),
             mFreeBusyManager, SLOT( slotPerhapsUploadFB() ) );
  }

  return mFreeBusyManager;
}

void KOGroupware::slotStartScheduling()
{
  // Set up the dir watch of the three incoming dirs
  KDirWatch* watcher = KDirWatch::self();
  watcher->addDir( locateLocal( "data", "korganizer/income.accepted/" ) );
  watcher->addDir( locateLocal( "data", "korganizer/income.tentative/" ) );
  watcher->addDir( locateLocal( "data", "korganizer/income.cancel/" ) );
  watcher->addDir( locateLocal( "data", "korganizer/income.reply/" ) );
  connect( watcher, SIGNAL( dirty( const QString& ) ),
           this, SLOT( incomingDirChanged( const QString& ) ) );
  // Now set the ball rolling
  incomingDirChanged( locateLocal( "data", "korganizer/income.accepted/" ) );
  incomingDirChanged( locateLocal( "data", "korganizer/income.tentative/" ) );
  incomingDirChanged( locateLocal( "data", "korganizer/income.cancel/" ) );
  incomingDirChanged( locateLocal( "data", "korganizer/income.reply/" ) );
}

void KOGroupware::incomingDirChanged( const QString& path )
{
  const QString incomingDirName = locateLocal( "data","korganizer/" )
                                  + "income.";
  if ( !path.startsWith( incomingDirName ) ) {
    kdDebug(5850) << "incomingDirChanged: Wrong dir " << path << endl;
    return;
  }
  QString action = path.mid( incomingDirName.length() );
  while ( action.length() > 0 && action[ action.length()-1 ] == '/' )
    // Strip slashes at the end
    action.truncate( action.length()-1 );

  // Handle accepted invitations
  QDir dir( path );
  QStringList files = dir.entryList( QDir::Files );
  if ( files.count() == 0 )
    // No more files here
    return;

  // Read the file and remove it
  QFile f( path + "/" + files[0] );
  if (!f.open(IO_ReadOnly)) {
    kdError(5850) << "Can't open file '" << files[0] << "'" << endl;
    return;
  }
  QTextStream t(&f);
  t.setEncoding( QTextStream::UnicodeUTF8 );
  // Read the receiver email address
  QString receiver = t.readLine();
  if ( receiver == "Receiver Not Searched" )
    // The receiver was never checked
    receiver = QString::null;
  else
    // There should be an email address in here
    receiver = KPIM::getEmailAddr( receiver );
  // Read the iCal
  QString iCal = t.read();

  f.remove();

  kdDebug(5850) << "Received this for scheduling (" << action << ")\n"
                << "Receiver: " << receiver << "\niCal:\n" << iCal << endl;
  ScheduleMessage *message = mFormat.parseScheduleMessage( mCalendar, iCal );
  if ( !message ) {
    QString errorMessage;
    if (mFormat.exception())
      errorMessage = "\nError message: " + mFormat.exception()->message();
    kdDebug(5850) << "MailScheduler::retrieveTransactions() Error parsing"
                  << errorMessage << endl;
    KMessageBox::detailedError( mView,
        i18n("Error while processing an invitation or update."),
        errorMessage );
    return;
  }

  KCal::Scheduler::Method method =
    static_cast<KCal::Scheduler::Method>( message->method() );
  KCal::ScheduleMessage::Status status = message->status();
  KCal::Incidence* incidence =
    dynamic_cast<KCal::Incidence*>( message->event() );
  KCal::MailScheduler scheduler( mCalendar );
  if ( action.startsWith( "accepted" ) || action.startsWith( "tentative" ) ) {
    // Find myself and set my status. This can't be done in the scheduler,
    // since this does not know the choice I made in the KMail bpf
    KCal::Attendee::List attendees = incidence->attendees();
    KCal::Attendee::List::ConstIterator it;
    for ( it = attendees.begin(); it != attendees.end(); ++it ) {
      if( (*it)->email() == receiver ) {
        if ( action.startsWith( "accepted" ) )
          (*it)->setStatus( KCal::Attendee::Accepted );
        else
          (*it)->setStatus( KCal::Attendee::Tentative );
        break;
      }
    }
    scheduler.acceptTransaction( incidence, method, status );
  } else if ( action.startsWith( "cancel" ) )
    // Delete the old incidence, if one is present
    mCalendar->deleteIncidence( incidence );
  else if ( action.startsWith( "reply" ) )
    scheduler.acceptTransaction( incidence, method, status );
  else
    kdError(5850) << "Unknown incoming action " << action << endl;
  mView->updateView();
}

/* This function sends mails if necessary, and makes sure the user really
 * want to change his calendar.
 *
 * Return true means accept the changes
 * Return false means revert the changes
 */
bool KOGroupware::sendICalMessage( QWidget* parent,
                                   KCal::Scheduler::Method method,
                                   Incidence* incidence, bool isDeleting,
                                   bool statusChanged )
{
  // If there are no attendees, don't bother
  if( incidence->attendees().isEmpty() )
    return true;

  bool isOrganizer = KOPrefs::instance()->thatIsMe( incidence->organizer().email() );
  int rc = 0;
  /*
   * There are two scenarios:
   * o "we" are the organizer, where "we" means any of the identities or mail
   *   addresses known to Kontact/PIM. If there are attendees, we need to mail
   *   them all, even if one or more of them are also "us". Otherwise there
   *   would be no way to invite a resource or our boss, other identities we
   *   also manage.
   * o "we: are not the organizer, which means we changed the completion status
   *   of a todo, or we changed our attendee status from, say, tentative to
   *   accepted. In both cases we only mail the organizer. All other changes
   *   bring us out of sync with the organizer, so we won't mail, if the user
   *   insists on applying them.
   */

  if ( isOrganizer ) {
    /* We are the organizer. If there is more than one attendee, or if there is
     * only one, and it's not the same as the organizer, ask the user to send
     * mail. */
    if ( incidence->attendees().count() > 1
        || incidence->attendees().first()->email() != incidence->organizer().email() ) {
      QString type;
      if( incidence->type() == "Event") type = i18n("event");
      else if( incidence->type() == "Todo" ) type = i18n("task");
      else if( incidence->type() == "Journal" ) type = i18n("journal entry");
      else type = incidence->type();
      QString txt = i18n( "This %1 includes other people. "
          "Should email be sent out to the attendees?" )
        .arg( type );
      rc = KMessageBox::questionYesNoCancel( parent, txt,
          i18n("Group scheduling email") );
    } else {
      return true;
    }
  } else if( incidence->type() == "Todo" ) {
    if( method == Scheduler::Request )
      // This is an update to be sent to the organizer
      method = Scheduler::Reply;

    // Ask if the user wants to tell the organizer about the current status
    QString txt = i18n( "Do you want to send a status update to the "
                        "organizer of this task?");
    rc = KMessageBox::questionYesNo( parent, txt );
  } else if( incidence->type() == "Event" ) {
    QString txt;
    if ( statusChanged && method == Scheduler::Request ) {
      txt = i18n( "Your status as an attendee of this event "
          "changed. Do you want to send a status update to the "
          "organizer of this event?" );
      method = Scheduler::Reply;
      rc = KMessageBox::questionYesNo( parent, txt );
    } else {
      if( isDeleting )
        txt = i18n( "You are not the organizer of this event. "
            "Deleting it will bring your calendar out of sync "
            "with the organizers calendar. Do you really want "
            "to delete it?" );
      else
        txt = i18n( "You are not the organizer of this event. "
            "Editing it will bring your calendar out of sync "
            "with the organizers calendar. Do you really want "
            "to edit it?" );
      rc = KMessageBox::questionYesNo( parent, txt );
      return ( rc == KMessageBox::Yes );
    }
  } else {
    kdWarning(5850) << "Groupware messages for Journals are not implemented yet!" << endl;
    return true;
  }
  if( rc == KMessageBox::Yes ) {
    // We will be sending out a message here. Now make sure there is
    // some summary
    if( incidence->summary().isEmpty() )
      incidence->setSummary( i18n("<No summary given>") );

    // Send the mail
    KCal::MailScheduler scheduler( mCalendar );
    scheduler.performTransaction( incidence, method );

    return true;
  } else if( rc == KMessageBox::No )
    return true;
  else
    return false;
}

#include "kogroupware.moc"
<commit_msg>Remove awful hack and see if we really have a problem or not<commit_after>/*
  This file is part of the Groupware/KOrganizer integration.

  Requires the Qt and KDE widget libraries, available at no cost at
  http://www.trolltech.com and http://www.kde.org respectively

  Copyright (c) 2002-2004 Klarälvdalens Datakonsult AB
        <info@klaralvdalens-datakonsult.se>

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

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

  You should have received a copy of the GNU General Public License
  along with this program; if not, write to the Free Software
  Foundation, Inc., 59 Temple Place - Suite 330, Boston,
  MA  02111-1307, USA.

  In addition, as a special exception, the copyright holders give
  permission to link the code of this program with any edition of
  the Qt library by Trolltech AS, Norway (or with modified versions
  of Qt that use the same license as Qt), and distribute linked
  combinations including the two.  You must obey the GNU General
  Public License in all respects for all of the code used other than
  Qt.  If you modify this file, you may extend this exception to
  your version of the file, but you are not obligated to do so.  If
  you do not wish to do so, delete this exception statement from
  your version.
*/

#include "kogroupware.h"
#include "freebusymanager.h"
#include "calendarview.h"
#include "mailscheduler.h"
#include "koprefs.h"
#include <libkdepim/email.h>
#include <libkcal/attendee.h>
#include <libkcal/journal.h>
#include <kdebug.h>
#include <kmessagebox.h>
#include <kstandarddirs.h>
#include <kdirwatch.h>
#include <qfile.h>
#include <qregexp.h>
#include <qdir.h>
#include <qtimer.h>

FreeBusyManager *KOGroupware::mFreeBusyManager = 0;

KOGroupware *KOGroupware::mInstance = 0;

KOGroupware *KOGroupware::create( CalendarView *view,
                                  KCal::CalendarResources *calendar )
{
  if( !mInstance )
    mInstance = new KOGroupware( view, calendar );
  return mInstance;
}

KOGroupware *KOGroupware::instance()
{
  // Doesn't create, that is the task of create()
  Q_ASSERT( mInstance );
  return mInstance;
}

KOGroupware::KOGroupware( CalendarView* view, KCal::CalendarResources* cal )
  : QObject( 0, "kmgroupware_instance" ), mView( view ), mCalendar( cal )
{
  // Temporary hack: Wait one minute before starting the scheduling handling
  // This is because we need the full calendars to be loaded first
  // TODO: GET RID OF THIS!!! The real fix is to listen for the resources
  // being all done loading and start the scheduling after that. Even
  // better fix would be that we would be able to locate the resource
  // an event is saved in even though the resource is deactivated
  //QTimer::singleShot( 60000, this, SLOT( slotStartScheduling() ) );

  // It could be that the hack ^ is not needed after all. Test that for
  // a while. *sigh* - experimenting programming is bad
  slotStartScheduling();
}

FreeBusyManager *KOGroupware::freeBusyManager()
{
  if ( !mFreeBusyManager ) {
    mFreeBusyManager = new FreeBusyManager( this, "freebusymanager" );
    mFreeBusyManager->setCalendar( mCalendar );
    connect( mCalendar, SIGNAL( calendarChanged() ),
             mFreeBusyManager, SLOT( slotPerhapsUploadFB() ) );
  }

  return mFreeBusyManager;
}

void KOGroupware::slotStartScheduling()
{
  // Set up the dir watch of the three incoming dirs
  KDirWatch* watcher = KDirWatch::self();
  watcher->addDir( locateLocal( "data", "korganizer/income.accepted/" ) );
  watcher->addDir( locateLocal( "data", "korganizer/income.tentative/" ) );
  watcher->addDir( locateLocal( "data", "korganizer/income.cancel/" ) );
  watcher->addDir( locateLocal( "data", "korganizer/income.reply/" ) );
  connect( watcher, SIGNAL( dirty( const QString& ) ),
           this, SLOT( incomingDirChanged( const QString& ) ) );
  // Now set the ball rolling
  incomingDirChanged( locateLocal( "data", "korganizer/income.accepted/" ) );
  incomingDirChanged( locateLocal( "data", "korganizer/income.tentative/" ) );
  incomingDirChanged( locateLocal( "data", "korganizer/income.cancel/" ) );
  incomingDirChanged( locateLocal( "data", "korganizer/income.reply/" ) );
}

void KOGroupware::incomingDirChanged( const QString& path )
{
  const QString incomingDirName = locateLocal( "data","korganizer/" )
                                  + "income.";
  if ( !path.startsWith( incomingDirName ) ) {
    kdDebug(5850) << "incomingDirChanged: Wrong dir " << path << endl;
    return;
  }
  QString action = path.mid( incomingDirName.length() );
  while ( action.length() > 0 && action[ action.length()-1 ] == '/' )
    // Strip slashes at the end
    action.truncate( action.length()-1 );

  // Handle accepted invitations
  QDir dir( path );
  QStringList files = dir.entryList( QDir::Files );
  if ( files.count() == 0 )
    // No more files here
    return;

  // Read the file and remove it
  QFile f( path + "/" + files[0] );
  if (!f.open(IO_ReadOnly)) {
    kdError(5850) << "Can't open file '" << files[0] << "'" << endl;
    return;
  }
  QTextStream t(&f);
  t.setEncoding( QTextStream::UnicodeUTF8 );
  // Read the receiver email address
  QString receiver = t.readLine();
  if ( receiver == "Receiver Not Searched" )
    // The receiver was never checked
    receiver = QString::null;
  else
    // There should be an email address in here
    receiver = KPIM::getEmailAddr( receiver );
  // Read the iCal
  QString iCal = t.read();

  f.remove();

  kdDebug(5850) << "Received this for scheduling (" << action << ")\n"
                << "Receiver: " << receiver << "\niCal:\n" << iCal << endl;
  ScheduleMessage *message = mFormat.parseScheduleMessage( mCalendar, iCal );
  if ( !message ) {
    QString errorMessage;
    if (mFormat.exception())
      errorMessage = "\nError message: " + mFormat.exception()->message();
    kdDebug(5850) << "MailScheduler::retrieveTransactions() Error parsing"
                  << errorMessage << endl;
    KMessageBox::detailedError( mView,
        i18n("Error while processing an invitation or update."),
        errorMessage );
    return;
  }

  KCal::Scheduler::Method method =
    static_cast<KCal::Scheduler::Method>( message->method() );
  KCal::ScheduleMessage::Status status = message->status();
  KCal::Incidence* incidence =
    dynamic_cast<KCal::Incidence*>( message->event() );
  KCal::MailScheduler scheduler( mCalendar );
  if ( action.startsWith( "accepted" ) || action.startsWith( "tentative" ) ) {
    // Find myself and set my status. This can't be done in the scheduler,
    // since this does not know the choice I made in the KMail bpf
    KCal::Attendee::List attendees = incidence->attendees();
    KCal::Attendee::List::ConstIterator it;
    for ( it = attendees.begin(); it != attendees.end(); ++it ) {
      if( (*it)->email() == receiver ) {
        if ( action.startsWith( "accepted" ) )
          (*it)->setStatus( KCal::Attendee::Accepted );
        else
          (*it)->setStatus( KCal::Attendee::Tentative );
        break;
      }
    }
    scheduler.acceptTransaction( incidence, method, status );
  } else if ( action.startsWith( "cancel" ) )
    // Delete the old incidence, if one is present
    mCalendar->deleteIncidence( incidence );
  else if ( action.startsWith( "reply" ) )
    scheduler.acceptTransaction( incidence, method, status );
  else
    kdError(5850) << "Unknown incoming action " << action << endl;
  mView->updateView();
}

/* This function sends mails if necessary, and makes sure the user really
 * want to change his calendar.
 *
 * Return true means accept the changes
 * Return false means revert the changes
 */
bool KOGroupware::sendICalMessage( QWidget* parent,
                                   KCal::Scheduler::Method method,
                                   Incidence* incidence, bool isDeleting,
                                   bool statusChanged )
{
  // If there are no attendees, don't bother
  if( incidence->attendees().isEmpty() )
    return true;

  bool isOrganizer = KOPrefs::instance()->thatIsMe( incidence->organizer().email() );
  int rc = 0;
  /*
   * There are two scenarios:
   * o "we" are the organizer, where "we" means any of the identities or mail
   *   addresses known to Kontact/PIM. If there are attendees, we need to mail
   *   them all, even if one or more of them are also "us". Otherwise there
   *   would be no way to invite a resource or our boss, other identities we
   *   also manage.
   * o "we: are not the organizer, which means we changed the completion status
   *   of a todo, or we changed our attendee status from, say, tentative to
   *   accepted. In both cases we only mail the organizer. All other changes
   *   bring us out of sync with the organizer, so we won't mail, if the user
   *   insists on applying them.
   */

  if ( isOrganizer ) {
    /* We are the organizer. If there is more than one attendee, or if there is
     * only one, and it's not the same as the organizer, ask the user to send
     * mail. */
    if ( incidence->attendees().count() > 1
        || incidence->attendees().first()->email() != incidence->organizer().email() ) {
      QString type;
      if( incidence->type() == "Event") type = i18n("event");
      else if( incidence->type() == "Todo" ) type = i18n("task");
      else if( incidence->type() == "Journal" ) type = i18n("journal entry");
      else type = incidence->type();
      QString txt = i18n( "This %1 includes other people. "
          "Should email be sent out to the attendees?" )
        .arg( type );
      rc = KMessageBox::questionYesNoCancel( parent, txt,
          i18n("Group scheduling email") );
    } else {
      return true;
    }
  } else if( incidence->type() == "Todo" ) {
    if( method == Scheduler::Request )
      // This is an update to be sent to the organizer
      method = Scheduler::Reply;

    // Ask if the user wants to tell the organizer about the current status
    QString txt = i18n( "Do you want to send a status update to the "
                        "organizer of this task?");
    rc = KMessageBox::questionYesNo( parent, txt );
  } else if( incidence->type() == "Event" ) {
    QString txt;
    if ( statusChanged && method == Scheduler::Request ) {
      txt = i18n( "Your status as an attendee of this event "
          "changed. Do you want to send a status update to the "
          "organizer of this event?" );
      method = Scheduler::Reply;
      rc = KMessageBox::questionYesNo( parent, txt );
    } else {
      if( isDeleting )
        txt = i18n( "You are not the organizer of this event. "
            "Deleting it will bring your calendar out of sync "
            "with the organizers calendar. Do you really want "
            "to delete it?" );
      else
        txt = i18n( "You are not the organizer of this event. "
            "Editing it will bring your calendar out of sync "
            "with the organizers calendar. Do you really want "
            "to edit it?" );
      rc = KMessageBox::questionYesNo( parent, txt );
      return ( rc == KMessageBox::Yes );
    }
  } else {
    kdWarning(5850) << "Groupware messages for Journals are not implemented yet!" << endl;
    return true;
  }
  if( rc == KMessageBox::Yes ) {
    // We will be sending out a message here. Now make sure there is
    // some summary
    if( incidence->summary().isEmpty() )
      incidence->setSummary( i18n("<No summary given>") );

    // Send the mail
    KCal::MailScheduler scheduler( mCalendar );
    scheduler.performTransaction( incidence, method );

    return true;
  } else if( rc == KMessageBox::No )
    return true;
  else
    return false;
}

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