<commit_before>/*******************************************************************************
**
** Filename   : newfolderdialog.cpp
** Created on : 30 January, 2005
** Copyright  : (c) 2005 Till Adam
** Email      : adam@kde.org
**
*******************************************************************************/

/*******************************************************************************
**
**   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.
**
**   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 <qvariant.h>
#include <qpushbutton.h>
#include <qlabel.h>
#include <qlineedit.h>
#include <qcombobox.h>
#include <qlayout.h>
#include <qtooltip.h>
#include <qwhatsthis.h>
#include <qregexp.h>

#include <klocale.h>
#include <kdialogbase.h>
#include <kmessagebox.h>

#include "newfolderdialog.h"
#include "kmfolder.h"
#include "folderstorage.h"
#include "kmfolderimap.h"
#include "kmfoldercachedimap.h"
#include "kmfoldermgr.h"
#include "kmfolderdir.h"
#include "folderstorage.h"
#include "kmailicalifaceimpl.h"
#include "kmacctimap.h"
#include "kmacctcachedimap.h"

using namespace KMail;

NewFolderDialog::NewFolderDialog( QWidget* parent, KMFolder *folder )
    : KDialogBase( parent, "new_folder_dialog", false, i18n( "New Folder" ),
                   KDialogBase::Ok|KDialogBase::Cancel,
                   KDialogBase::Ok, true ),
      mFolder( folder )
{
  setWFlags( getWFlags() | WDestructiveClose );
  if ( mFolder ) {
    setCaption( i18n("New Subfolder of %1").arg( mFolder->prettyURL() ) );
  }
  QWidget* privateLayoutWidget = new QWidget( this, "mTopLevelLayout" );
  privateLayoutWidget->setGeometry( QRect( 10, 10, 260, 80 ) );
  setMainWidget( privateLayoutWidget );
  mTopLevelLayout = new QVBoxLayout( privateLayoutWidget, 0, spacingHint(),
                                     "mTopLevelLayout");

  mNameHBox = new QHBoxLayout( 0, 0, 6, "mNameHBox");

  mNameLabel = new QLabel( privateLayoutWidget, "mNameLabel" );
  mNameLabel->setText( i18n( "&Name:" ) );
  mNameHBox->addWidget( mNameLabel );

  mNameLineEdit = new QLineEdit( privateLayoutWidget, "mNameLineEdit" );
  mNameLabel->setBuddy( mNameLineEdit );
  QWhatsThis::add( mNameLineEdit, i18n( "Enter a name for the new folder." ) );
  mNameLineEdit->setFocus();
  mNameHBox->addWidget( mNameLineEdit );
  mTopLevelLayout->addLayout( mNameHBox );
  connect( mNameLineEdit, SIGNAL( textChanged ( const QString & ) ), this, SLOT( slotFolderNameChanged( const QString & ) ) );

  if ( !mFolder ||
      ( mFolder->folderType() != KMFolderTypeImap &&
        mFolder->folderType() != KMFolderTypeCachedImap ) ) {
    mFormatHBox = new QHBoxLayout( 0, 0, 6, "mFormatHBox");
    mMailboxFormatLabel = new QLabel( privateLayoutWidget, "mMailboxFormatLabel" );
    mMailboxFormatLabel->setText( i18n( "Mailbox &format:" ) );
    mFormatHBox->addWidget( mMailboxFormatLabel );

    mFormatComboBox = new QComboBox( false, privateLayoutWidget, "mFormatComboBox" );
    mMailboxFormatLabel->setBuddy( mFormatComboBox );
    QWhatsThis::add( mFormatComboBox, i18n( "Select whether you want to store the messages in this folder as one file per  message (maildir) or as one big file (mbox). KMail uses maildir by default and this only needs to be changed in rare circumstances. If you are unsure, leave this option as-is." ) );

    mFormatComboBox->insertItem("mbox", 0);
    mFormatComboBox->insertItem("maildir", 1);
    // does the below make any sense?
    //  mFormatComboBox->insertItem("search", 2);
    {
      KConfig *config = KMKernel::config();
      KConfigGroupSaver saver(config, "General");
      int type = config->readNumEntry("default-mailbox-format", 1);
      if ( type < 0 || type > 1 ) type = 1;
      mFormatComboBox->setCurrentItem( type );
    }
    mFormatHBox->addWidget( mFormatComboBox );
    mTopLevelLayout->addLayout( mFormatHBox );
  }

  // --- contents -----
  if ( kmkernel->iCalIface().isEnabled() ) {
    mContentsHBox = new QHBoxLayout( 0, 0, 6, "mContentsHBox");

    mContentsLabel = new QLabel( privateLayoutWidget, "mContentsLabel" );
    mContentsLabel->setText( i18n( "Folder &contains:" ) );
    mContentsHBox->addWidget( mContentsLabel );

    mContentsComboBox = new QComboBox( false, privateLayoutWidget, "mContentsComboBox" );
    mContentsLabel->setBuddy( mContentsComboBox );
    QWhatsThis::add( mContentsComboBox, i18n( "Select whether you want the new folder to be used for mail storage of for storage of groupware items such as tasks or notes. The default is mail. If you are unsure, leave this option as-is." ) );
    mContentsComboBox->insertItem( i18n( "Mail" ) );
    mContentsComboBox->insertItem( i18n( "Calendar" ) );
    mContentsComboBox->insertItem( i18n( "Contacts" ) );
    mContentsComboBox->insertItem( i18n( "Notes" ) );
    mContentsComboBox->insertItem( i18n( "Tasks" ) );
    mContentsComboBox->insertItem( i18n( "Journal" ) );
    if ( mFolder ) // inherit contents type from papa
      mContentsComboBox->setCurrentItem( mFolder->storage()->contentsType() );
    mContentsHBox->addWidget( mContentsComboBox );
    mTopLevelLayout->addLayout( mContentsHBox );
  }

  if ( mFolder &&
      ( mFolder->folderType() == KMFolderTypeImap ||
        mFolder->folderType() == KMFolderTypeCachedImap ) ) {
    bool rootFolder = false;
    QStringList namespaces;
    if ( mFolder->folderType() == KMFolderTypeImap ) {
      ImapAccountBase* ai = static_cast<KMFolderImap*>(mFolder->storage())->account();
      if ( mFolder->storage() == ai->rootFolder() ) {
        rootFolder = true;
        namespaces = ai->namespaces()[ImapAccountBase::PersonalNS];
      }
    }
    if ( mFolder->folderType() == KMFolderTypeCachedImap ) {
      ImapAccountBase* ai = static_cast<KMFolderCachedImap*>(mFolder->storage())->account();
      if ( ai && mFolder->storage() == ai->rootFolder() ) {
        rootFolder = true;
        namespaces = ai->namespaces()[ImapAccountBase::PersonalNS];
      }
    }
    if ( rootFolder && namespaces.count() > 1 ) {
      mNamespacesHBox = new QHBoxLayout( 0, 0, 6, "mNamespaceHBox");

      mNamespacesLabel = new QLabel( privateLayoutWidget, "mNamespacesLabel" );
      mNamespacesLabel->setText( i18n( "Namespace for &folder:" ) );
      mNamespacesHBox->addWidget( mNamespacesLabel );

      mNamespacesComboBox = new QComboBox( false, privateLayoutWidget, "mNamespacesComboBox" );
      mNamespacesLabel->setBuddy( mNamespacesComboBox );
      QWhatsThis::add( mNamespacesComboBox, i18n( "Select the personal namespace the folder should be created in." ) );
      mNamespacesComboBox->insertStringList( namespaces );
      mNamespacesHBox->addWidget( mNamespacesComboBox );
      mTopLevelLayout->addLayout( mNamespacesHBox );
    } else {
      mNamespacesComboBox = 0;
    }
  }

  resize( QSize(282, 108).expandedTo(minimumSizeHint()) );
  clearWState( WState_Polished );
  slotFolderNameChanged( mNameLineEdit->text());
}

void NewFolderDialog::slotFolderNameChanged( const QString & _text)
{
  enableButtonOK( !_text.isEmpty() );
}

void NewFolderDialog::slotOk()
{
  const QString fldName = mNameLineEdit->text();
  if ( fldName.isEmpty() ) {
     KMessageBox::error( this, i18n("Please specify a name for the new folder."),
        i18n( "No Name Specified" ) );
     return;
  }

  // names of local folders must not contain a '/'
  if ( fldName.find( '/' ) != -1 &&
       ( !mFolder ||
         ( mFolder->folderType() != KMFolderTypeImap &&
           mFolder->folderType() != KMFolderTypeCachedImap ) ) ) {
    KMessageBox::error( this, i18n( "Folder names cannot contain the / (slash) character; please choose another folder name." ) );
    return;
  }

  // folder names must not start with a '.'
  if ( fldName.startsWith( "." ) ) {
    KMessageBox::error( this, i18n( "Folder names cannot start with a . (dot) character; please choose another folder name." ) );
    return;
  }

  // names of IMAP folders must not contain the folder delimiter
  if ( mFolder &&
      ( mFolder->folderType() == KMFolderTypeImap ||
        mFolder->folderType() == KMFolderTypeCachedImap ) ) {
    QString delimiter;
    if ( mFolder->folderType() == KMFolderTypeImap ) {
      KMAcctImap* ai = static_cast<KMFolderImap*>( mFolder->storage() )->account();
      delimiter = ai->delimiterForFolder( mFolder->storage() );
    } else {
      KMAcctCachedImap* ai = static_cast<KMFolderCachedImap*>( mFolder->storage() )->account();
      delimiter = ai->delimiterForFolder( mFolder->storage() );
    }
    if ( !delimiter.isEmpty() && fldName.find( delimiter ) != -1 ) {
      KMessageBox::error( this, i18n( "Your IMAP server does not allow the character '%1'; please choose another folder name." ).arg( delimiter ) );
      return;
    }
  }

  // default parent is Top Level local folders
  KMFolderDir * selectedFolderDir = &(kmkernel->folderMgr()->dir());
  // we got a parent, let's use that
  if ( mFolder )
    selectedFolderDir = mFolder->createChildFolder();

  // check if the folder already exists
  if( selectedFolderDir->hasNamedFolder( fldName )
      && ( !( mFolder
          && ( selectedFolderDir == mFolder->parent() )
          && ( mFolder->storage()->name() == fldName ) ) ) )
  {
    const QString message = i18n( "<qt>Failed to create folder %1, folder already exists.</qt>" ).arg(fldName);
    KMessageBox::error( this, message );
    return;
  }

  /* Ok, obvious errors caught, let's try creating it for real. */
  const QString message = i18n( "<qt>Failed to create folder %1."
            "</qt> " ).arg(fldName);
  bool success = false;
  KMFolder *newFolder = 0;

   if ( mFolder && mFolder->folderType() == KMFolderTypeImap ) {
    KMFolderImap* selectedStorage = static_cast<KMFolderImap*>( mFolder->storage() );
    KMAcctImap *anAccount = selectedStorage->account();
    // check if a connection is available BEFORE creating the folder
    if (anAccount->makeConnection() == ImapAccountBase::Connected) {
      newFolder = kmkernel->imapFolderMgr()->createFolder( fldName, false, KMFolderTypeImap, selectedFolderDir );
      if ( newFolder ) {
        QString imapPath, parent;
        if ( mNamespacesComboBox ) {
          // create folder with namespace
          parent = anAccount->addPathToNamespace( mNamespacesComboBox->currentText() );
          imapPath = anAccount->createImapPath( parent, fldName );
        } else {
          imapPath = anAccount->createImapPath( selectedStorage->imapPath(), fldName );
        }
        KMFolderImap* newStorage = static_cast<KMFolderImap*>( newFolder->storage() );
        selectedStorage->createFolder(fldName, parent); // create it on the server
        newStorage->initializeFrom( selectedStorage, imapPath, QString::null );
        static_cast<KMFolderImap*>(mFolder->storage())->setAccount( selectedStorage->account() );
        success = true;
      }
    }
  } else if ( mFolder && mFolder->folderType() == KMFolderTypeCachedImap ) {
    newFolder = kmkernel->dimapFolderMgr()->createFolder( fldName, false, KMFolderTypeCachedImap, selectedFolderDir );
    if ( newFolder ) {
      KMFolderCachedImap* selectedStorage = static_cast<KMFolderCachedImap*>( mFolder->storage() );
      KMFolderCachedImap* newStorage = static_cast<KMFolderCachedImap*>( newFolder->storage() );
      newStorage->initializeFrom( selectedStorage );
      if ( mNamespacesComboBox ) {
        // create folder with namespace
        QString path = selectedStorage->account()->createImapPath(
            mNamespacesComboBox->currentText(), fldName );
        newStorage->setImapPathForCreation( path );
      }
      success = true;
    }
  } else {
    // local folder
    if (mFormatComboBox->currentItem() == 1)
      newFolder = kmkernel->folderMgr()->createFolder(fldName, false, KMFolderTypeMaildir, selectedFolderDir );
    else
      newFolder = kmkernel->folderMgr()->createFolder(fldName, false, KMFolderTypeMbox, selectedFolderDir );
    if ( newFolder )
      success = true;
  }
  if ( !success ) {
    KMessageBox::error( this, message );
    return;
  }

  // Set type field
  if ( kmkernel->iCalIface().isEnabled() && mContentsComboBox ) {
    KMail::FolderContentsType type =
      static_cast<KMail::FolderContentsType>( mContentsComboBox->currentItem() );
    newFolder->storage()->setContentsType( type );
    newFolder->storage()->writeConfig(); // connected slots will read it
  }
  KDialogBase::slotOk();
}

#include "newfolderdialog.moc"
<commit_msg>More guards against not yet set accounts. kolab/issue2387<commit_after>/*******************************************************************************
**
** Filename   : newfolderdialog.cpp
** Created on : 30 January, 2005
** Copyright  : (c) 2005 Till Adam
** Email      : adam@kde.org
**
*******************************************************************************/

/*******************************************************************************
**
**   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.
**
**   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 <qvariant.h>
#include <qpushbutton.h>
#include <qlabel.h>
#include <qlineedit.h>
#include <qcombobox.h>
#include <qlayout.h>
#include <qtooltip.h>
#include <qwhatsthis.h>
#include <qregexp.h>

#include <klocale.h>
#include <kdialogbase.h>
#include <kmessagebox.h>

#include "newfolderdialog.h"
#include "kmfolder.h"
#include "folderstorage.h"
#include "kmfolderimap.h"
#include "kmfoldercachedimap.h"
#include "kmfoldermgr.h"
#include "kmfolderdir.h"
#include "folderstorage.h"
#include "kmailicalifaceimpl.h"
#include "kmacctimap.h"
#include "kmacctcachedimap.h"

using namespace KMail;

NewFolderDialog::NewFolderDialog( QWidget* parent, KMFolder *folder )
    : KDialogBase( parent, "new_folder_dialog", false, i18n( "New Folder" ),
                   KDialogBase::Ok|KDialogBase::Cancel,
                   KDialogBase::Ok, true ),
      mFolder( folder )
{
  setWFlags( getWFlags() | WDestructiveClose );
  if ( mFolder ) {
    setCaption( i18n("New Subfolder of %1").arg( mFolder->prettyURL() ) );
  }
  QWidget* privateLayoutWidget = new QWidget( this, "mTopLevelLayout" );
  privateLayoutWidget->setGeometry( QRect( 10, 10, 260, 80 ) );
  setMainWidget( privateLayoutWidget );
  mTopLevelLayout = new QVBoxLayout( privateLayoutWidget, 0, spacingHint(),
                                     "mTopLevelLayout");

  mNameHBox = new QHBoxLayout( 0, 0, 6, "mNameHBox");

  mNameLabel = new QLabel( privateLayoutWidget, "mNameLabel" );
  mNameLabel->setText( i18n( "&Name:" ) );
  mNameHBox->addWidget( mNameLabel );

  mNameLineEdit = new QLineEdit( privateLayoutWidget, "mNameLineEdit" );
  mNameLabel->setBuddy( mNameLineEdit );
  QWhatsThis::add( mNameLineEdit, i18n( "Enter a name for the new folder." ) );
  mNameLineEdit->setFocus();
  mNameHBox->addWidget( mNameLineEdit );
  mTopLevelLayout->addLayout( mNameHBox );
  connect( mNameLineEdit, SIGNAL( textChanged ( const QString & ) ), this, SLOT( slotFolderNameChanged( const QString & ) ) );

  if ( !mFolder ||
      ( mFolder->folderType() != KMFolderTypeImap &&
        mFolder->folderType() != KMFolderTypeCachedImap ) ) {
    mFormatHBox = new QHBoxLayout( 0, 0, 6, "mFormatHBox");
    mMailboxFormatLabel = new QLabel( privateLayoutWidget, "mMailboxFormatLabel" );
    mMailboxFormatLabel->setText( i18n( "Mailbox &format:" ) );
    mFormatHBox->addWidget( mMailboxFormatLabel );

    mFormatComboBox = new QComboBox( false, privateLayoutWidget, "mFormatComboBox" );
    mMailboxFormatLabel->setBuddy( mFormatComboBox );
    QWhatsThis::add( mFormatComboBox, i18n( "Select whether you want to store the messages in this folder as one file per  message (maildir) or as one big file (mbox). KMail uses maildir by default and this only needs to be changed in rare circumstances. If you are unsure, leave this option as-is." ) );

    mFormatComboBox->insertItem("mbox", 0);
    mFormatComboBox->insertItem("maildir", 1);
    // does the below make any sense?
    //  mFormatComboBox->insertItem("search", 2);
    {
      KConfig *config = KMKernel::config();
      KConfigGroupSaver saver(config, "General");
      int type = config->readNumEntry("default-mailbox-format", 1);
      if ( type < 0 || type > 1 ) type = 1;
      mFormatComboBox->setCurrentItem( type );
    }
    mFormatHBox->addWidget( mFormatComboBox );
    mTopLevelLayout->addLayout( mFormatHBox );
  }

  // --- contents -----
  if ( kmkernel->iCalIface().isEnabled() ) {
    mContentsHBox = new QHBoxLayout( 0, 0, 6, "mContentsHBox");

    mContentsLabel = new QLabel( privateLayoutWidget, "mContentsLabel" );
    mContentsLabel->setText( i18n( "Folder &contains:" ) );
    mContentsHBox->addWidget( mContentsLabel );

    mContentsComboBox = new QComboBox( false, privateLayoutWidget, "mContentsComboBox" );
    mContentsLabel->setBuddy( mContentsComboBox );
    QWhatsThis::add( mContentsComboBox, i18n( "Select whether you want the new folder to be used for mail storage of for storage of groupware items such as tasks or notes. The default is mail. If you are unsure, leave this option as-is." ) );
    mContentsComboBox->insertItem( i18n( "Mail" ) );
    mContentsComboBox->insertItem( i18n( "Calendar" ) );
    mContentsComboBox->insertItem( i18n( "Contacts" ) );
    mContentsComboBox->insertItem( i18n( "Notes" ) );
    mContentsComboBox->insertItem( i18n( "Tasks" ) );
    mContentsComboBox->insertItem( i18n( "Journal" ) );
    if ( mFolder ) // inherit contents type from papa
      mContentsComboBox->setCurrentItem( mFolder->storage()->contentsType() );
    mContentsHBox->addWidget( mContentsComboBox );
    mTopLevelLayout->addLayout( mContentsHBox );
  }

  if ( mFolder &&
      ( mFolder->folderType() == KMFolderTypeImap ||
        mFolder->folderType() == KMFolderTypeCachedImap ) ) {
    bool rootFolder = false;
    QStringList namespaces;
    if ( mFolder->folderType() == KMFolderTypeImap ) {
      ImapAccountBase* ai = static_cast<KMFolderImap*>(mFolder->storage())->account();
      if ( mFolder->storage() == ai->rootFolder() ) {
        rootFolder = true;
        namespaces = ai->namespaces()[ImapAccountBase::PersonalNS];
      }
    }
    if ( mFolder->folderType() == KMFolderTypeCachedImap ) {
      ImapAccountBase* ai = static_cast<KMFolderCachedImap*>(mFolder->storage())->account();
      if ( ai && mFolder->storage() == ai->rootFolder() ) {
        rootFolder = true;
        namespaces = ai->namespaces()[ImapAccountBase::PersonalNS];
      }
    }
    if ( rootFolder && namespaces.count() > 1 ) {
      mNamespacesHBox = new QHBoxLayout( 0, 0, 6, "mNamespaceHBox");

      mNamespacesLabel = new QLabel( privateLayoutWidget, "mNamespacesLabel" );
      mNamespacesLabel->setText( i18n( "Namespace for &folder:" ) );
      mNamespacesHBox->addWidget( mNamespacesLabel );

      mNamespacesComboBox = new QComboBox( false, privateLayoutWidget, "mNamespacesComboBox" );
      mNamespacesLabel->setBuddy( mNamespacesComboBox );
      QWhatsThis::add( mNamespacesComboBox, i18n( "Select the personal namespace the folder should be created in." ) );
      mNamespacesComboBox->insertStringList( namespaces );
      mNamespacesHBox->addWidget( mNamespacesComboBox );
      mTopLevelLayout->addLayout( mNamespacesHBox );
    } else {
      mNamespacesComboBox = 0;
    }
  }

  resize( QSize(282, 108).expandedTo(minimumSizeHint()) );
  clearWState( WState_Polished );
  slotFolderNameChanged( mNameLineEdit->text());
}

void NewFolderDialog::slotFolderNameChanged( const QString & _text)
{
  enableButtonOK( !_text.isEmpty() );
}

void NewFolderDialog::slotOk()
{
  const QString fldName = mNameLineEdit->text();
  if ( fldName.isEmpty() ) {
     KMessageBox::error( this, i18n("Please specify a name for the new folder."),
        i18n( "No Name Specified" ) );
     return;
  }

  // names of local folders must not contain a '/'
  if ( fldName.find( '/' ) != -1 &&
       ( !mFolder ||
         ( mFolder->folderType() != KMFolderTypeImap &&
           mFolder->folderType() != KMFolderTypeCachedImap ) ) ) {
    KMessageBox::error( this, i18n( "Folder names cannot contain the / (slash) character; please choose another folder name." ) );
    return;
  }

  // folder names must not start with a '.'
  if ( fldName.startsWith( "." ) ) {
    KMessageBox::error( this, i18n( "Folder names cannot start with a . (dot) character; please choose another folder name." ) );
    return;
  }

  // names of IMAP folders must not contain the folder delimiter
  if ( mFolder &&
      ( mFolder->folderType() == KMFolderTypeImap ||
        mFolder->folderType() == KMFolderTypeCachedImap ) ) {
    QString delimiter;
    if ( mFolder->folderType() == KMFolderTypeImap ) {
      KMAcctImap* ai = static_cast<KMFolderImap*>( mFolder->storage() )->account();
      if ( ai )
        delimiter = ai->delimiterForFolder( mFolder->storage() );
    } else {
      KMAcctCachedImap* ai = static_cast<KMFolderCachedImap*>( mFolder->storage() )->account();
      if ( ai )
        delimiter = ai->delimiterForFolder( mFolder->storage() );
    }
    if ( !delimiter.isEmpty() && fldName.find( delimiter ) != -1 ) {
      KMessageBox::error( this, i18n( "Your IMAP server does not allow the character '%1'; please choose another folder name." ).arg( delimiter ) );
      return;
    }
  }

  // default parent is Top Level local folders
  KMFolderDir * selectedFolderDir = &(kmkernel->folderMgr()->dir());
  // we got a parent, let's use that
  if ( mFolder )
    selectedFolderDir = mFolder->createChildFolder();

  // check if the folder already exists
  if( selectedFolderDir->hasNamedFolder( fldName )
      && ( !( mFolder
          && ( selectedFolderDir == mFolder->parent() )
          && ( mFolder->storage()->name() == fldName ) ) ) )
  {
    const QString message = i18n( "<qt>Failed to create folder %1, folder already exists.</qt>" ).arg(fldName);
    KMessageBox::error( this, message );
    return;
  }

  /* Ok, obvious errors caught, let's try creating it for real. */
  const QString message = i18n( "<qt>Failed to create folder %1."
            "</qt> " ).arg(fldName);
  bool success = false;
  KMFolder *newFolder = 0;

   if ( mFolder && mFolder->folderType() == KMFolderTypeImap ) {
    KMFolderImap* selectedStorage = static_cast<KMFolderImap*>( mFolder->storage() );
    KMAcctImap *anAccount = selectedStorage->account();
    // check if a connection is available BEFORE creating the folder
    if (anAccount->makeConnection() == ImapAccountBase::Connected) {
      newFolder = kmkernel->imapFolderMgr()->createFolder( fldName, false, KMFolderTypeImap, selectedFolderDir );
      if ( newFolder ) {
        QString imapPath, parent;
        if ( mNamespacesComboBox ) {
          // create folder with namespace
          parent = anAccount->addPathToNamespace( mNamespacesComboBox->currentText() );
          imapPath = anAccount->createImapPath( parent, fldName );
        } else {
          imapPath = anAccount->createImapPath( selectedStorage->imapPath(), fldName );
        }
        KMFolderImap* newStorage = static_cast<KMFolderImap*>( newFolder->storage() );
        selectedStorage->createFolder(fldName, parent); // create it on the server
        newStorage->initializeFrom( selectedStorage, imapPath, QString::null );
        static_cast<KMFolderImap*>(mFolder->storage())->setAccount( selectedStorage->account() );
        success = true;
      }
    }
  } else if ( mFolder && mFolder->folderType() == KMFolderTypeCachedImap ) {
    newFolder = kmkernel->dimapFolderMgr()->createFolder( fldName, false, KMFolderTypeCachedImap, selectedFolderDir );
    if ( newFolder ) {
      KMFolderCachedImap* selectedStorage = static_cast<KMFolderCachedImap*>( mFolder->storage() );
      KMFolderCachedImap* newStorage = static_cast<KMFolderCachedImap*>( newFolder->storage() );
      newStorage->initializeFrom( selectedStorage );
      if ( mNamespacesComboBox ) {
        // create folder with namespace
        QString path = selectedStorage->account()->createImapPath(
            mNamespacesComboBox->currentText(), fldName );
        newStorage->setImapPathForCreation( path );
      }
      success = true;
    }
  } else {
    // local folder
    if (mFormatComboBox->currentItem() == 1)
      newFolder = kmkernel->folderMgr()->createFolder(fldName, false, KMFolderTypeMaildir, selectedFolderDir );
    else
      newFolder = kmkernel->folderMgr()->createFolder(fldName, false, KMFolderTypeMbox, selectedFolderDir );
    if ( newFolder )
      success = true;
  }
  if ( !success ) {
    KMessageBox::error( this, message );
    return;
  }

  // Set type field
  if ( kmkernel->iCalIface().isEnabled() && mContentsComboBox ) {
    KMail::FolderContentsType type =
      static_cast<KMail::FolderContentsType>( mContentsComboBox->currentItem() );
    newFolder->storage()->setContentsType( type );
    newFolder->storage()->writeConfig(); // connected slots will read it
  }
  KDialogBase::slotOk();
}

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


<commit_before>/*
 * #%L
 * %%
 * Copyright (C) 2011 - 2015 BMW Car IT GmbH
 * %%
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * #L%
 */
#include <concurrency/TimerData.h>
#include "joynr/Timer.h"
#include <tuple>
#include <chrono>
#include <cassert>

#include "joynr/joynrlogging.h"

using namespace joynr::joynr_logging;
Logger* joynr::Timer::logger = Logging::getInstance()->getLogger("MSG", "Timer");

joynr::Timer::Timer()
        : currentId(0),
          timers(),
          waitCondition(),
          mutex(),
          keepRunning(true),
          workerThread(&joynr::Timer::runTimer, this)
{
}

joynr::Timer::~Timer()
{
    LOG_TRACE(logger, "Dtor called");
    assert(!keepRunning);
    assert(!workerThread.joinable());
}

joynr::Timer::TimerId joynr::Timer::addTimer(
        std::function<void(joynr::Timer::TimerId)> onTimerExpired,
        std::function<void(joynr::Timer::TimerId)> onActiveTimerRemoved,
        uint64_t msToBeExpired,
        bool periodic)
{
    const milliseconds interval(msToBeExpired);
    TimerData* newTimer = NULL;

    {
        std::unique_lock<std::mutex> lock(mutex);
        if (periodic) {
            newTimer = new PeriodicTimerData(
                    ++currentId, onTimerExpired, onActiveTimerRemoved, interval);
        } else {
            newTimer = new OneShotTimerData(
                    ++currentId, onTimerExpired, onActiveTimerRemoved, interval);
        }
        timers.emplace(newTimer->getNextExpiry(), newTimer);
    }

    // If the new timer the next timer in the list we need to reorganize
    if (timers.begin()->second == newTimer) {
        LOG_TRACE(logger,
                  FormatString("New timer %0 has the earliest deadline").arg(currentId).str());
        waitCondition.notify_one();
    }
    return currentId;
}

bool joynr::Timer::removeTimer(TimerId id)
{
    for (auto it = timers.begin(); it != timers.end(); ++it) {
        if (it->second->getId() == id) {
            const bool reorganize = (it == timers.begin());

            // Send "remove" callback to event receiver
            auto callback = it->second->getRemoveCallback();
            callback(it->second->getId());

            // Call Dtor and remove from map
            {
                std::unique_lock<std::mutex> lock(mutex);
                delete it->second;
                timers.erase(it);
            }

            // Only reorganize if timer is the current timer
            if (reorganize) {
                LOG_TRACE(logger, FormatString("Reorganize after %0 was removed.").arg(id).str());
                waitCondition.notify_one();
            }
            return true;
        }
    }
    LOG_TRACE(logger, "Timer not removed");
    return false;
}

void joynr::Timer::shutdown()
{
    LOG_TRACE(logger, "shutdown() called");

    // shutdown thread to go for shure no other event fires
    keepRunning = false;
    waitCondition.notify_all();
    if (workerThread.joinable()) {
        workerThread.join();
    }

    // Notify event receivers the timer will not expire
    for (auto it = timers.begin(); it != timers.end(); ++it) {
        auto callback = it->second->getRemoveCallback();
        callback(it->second->getId());
        delete it->second;
    }
    timers.clear();
}

void joynr::Timer::runTimer()
{
    while (keepRunning) {
        {
            // Wait for initial work / timer
            std::unique_lock<std::mutex> lock(mutex);
            if (timers.empty()) {
                LOG_TRACE(logger, "List of timers is empty. Waiting.");
                waitCondition.wait(lock, [this] { return !timers.empty() || !keepRunning; });
            }
        }

        if (keepRunning && !timers.empty()) {

            // Get the first timer in the sorted map and lock until expiry
            std::unique_lock<std::mutex> lock(mutex);
            const system_clock::time_point& tp = timers.begin()->first;
            if (waitCondition.wait_until(lock, tp) == std::cv_status::timeout) {

                // In case of a race condition we should check if the time
                // point is still valid
                auto it = timers.find(tp);
                if (it == timers.end()) {
                    continue;
                }

                // send callback
                TimerData* const timer = it->second;
                auto callback = it->second->getExpiryCallback();
                callback(it->second->getId());

                // if periodic do reschedule else delete object
                if (timer->isPeriodic()) {
                    timers.emplace(timer->getNextExpiry(), timer);
                } else {
                    delete timer;
                }
                timers.erase(tp);
            } else {
                // Either a new timer with earlier deadline was added or a shutdown was triggered
                LOG_TRACE(logger, "Timer conditional wait was interrupted");
            }
        }
    }
    LOG_DEBUG(logger, "Leaving timer loop");
}
<commit_msg>[C++] fix seg fault in Timer<commit_after>/*
 * #%L
 * %%
 * Copyright (C) 2011 - 2015 BMW Car IT GmbH
 * %%
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * #L%
 */
#include <concurrency/TimerData.h>
#include "joynr/Timer.h"
#include <tuple>
#include <chrono>
#include <cassert>

#include "joynr/joynrlogging.h"

using namespace joynr::joynr_logging;
Logger* joynr::Timer::logger = Logging::getInstance()->getLogger("MSG", "Timer");

joynr::Timer::Timer()
        : currentId(0),
          timers(),
          waitCondition(),
          mutex(),
          keepRunning(true),
          workerThread(&joynr::Timer::runTimer, this)
{
}

joynr::Timer::~Timer()
{
    LOG_TRACE(logger, "Dtor called");
    assert(!keepRunning);
    assert(!workerThread.joinable());
}

joynr::Timer::TimerId joynr::Timer::addTimer(
        std::function<void(joynr::Timer::TimerId)> onTimerExpired,
        std::function<void(joynr::Timer::TimerId)> onActiveTimerRemoved,
        uint64_t msToBeExpired,
        bool periodic)
{
    const milliseconds interval(msToBeExpired);
    TimerData* newTimer = NULL;

    {
        std::unique_lock<std::mutex> lock(mutex);
        if (periodic) {
            newTimer = new PeriodicTimerData(
                    ++currentId, onTimerExpired, onActiveTimerRemoved, interval);
        } else {
            newTimer = new OneShotTimerData(
                    ++currentId, onTimerExpired, onActiveTimerRemoved, interval);
        }
        timers.emplace(newTimer->getNextExpiry(), newTimer);
    }

    // If the new timer the next timer in the list we need to reorganize
    if (timers.begin()->second == newTimer) {
        LOG_TRACE(logger,
                  FormatString("New timer %0 has the earliest deadline").arg(currentId).str());
        waitCondition.notify_one();
    }
    return currentId;
}

bool joynr::Timer::removeTimer(TimerId id)
{
    bool reorganize = false;
    // Call Dtor and remove from map
    {
        std::unique_lock<std::mutex> lock(mutex);
        auto it = timers.begin();
        while (it != timers.end()) {
            if (it->second->getId() == id) {
                break;
            }
            ++it;
        }
        if (it == timers.end()) {
            LOG_TRACE(logger, FormatString("Timer %1 not found. Unable to remove.").arg(id).str());
            return false;
        }
        reorganize = (it == timers.begin());

        // Send "remove" callback to event receiver
        auto callback = it->second->getRemoveCallback();
        callback(it->second->getId());

        delete it->second;
        timers.erase(it);
    }

    // Only reorganize if timer is the current timer
    if (reorganize) {
        LOG_TRACE(logger, FormatString("Reorganize after %1 was removed.").arg(id).str());
        waitCondition.notify_one();
    }
    LOG_TRACE(logger, FormatString("Timer %1 removed.").arg(id).str());
    return true;
}

void joynr::Timer::shutdown()
{
    LOG_TRACE(logger, "shutdown() called");

    // shutdown thread to go for shure no other event fires
    keepRunning = false;
    waitCondition.notify_all();
    if (workerThread.joinable()) {
        workerThread.join();
    }

    // Notify event receivers the timer will not expire
    for (auto it = timers.begin(); it != timers.end(); ++it) {
        auto callback = it->second->getRemoveCallback();
        callback(it->second->getId());
        delete it->second;
    }
    timers.clear();
}

void joynr::Timer::runTimer()
{
    while (keepRunning) {
        {
            // Wait for initial work / timer
            std::unique_lock<std::mutex> lock(mutex);
            if (timers.empty()) {
                LOG_TRACE(logger, "List of timers is empty. Waiting.");
                waitCondition.wait(lock, [this] { return !timers.empty() || !keepRunning; });
            }
        }

        if (keepRunning && !timers.empty()) {

            // Get the first timer in the sorted map and lock until expiry
            std::unique_lock<std::mutex> lock(mutex);
            const system_clock::time_point& tp = timers.begin()->first;
            if (waitCondition.wait_until(lock, tp) == std::cv_status::timeout) {

                // In case of a race condition we should check if the time
                // point is still valid
                auto it = timers.find(tp);
                if (it == timers.end()) {
                    continue;
                }

                // send callback
                TimerData* const timer = it->second;
                auto callback = it->second->getExpiryCallback();
                callback(it->second->getId());

                // if periodic do reschedule else delete object
                if (timer->isPeriodic()) {
                    timers.emplace(timer->getNextExpiry(), timer);
                } else {
                    delete timer;
                }
                timers.erase(tp);
            } else {
                // Either a new timer with earlier deadline was added or a shutdown was triggered
                LOG_TRACE(logger, "Timer conditional wait was interrupted");
            }
        }
    }
    LOG_DEBUG(logger, "Leaving timer loop");
}
<|endoftext|>


<commit_before>
#include <glib.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>

#include <wifi.h>
#include <netdb.h>
#include <sys/ioctl.h>
#include <sys/un.h>
#include <fcntl.h>
#include <errno.h>
#include <assert.h>
#include <tizen_error.h>

#include <dlog.h>
#include <udp_test.h>

#include <vconf.h>

#define UDP_PORT    0x8000
#define MAXLINE    1024

int socket_fd;

int msg_send_func(unsigned int ulMsgId, char *strMsg, unsigned int ul1stValue, unsigned int ul2ndValue)
{
	struct stMsg stSendBuf;
	struct sockaddr_in destaddr;
	int addrlen = sizeof(destaddr);
	FILE *fp;
	char ip_addr[16];

	memset(ip_addr, 0, sizeof(ip_addr));

	fp = fopen("/temp/app_relay_sever_ip.txt", "r");
	fread(ip_addr, 1, 15, fp);
	fclose(fp);

	printf("\n\r Dest Ip Addres is %s \n\r",ip_addr);

	memset(&stSendBuf, 0x0, sizeof(stSendBuf));

	stSendBuf.ulMsgId = htonl(ulMsgId);
	strcpy(stSendBuf.cName, strMsg);
	stSendBuf.ulValue[0] = htonl(ul1stValue);
	stSendBuf.ulValue[1] = htonl(ul2ndValue);

	// Sender
    destaddr.sin_family = AF_INET;
    destaddr.sin_addr.s_addr = inet_addr((const char*)ip_addr);
    destaddr.sin_port = htons(UDP_PORT);

	if((sendto(socket_fd, &stSendBuf, sizeof(struct stMsg), 0, (struct sockaddr *)&destaddr, addrlen)) < 0)
	{
		perror("sendto fail");
		exit(0);
	}
}

gboolean udp_test_thread(GIOChannel *source, GIOCondition condition, gpointer data)
{
	int rv,icnt;
	char a[10];

	printf("Event received from stdin\n");

	rv = read(0, a, 10);
	if (a[0] == '\n' || a[0] == '\r') {
		printf("==================================\n\r");
    	printf("1) Send Connection Req\n\r");
    	printf("2) Send Report Data  Req\n\r");
		printf("q) Send Report Data  Req\n\r");
    	printf("==================================\n\r");
		printf("ENTER  - Show options menu.......\n");
	}

	switch (a[0])
	{
		case '1':
			printf("Send Connenction Req Message \n\r");
			msg_send_func(CONNECTION_REQ, "", 0, 0);
			break;

		case '2':
			printf("Send Report Data Req Message \n\r");
			msg_send_func(REPORT_DATA_REQ, "/abc/hyojin.mp3", 1234, 87);
			break;

		case 'q':
			return TRUE;
			break;

		default:
			break;
	}

	return TRUE;
}

bool bConnectionDone = FALSE;
unsigned int ulSendCount = 0;

void global_socket_init()
{
	struct sockaddr_in srcaddr;
	int addrlen = sizeof(srcaddr);
	int iMode;

	close(socket_fd);

	if((socket_fd = socket(PF_INET, SOCK_DGRAM, 0)) < 0) {
        perror("socket fail");
        exit(0);
    }

	// Receiver
	srcaddr.sin_family = AF_INET;
	srcaddr.sin_addr.s_addr = htonl(INADDR_ANY);
	srcaddr.sin_port = htons(UDP_PORT);

	#if 1
    iMode = 1;
    if (ioctl(socket_fd, FIONBIO, &iMode))
    {
        perror("ioctl failed");
        exit(0);
    }
    #endif

	if(bind(socket_fd, (struct sockaddr *)&srcaddr, addrlen) < 0) {
	    perror("bind fail");
	    exit(0);
	}
}

void *udp_thread_start(void*)
{
	char RecvBuf[MAXLINE];
	struct stMsg *stUdpMsg;
	int nbyte;
	struct sockaddr_in cliaddr;
	int addrlen = sizeof(cliaddr);
	int icnt;
	double progress;
	unsigned a,b;

	global_socket_init();

	while(1)
	{
		ALOGI(
"\n\rNow waiting...\n\r");

		memset(RecvBuf, 0, sizeof(RecvBuf));
		nbyte = recvfrom(socket_fd, RecvBuf, MAXLINE , 0, (struct sockaddr *)&cliaddr, (socklen_t *)&addrlen);
		if(nbyte > 0)
		{
			stUdpMsg = (struct stMsg *)RecvBuf;

			printf("\n\r");
			printf("Message ID : 0x%08X \n\r", ntohl(stUdpMsg->ulMsgId));
			printf("File Name  : [%s] \n\r", stUdpMsg->cName);
			printf("1st  Value : %d \n\r", ntohl(stUdpMsg->ulValue[0]));
			printf("2nd  Value : %d \n\r", ntohl(stUdpMsg->ulValue[1]));
			printf("3rd  Value : %d \n\r", ntohl(stUdpMsg->ulValue[2]));
			printf("4th  Value : %d \n\r", ntohl(stUdpMsg->ulValue[3]));

			switch(ntohl(stUdpMsg->ulMsgId))
			{
				case CONNECTION_RSP:
					printf("Get Connection Rsp Message\n\r");
					printf("Connection complete!!\n\r");
					bConnectionDone = TRUE;
					break;

				case REPORT_DATA_RSP:
					printf("Get Report Rsp Message\n\r");
					break;

				case PUSH_DATA_REQ:
					printf("Get Push Data Req Message\n\r");
					msg_send_func(PUSH_DATA_RSP, "", 0, 0);

					// To Do : process value , Launch Music Player, send Posisition Data
					a = ntohl(stUdpMsg->ulValue[0]);
					b = ntohl(stUdpMsg->ulValue[1]);
					progress = (double)a + ((double)b / 1000.);

					vconf_set_dbl("memory/private/org.tizen.music-player/pos", progress);

					break;

				default :
					break;
			}
		}

		if(bConnectionDone == FALSE)
		{
			printf("Send Connenction Req Message \n\r");
			msg_send_func(CONNECTION_REQ, "", 0, 0);
			ulSendCount++;
		}

		if(ulSendCount > 5)
		{
			ulSendCount = 0;
			global_socket_init();
		}

		sleep(1);
	}

	close(socket_fd);
}

<commit_msg>modify udp client to get data from the server<commit_after>
#include <glib.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>

#include <wifi.h>
#include <netdb.h>
#include <sys/ioctl.h>
#include <sys/un.h>
#include <fcntl.h>
#include <errno.h>
#include <assert.h>
#include <tizen_error.h>

#include <dlog.h>
#include <udp_test.h>

#include <vconf.h>

#define UDP_PORT    0x8000
#define MAXLINE    1024

int socket_fd;

int msg_send_func(unsigned int ulMsgId, char *strMsg, unsigned int ul1stValue, unsigned int ul2ndValue)
{
	struct stMsg stSendBuf;
	struct sockaddr_in destaddr;
	int addrlen = sizeof(destaddr);
	FILE *fp;
	char ip_addr[16];

	memset(ip_addr, 0, sizeof(ip_addr));

	fp = fopen("/temp/app_relay_sever_ip.txt", "r");
	fread(ip_addr, 1, 15, fp);
	fclose(fp);

	printf("\n\r Dest Ip Addres is %s \n\r",ip_addr);

	memset(&stSendBuf, 0x0, sizeof(stSendBuf));

	stSendBuf.ulMsgId = htonl(ulMsgId);
	strcpy(stSendBuf.cName, strMsg);
	stSendBuf.ulValue[0] = htonl(ul1stValue);
	stSendBuf.ulValue[1] = htonl(ul2ndValue);

	// Sender
    destaddr.sin_family = AF_INET;
    destaddr.sin_addr.s_addr = inet_addr((const char*)ip_addr);
    destaddr.sin_port = htons(UDP_PORT);

	if((sendto(socket_fd, &stSendBuf, sizeof(struct stMsg), 0, (struct sockaddr *)&destaddr, addrlen)) < 0)
	{
		perror("sendto fail");
		exit(0);
	}
}

gboolean udp_test_thread(GIOChannel *source, GIOCondition condition, gpointer data)
{
	int rv,icnt;
	char a[10];

	printf("Event received from stdin\n");

	rv = read(0, a, 10);
	if (a[0] == '\n' || a[0] == '\r') {
		printf("==================================\n\r");
    	printf("1) Send Connection Req\n\r");
    	printf("2) Send Report Data  Req\n\r");
		printf("q) Send Report Data  Req\n\r");
    	printf("==================================\n\r");
		printf("ENTER  - Show options menu.......\n");
	}

	switch (a[0])
	{
		case '1':
			printf("Send Connenction Req Message \n\r");
			msg_send_func(CONNECTION_REQ, "", 0, 0);
			break;

		case '2':
			printf("Send Report Data Req Message \n\r");
			msg_send_func(REPORT_DATA_REQ, "/abc/hyojin.mp3", 1234, 87);
			break;

		case 'q':
			return TRUE;
			break;

		default:
			break;
	}

	return TRUE;
}

bool bConnectionDone = FALSE;
unsigned int ulSendCount = 0;

void global_socket_init()
{
	struct sockaddr_in srcaddr;
	int addrlen = sizeof(srcaddr);
	int iMode;

	close(socket_fd);

	if((socket_fd = socket(PF_INET, SOCK_DGRAM, 0)) < 0) {
        perror("socket fail");
        exit(0);
    }

	// Receiver
	srcaddr.sin_family = AF_INET;
	srcaddr.sin_addr.s_addr = htonl(INADDR_ANY);
	srcaddr.sin_port = htons(UDP_PORT);

	#if 1
    iMode = 1;
    if (ioctl(socket_fd, FIONBIO, &iMode))
    {
        perror("ioctl failed");
        exit(0);
    }
    #endif

	if(bind(socket_fd, (struct sockaddr *)&srcaddr, addrlen) < 0) {
	    perror("bind fail");
	    exit(0);
	}
}

void *udp_thread_start(void*)
{
	char RecvBuf[MAXLINE];
	struct stMsg *stUdpMsg;
	int nbyte;
	struct sockaddr_in cliaddr;
	int addrlen = sizeof(cliaddr);
	int icnt;
	double progress;
	unsigned a,b;

	global_socket_init();

	while(1)
	{
		ALOGI(
"\n\rNow waiting...\n\r");

		memset(RecvBuf, 0, sizeof(RecvBuf));
		nbyte = recvfrom(socket_fd, RecvBuf, MAXLINE , 0, (struct sockaddr *)&cliaddr, (socklen_t *)&addrlen);
		if(nbyte > 0)
		{
			stUdpMsg = (struct stMsg *)RecvBuf;

			printf("\n\r");
			printf("Message ID : 0x%08X \n\r", ntohl(stUdpMsg->ulMsgId));
			printf("1st  Value : %d \n\r", stUdpMsg->ulValue[0]);
			printf("2nd  Value : %d \n\r", stUdpMsg->ulValue[1]);
			printf("3rd  Value : %d \n\r", stUdpMsg->ulValue[2]);
			printf("4th  Value : %d \n\r", stUdpMsg->ulValue[3]);
			printf("File Name  : [%s] \n\r", stUdpMsg->cName);

			switch(ntohl(stUdpMsg->ulMsgId))
			{
				case CONNECTION_RSP:
					printf("Get Connection Rsp Message\n\r");
					printf("Connection complete!!\n\r");
					bConnectionDone = TRUE;
					break;

				case REPORT_DATA_RSP:
					printf("Get Report Rsp Message\n\r");
					break;

				case PUSH_DATA_REQ:
					printf("Get Push Data Req Message\n\r");
					msg_send_func(PUSH_DATA_RSP, "", 0, 0);

					// To Do : process value , Launch Music Player, send Posisition Data
					a = ntohl(stUdpMsg->ulValue[0]);
					b = ntohl(stUdpMsg->ulValue[1]);
					progress = (double)a + ((double)b / 1000.);

					vconf_set_dbl("memory/private/org.tizen.music-player/pos", progress);

					break;

				default :
					break;
			}
		}

		if(bConnectionDone == FALSE)
		{
			printf("Send Connenction Req Message \n\r");
			msg_send_func(CONNECTION_REQ, "", 0, 0);
			ulSendCount++;
		}

		if(ulSendCount > 5)
		{
			ulSendCount = 0;
			global_socket_init();
		}

		sleep(1);
	}

	close(socket_fd);
}

<|endoftext|>


<commit_before>// FIXME: Disabled until catch IRgen change lands.
// RUNX: %clang_cc1 -emit-llvm %s -o - -triple=i386-pc-win32 -mconstructor-aliases -fcxx-exceptions -fexceptions -fno-rtti -DTRY   | FileCheck %s -check-prefix=TRY
// RUNX: %clang_cc1 -emit-llvm %s -o - -triple=i386-pc-win32 -mconstructor-aliases -fcxx-exceptions -fexceptions -fno-rtti -DTHROW | FileCheck %s -check-prefix=THROW

void external();

inline void not_emitted() {
  throw int(13); // no error
}

int main() {
  int rv = 0;
#ifdef TRY
  try {
    external(); // TRY: invoke void @"\01?external@@YAXXZ"
  } catch (int) {
    rv = 1;
    // TRY: call i8* @llvm.eh.begincatch
    // TRY: call void @llvm.eh.endcatch
  }
#endif
#ifdef THROW
  // THROW: call void @"\01?terminate@@YAXXZ"
  throw int(42);
#endif
  return rv;
}
<commit_msg>Disable the right RUN line<commit_after>// FIXME: Disabled until catch IRgen change lands.
// RUNX: %clang_cc1 -emit-llvm %s -o - -triple=i386-pc-win32 -mconstructor-aliases -fcxx-exceptions -fexceptions -fno-rtti -DTRY   | FileCheck %s -check-prefix=TRY
// RUN: %clang_cc1 -emit-llvm %s -o - -triple=i386-pc-win32 -mconstructor-aliases -fcxx-exceptions -fexceptions -fno-rtti -DTHROW | FileCheck %s -check-prefix=THROW

void external();

inline void not_emitted() {
  throw int(13); // no error
}

int main() {
  int rv = 0;
#ifdef TRY
  try {
    external(); // TRY: invoke void @"\01?external@@YAXXZ"
  } catch (int) {
    rv = 1;
    // TRY: call i8* @llvm.eh.begincatch
    // TRY: call void @llvm.eh.endcatch
  }
#endif
#ifdef THROW
  // THROW: call void @"\01?terminate@@YAXXZ"
  throw int(42);
#endif
  return rv;
}
<|endoftext|>


<commit_before>// RUN: %clang_cc1 -verify -std=c++2a -fsyntax-only -triple x86_64-apple-macosx10.14.0 %s
// RUN: %clang_cc1 -verify -std=c++2a -fsyntax-only -triple x86_64-apple-macosx10.14.0 %s -fno-signed-char
// RUN: %clang_cc1 -verify -std=c++2a -fsyntax-only -triple aarch64_be-linux-gnu %s

#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
#  define LITTLE_END 1
#elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
#  define LITTLE_END 0
#else
#  error "huh?"
#endif

template <class T, class V> struct is_same {
  static constexpr bool value = false;
};
template <class T> struct is_same<T, T> {
  static constexpr bool value = true;
};

static_assert(sizeof(int) == 4);
static_assert(sizeof(long long) == 8);

template <class To, class From>
constexpr To bit_cast(const From &from) {
  static_assert(sizeof(To) == sizeof(From));
#ifdef __CHAR_UNSIGNED__
  // expected-note@+4 2 {{indeterminate value can only initialize an object of type 'unsigned char', 'char', or 'std::byte'; 'signed char' is invalid}}
#else
  // expected-note@+2 2 {{indeterminate value can only initialize an object of type 'unsigned char' or 'std::byte'; 'signed char' is invalid}}
#endif
  return __builtin_bit_cast(To, from);
}

template <class Intermediate, class Init>
constexpr bool round_trip(const Init &init) {
  return bit_cast<Init>(bit_cast<Intermediate>(init)) == init;
}

void test_int() {
  static_assert(round_trip<unsigned>((int)-1));
  static_assert(round_trip<unsigned>((int)0x12345678));
  static_assert(round_trip<unsigned>((int)0x87654321));
  static_assert(round_trip<unsigned>((int)0x0C05FEFE));
}

void test_array() {
  constexpr unsigned char input[] = {0xCA, 0xFE, 0xBA, 0xBE};
  constexpr unsigned expected = LITTLE_END ? 0xBEBAFECA : 0xCAFEBABE;
  static_assert(bit_cast<unsigned>(input) == expected);
}

void test_record() {
  struct int_splicer {
    unsigned x;
    unsigned y;

    constexpr bool operator==(const int_splicer &other) const {
      return other.x == x && other.y == y;
    }
  };

  constexpr int_splicer splice{0x0C05FEFE, 0xCAFEBABE};

  static_assert(bit_cast<unsigned long long>(splice) == LITTLE_END
                ? 0xCAFEBABE0C05FEFE
                : 0x0C05FEFECAFEBABE);

  static_assert(bit_cast<int_splicer>(0xCAFEBABE0C05FEFE).x == LITTLE_END
                ? 0x0C05FEFE
                : 0xCAFEBABE);

  static_assert(round_trip<unsigned long long>(splice));
  static_assert(round_trip<long long>(splice));

  struct base2 {
  };

  struct base3 {
    unsigned z;
  };

  struct bases : int_splicer, base2, base3 {
    unsigned doublez;
  };

  struct tuple4 {
    unsigned x, y, z, doublez;

    constexpr bool operator==(tuple4 const &other) const {
      return x == other.x && y == other.y &&
             z == other.z && doublez == other.doublez;
    }
  };
  constexpr bases b = {{1, 2}, {}, {3}, 4};
  constexpr tuple4 t4 = bit_cast<tuple4>(b);
  static_assert(t4 == tuple4{1, 2, 3, 4});
  static_assert(round_trip<tuple4>(b));
}

void test_partially_initialized() {
  struct pad {
    signed char x;
    int y;
  };

  struct no_pad {
    signed char x;
    signed char p1, p2, p3;
    int y;
  };

  static_assert(sizeof(pad) == sizeof(no_pad));

  constexpr pad pir{4, 4};
  // expected-error@+2 {{constexpr variable 'piw' must be initialized by a constant expression}}
  // expected-note@+1 {{in call to 'bit_cast(pir)'}}
  constexpr int piw = bit_cast<no_pad>(pir).x;

  // expected-error@+2 {{constexpr variable 'bad' must be initialized by a constant expression}}
  // expected-note@+1 {{in call to 'bit_cast(pir)'}}
  constexpr no_pad bad = bit_cast<no_pad>(pir);

  constexpr pad fine = bit_cast<pad>(no_pad{1, 2, 3, 4, 5});
  static_assert(fine.x == 1 && fine.y == 5);
}

void no_bitfields() {
  // FIXME!
  struct S {
    unsigned char x : 8;
  };

  struct G {
    unsigned char x : 8;
  };

  constexpr S s{0};
  // expected-error@+2 {{constexpr variable 'g' must be initialized by a constant expression}}
  // expected-note@+1 {{constexpr bit_cast involving bit-field is not yet supported}}
  constexpr G g = __builtin_bit_cast(G, s);
}

void array_members() {
  struct S {
    int ar[3];

    constexpr bool operator==(const S &rhs) {
      return ar[0] == rhs.ar[0] && ar[1] == rhs.ar[1] && ar[2] == rhs.ar[2];
    }
  };

  struct G {
    int a, b, c;

    constexpr bool operator==(const G &rhs) {
      return a == rhs.a && b == rhs.b && c == rhs.c;
    }
  };

  constexpr S s{{1, 2, 3}};
  constexpr G g = bit_cast<G>(s);
  static_assert(g.a == 1 && g.b == 2 && g.c == 3);

  static_assert(round_trip<G>(s));
  static_assert(round_trip<S>(g));
}

void bad_types() {
  union X {
    int x;
  };

  struct G {
    int g;
  };
  // expected-error@+2 {{constexpr variable 'g' must be initialized by a constant expression}}
  // expected-note@+1 {{bit_cast from a union type is not allowed in a constant expression}}
  constexpr G g = __builtin_bit_cast(G, X{0});
  // expected-error@+2 {{constexpr variable 'x' must be initialized by a constant expression}}
  // expected-note@+1 {{bit_cast to a union type is not allowed in a constant expression}}
  constexpr X x = __builtin_bit_cast(X, G{0});

  struct has_pointer {
    // expected-note@+1 2 {{invalid type 'int *' is a member of 'has_pointer'}}
    int *ptr;
  };

  // expected-error@+2 {{constexpr variable 'ptr' must be initialized by a constant expression}}
  // expected-note@+1 {{bit_cast from a pointer type is not allowed in a constant expression}}
  constexpr unsigned long ptr = __builtin_bit_cast(unsigned long, has_pointer{0});
  // expected-error@+2 {{constexpr variable 'hptr' must be initialized by a constant expression}}
  // expected-note@+1 {{bit_cast to a pointer type is not allowed in a constant expression}}
  constexpr has_pointer hptr =  __builtin_bit_cast(has_pointer, 0ul);
}

void backtrace() {
  struct A {
    // expected-note@+1 {{invalid type 'int *' is a member of 'A'}}
    int *ptr;
  };

  struct B {
    // expected-note@+1 {{invalid type 'A [10]' is a member of 'B'}}
    A as[10];
  };

  // expected-note@+1 {{invalid type 'B' is a base of 'C'}}
  struct C : B {
  };

  struct E {
    unsigned long ar[10];
  };

  // expected-error@+2 {{constexpr variable 'e' must be initialized by a constant expression}}
  // expected-note@+1 {{bit_cast from a pointer type is not allowed in a constant expression}}
  constexpr E e = __builtin_bit_cast(E, C{});
}

void test_array_fill() {
  constexpr unsigned char a[4] = {1, 2};
  constexpr unsigned int i = bit_cast<unsigned int>(a);
  static_assert(i == LITTLE_END ? 0x00000201 : 0x01020000, "");
}

typedef decltype(nullptr) nullptr_t;

#ifdef __CHAR_UNSIGNED__
// expected-note@+5 {{indeterminate value can only initialize an object of type 'unsigned char', 'char', or 'std::byte'; 'unsigned long' is invalid}}
#else
// expected-note@+3 {{indeterminate value can only initialize an object of type 'unsigned char' or 'std::byte'; 'unsigned long' is invalid}}
#endif
// expected-error@+1 {{constexpr variable 'test_from_nullptr' must be initialized by a constant expression}}
constexpr unsigned long test_from_nullptr = __builtin_bit_cast(unsigned long, nullptr);

constexpr int test_from_nullptr_pass = (__builtin_bit_cast(unsigned char[8], nullptr), 0);

constexpr int test_to_nullptr() {
  nullptr_t npt = __builtin_bit_cast(nullptr_t, 0ul);

  struct indet_mem {
    unsigned char data[sizeof(void *)];
  };
  indet_mem im = __builtin_bit_cast(indet_mem, nullptr);
  nullptr_t npt2 = __builtin_bit_cast(nullptr_t, im);

  return 0;
}

constexpr int ttn = test_to_nullptr();

// expected-warning@+2 {{returning reference to local temporary object}}
// expected-note@+1 {{temporary created here}}
constexpr const long &returns_local() { return 0L; }

// expected-error@+2 {{constexpr variable 'test_nullptr_bad' must be initialized by a constant expression}}
// expected-note@+1 {{read of temporary whose lifetime has ended}}
constexpr nullptr_t test_nullptr_bad = __builtin_bit_cast(nullptr_t, returns_local());

constexpr int test_indeterminate(bool read_indet) {
  struct pad {
    char a;
    int b;
  };

  struct no_pad {
    char a;
    unsigned char p1, p2, p3;
    int b;
  };

  pad p{1, 2};
  no_pad np = bit_cast<no_pad>(p);

  int tmp = np.a + np.b;

  unsigned char& indet_ref = np.p1;

  if (read_indet) {
    // expected-note@+1 {{read of uninitialized object is not allowed in a constant expression}}
    tmp = indet_ref;
  }

  indet_ref = 0;

  return 0;
}

constexpr int run_test_indeterminate = test_indeterminate(false);
// expected-error@+2 {{constexpr variable 'run_test_indeterminate2' must be initialized by a constant expression}}
// expected-note@+1 {{in call to 'test_indeterminate(true)'}}
constexpr int run_test_indeterminate2 = test_indeterminate(true);

struct ref_mem {
  const int &rm;
};

constexpr int global_int = 0;

// expected-error@+2 {{constexpr variable 'run_ref_mem' must be initialized by a constant expression}}
// expected-note@+1 {{bit_cast from a type with a reference member is not allowed in a constant expression}}
constexpr unsigned long run_ref_mem = __builtin_bit_cast(
    unsigned long, ref_mem{global_int});

union u {
  int im;
};

// expected-error@+2 {{constexpr variable 'run_u' must be initialized by a constant expression}}
// expected-note@+1 {{bit_cast from a union type is not allowed in a constant expression}}
constexpr int run_u = __builtin_bit_cast(int, u{32});

struct vol_mem {
  volatile int x;
};

// expected-error@+2 {{constexpr variable 'run_vol_mem' must be initialized by a constant expression}}
// expected-note@+1 {{non-literal type 'vol_mem' cannot be used in a constant expression}}
constexpr int run_vol_mem = __builtin_bit_cast(int, vol_mem{43});

struct mem_ptr {
  int vol_mem::*x; // expected-note{{invalid type 'int vol_mem::*' is a member of 'mem_ptr'}}
};
// expected-error@+2 {{constexpr variable 'run_mem_ptr' must be initialized by a constant expression}}
// expected-note@+1 {{bit_cast from a member pointer type is not allowed in a constant expression}}
constexpr int run_mem_ptr = __builtin_bit_cast(unsigned long, mem_ptr{nullptr});

struct A { char c; /* char padding : 8; */ short s; };
struct B { unsigned char x[4]; };

constexpr B one() {
  A a = {1, 2};
  return bit_cast<B>(a);
}
constexpr char good_one = one().x[0] + one().x[2] + one().x[3];
// expected-error@+2 {{constexpr variable 'bad_one' must be initialized by a constant expression}}
// expected-note@+1 {{read of uninitialized object is not allowed in a constant expression}}
constexpr char bad_one = one().x[1];

constexpr A two() {
  B b = one(); // b.x[1] is indeterminate.
  b.x[0] = 'a';
  b.x[2] = 1;
  b.x[3] = 2;
  return bit_cast<A>(b);
}
constexpr short good_two = two().c + two().s;

namespace std {
enum byte : unsigned char {};
}

enum my_byte : unsigned char {};

struct pad {
  char a;
  int b;
};

constexpr int ok_byte = (__builtin_bit_cast(std::byte[8], pad{1, 2}), 0);
constexpr int ok_uchar = (__builtin_bit_cast(unsigned char[8], pad{1, 2}), 0);

#ifdef __CHAR_UNSIGNED__
// expected-note@+5 {{indeterminate value can only initialize an object of type 'unsigned char', 'char', or 'std::byte'; 'my_byte' is invalid}}}}
#else
// expected-note@+3 {{indeterminate value can only initialize an object of type 'unsigned char' or 'std::byte'; 'my_byte' is invalid}}
#endif
// expected-error@+1 {{constexpr variable 'bad_my_byte' must be initialized by a constant expression}}
constexpr int bad_my_byte = (__builtin_bit_cast(my_byte[8], pad{1, 2}), 0);
#ifndef __CHAR_UNSIGNED__
// expected-error@+3 {{constexpr variable 'bad_char' must be initialized by a constant expression}}
// expected-note@+2 {{indeterminate value can only initialize an object of type 'unsigned char' or 'std::byte'; 'char' is invalid}}
#endif
constexpr int bad_char =  (__builtin_bit_cast(char[8], pad{1, 2}), 0);

struct pad_buffer { unsigned char data[sizeof(pad)]; };
constexpr bool test_pad_buffer() {
  pad x = {1, 2};
  pad_buffer y = __builtin_bit_cast(pad_buffer, x);
  pad z = __builtin_bit_cast(pad, y);
  return x.a == z.a && x.b == z.b;
}
static_assert(test_pad_buffer());
<commit_msg>[NFC] Fixed failed test<commit_after>// RUN: %clang_cc1 -verify -std=c++2a -fsyntax-only -triple x86_64-apple-macosx10.14.0 %s
// RUN: %clang_cc1 -verify -std=c++2a -fsyntax-only -triple x86_64-apple-macosx10.14.0 %s -fno-signed-char
// RUN: %clang_cc1 -verify -std=c++2a -fsyntax-only -triple aarch64_be-linux-gnu %s

#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
#  define LITTLE_END 1
#elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
#  define LITTLE_END 0
#else
#  error "huh?"
#endif

template <class T, class V> struct is_same {
  static constexpr bool value = false;
};
template <class T> struct is_same<T, T> {
  static constexpr bool value = true;
};

static_assert(sizeof(int) == 4);
static_assert(sizeof(long long) == 8);

template <class To, class From>
constexpr To bit_cast(const From &from) {
  static_assert(sizeof(To) == sizeof(From));
#ifdef __CHAR_UNSIGNED__
  // expected-note@+4 2 {{indeterminate value can only initialize an object of type 'unsigned char', 'char', or 'std::byte'; 'signed char' is invalid}}
#else
  // expected-note@+2 2 {{indeterminate value can only initialize an object of type 'unsigned char' or 'std::byte'; 'signed char' is invalid}}
#endif
  return __builtin_bit_cast(To, from);
}

template <class Intermediate, class Init>
constexpr bool round_trip(const Init &init) {
  return bit_cast<Init>(bit_cast<Intermediate>(init)) == init;
}

void test_int() {
  static_assert(round_trip<unsigned>((int)-1));
  static_assert(round_trip<unsigned>((int)0x12345678));
  static_assert(round_trip<unsigned>((int)0x87654321));
  static_assert(round_trip<unsigned>((int)0x0C05FEFE));
}

void test_array() {
  constexpr unsigned char input[] = {0xCA, 0xFE, 0xBA, 0xBE};
  constexpr unsigned expected = LITTLE_END ? 0xBEBAFECA : 0xCAFEBABE;
  static_assert(bit_cast<unsigned>(input) == expected);
}

void test_record() {
  struct int_splicer {
    unsigned x;
    unsigned y;

    constexpr bool operator==(const int_splicer &other) const {
      return other.x == x && other.y == y;
    }
  };

  constexpr int_splicer splice{0x0C05FEFE, 0xCAFEBABE};

  static_assert(bit_cast<unsigned long long>(splice) == LITTLE_END
                ? 0xCAFEBABE0C05FEFE
                : 0x0C05FEFECAFEBABE);

  static_assert(bit_cast<int_splicer>(0xCAFEBABE0C05FEFE).x == LITTLE_END
                ? 0x0C05FEFE
                : 0xCAFEBABE);

  static_assert(round_trip<unsigned long long>(splice));
  static_assert(round_trip<long long>(splice));

  struct base2 {
  };

  struct base3 {
    unsigned z;
  };

  struct bases : int_splicer, base2, base3 {
    unsigned doublez;
  };

  struct tuple4 {
    unsigned x, y, z, doublez;

    constexpr bool operator==(tuple4 const &other) const {
      return x == other.x && y == other.y &&
             z == other.z && doublez == other.doublez;
    }
  };
  constexpr bases b = {{1, 2}, {}, {3}, 4};
  constexpr tuple4 t4 = bit_cast<tuple4>(b);
  static_assert(t4 == tuple4{1, 2, 3, 4});
  static_assert(round_trip<tuple4>(b));
}

void test_partially_initialized() {
  struct pad {
    signed char x;
    int y;
  };

  struct no_pad {
    signed char x;
    signed char p1, p2, p3;
    int y;
  };

  static_assert(sizeof(pad) == sizeof(no_pad));

  constexpr pad pir{4, 4};
  // expected-error@+2 {{constexpr variable 'piw' must be initialized by a constant expression}}
  // expected-note@+1 {{in call to 'bit_cast(pir)'}}
  constexpr int piw = bit_cast<no_pad>(pir).x;

  // expected-error@+2 {{constexpr variable 'bad' must be initialized by a constant expression}}
  // expected-note@+1 {{in call to 'bit_cast(pir)'}}
  constexpr no_pad bad = bit_cast<no_pad>(pir);

  constexpr pad fine = bit_cast<pad>(no_pad{1, 2, 3, 4, 5});
  static_assert(fine.x == 1 && fine.y == 5);
}

void no_bitfields() {
  // FIXME!
  struct S {
    unsigned char x : 8;
  };

  struct G {
    unsigned char x : 8;
  };

  constexpr S s{0};
  // expected-error@+2 {{constexpr variable 'g' must be initialized by a constant expression}}
  // expected-note@+1 {{constexpr bit_cast involving bit-field is not yet supported}}
  constexpr G g = __builtin_bit_cast(G, s);
}

void array_members() {
  struct S {
    int ar[3];

    constexpr bool operator==(const S &rhs) {
      return ar[0] == rhs.ar[0] && ar[1] == rhs.ar[1] && ar[2] == rhs.ar[2];
    }
  };

  struct G {
    int a, b, c;

    constexpr bool operator==(const G &rhs) {
      return a == rhs.a && b == rhs.b && c == rhs.c;
    }
  };

  constexpr S s{{1, 2, 3}};
  constexpr G g = bit_cast<G>(s);
  static_assert(g.a == 1 && g.b == 2 && g.c == 3);

  static_assert(round_trip<G>(s));
  static_assert(round_trip<S>(g));
}

void bad_types() {
  union X {
    int x;
  };

  struct G {
    int g;
  };
  // expected-error@+2 {{constexpr variable 'g' must be initialized by a constant expression}}
  // expected-note@+1 {{bit_cast from a union type is not allowed in a constant expression}}
  constexpr G g = __builtin_bit_cast(G, X{0});
  // expected-error@+2 {{constexpr variable 'x' must be initialized by a constant expression}}
  // expected-note@+1 {{bit_cast to a union type is not allowed in a constant expression}}
  constexpr X x = __builtin_bit_cast(X, G{0});

  struct has_pointer {
    // expected-note@+1 2 {{invalid type 'int *' is a member of 'has_pointer'}}
    int *ptr;
  };

  // expected-error@+2 {{constexpr variable 'ptr' must be initialized by a constant expression}}
  // expected-note@+1 {{bit_cast from a pointer type is not allowed in a constant expression}}
  constexpr unsigned long ptr = __builtin_bit_cast(unsigned long, has_pointer{0});
  // expected-error@+2 {{constexpr variable 'hptr' must be initialized by a constant expression}}
  // expected-note@+1 {{bit_cast to a pointer type is not allowed in a constant expression}}
  constexpr has_pointer hptr =  __builtin_bit_cast(has_pointer, 0ul);
}

void backtrace() {
  struct A {
    // expected-note@+1 {{invalid type 'int *' is a member of 'A'}}
    int *ptr;
  };

  struct B {
    // expected-note@+1 {{invalid type 'A [10]' is a member of 'B'}}
    A as[10];
  };

  // expected-note@+1 {{invalid type 'B' is a base of 'C'}}
  struct C : B {
  };

  struct E {
    unsigned long ar[10];
  };

  // expected-error@+2 {{constexpr variable 'e' must be initialized by a constant expression}}
  // expected-note@+1 {{bit_cast from a pointer type is not allowed in a constant expression}}
  constexpr E e = __builtin_bit_cast(E, C{});
}

void test_array_fill() {
  constexpr unsigned char a[4] = {1, 2};
  constexpr unsigned int i = bit_cast<unsigned int>(a);
  static_assert(i == LITTLE_END ? 0x00000201 : 0x01020000, ""); // expected-warning {{converting the result of '?:' with integer constants to a boolean always evaluates to 'true'}}
}

typedef decltype(nullptr) nullptr_t;

#ifdef __CHAR_UNSIGNED__
// expected-note@+5 {{indeterminate value can only initialize an object of type 'unsigned char', 'char', or 'std::byte'; 'unsigned long' is invalid}}
#else
// expected-note@+3 {{indeterminate value can only initialize an object of type 'unsigned char' or 'std::byte'; 'unsigned long' is invalid}}
#endif
// expected-error@+1 {{constexpr variable 'test_from_nullptr' must be initialized by a constant expression}}
constexpr unsigned long test_from_nullptr = __builtin_bit_cast(unsigned long, nullptr);

constexpr int test_from_nullptr_pass = (__builtin_bit_cast(unsigned char[8], nullptr), 0);

constexpr int test_to_nullptr() {
  nullptr_t npt = __builtin_bit_cast(nullptr_t, 0ul);

  struct indet_mem {
    unsigned char data[sizeof(void *)];
  };
  indet_mem im = __builtin_bit_cast(indet_mem, nullptr);
  nullptr_t npt2 = __builtin_bit_cast(nullptr_t, im);

  return 0;
}

constexpr int ttn = test_to_nullptr();

// expected-warning@+2 {{returning reference to local temporary object}}
// expected-note@+1 {{temporary created here}}
constexpr const long &returns_local() { return 0L; }

// expected-error@+2 {{constexpr variable 'test_nullptr_bad' must be initialized by a constant expression}}
// expected-note@+1 {{read of temporary whose lifetime has ended}}
constexpr nullptr_t test_nullptr_bad = __builtin_bit_cast(nullptr_t, returns_local());

constexpr int test_indeterminate(bool read_indet) {
  struct pad {
    char a;
    int b;
  };

  struct no_pad {
    char a;
    unsigned char p1, p2, p3;
    int b;
  };

  pad p{1, 2};
  no_pad np = bit_cast<no_pad>(p);

  int tmp = np.a + np.b;

  unsigned char& indet_ref = np.p1;

  if (read_indet) {
    // expected-note@+1 {{read of uninitialized object is not allowed in a constant expression}}
    tmp = indet_ref;
  }

  indet_ref = 0;

  return 0;
}

constexpr int run_test_indeterminate = test_indeterminate(false);
// expected-error@+2 {{constexpr variable 'run_test_indeterminate2' must be initialized by a constant expression}}
// expected-note@+1 {{in call to 'test_indeterminate(true)'}}
constexpr int run_test_indeterminate2 = test_indeterminate(true);

struct ref_mem {
  const int &rm;
};

constexpr int global_int = 0;

// expected-error@+2 {{constexpr variable 'run_ref_mem' must be initialized by a constant expression}}
// expected-note@+1 {{bit_cast from a type with a reference member is not allowed in a constant expression}}
constexpr unsigned long run_ref_mem = __builtin_bit_cast(
    unsigned long, ref_mem{global_int});

union u {
  int im;
};

// expected-error@+2 {{constexpr variable 'run_u' must be initialized by a constant expression}}
// expected-note@+1 {{bit_cast from a union type is not allowed in a constant expression}}
constexpr int run_u = __builtin_bit_cast(int, u{32});

struct vol_mem {
  volatile int x;
};

// expected-error@+2 {{constexpr variable 'run_vol_mem' must be initialized by a constant expression}}
// expected-note@+1 {{non-literal type 'vol_mem' cannot be used in a constant expression}}
constexpr int run_vol_mem = __builtin_bit_cast(int, vol_mem{43});

struct mem_ptr {
  int vol_mem::*x; // expected-note{{invalid type 'int vol_mem::*' is a member of 'mem_ptr'}}
};
// expected-error@+2 {{constexpr variable 'run_mem_ptr' must be initialized by a constant expression}}
// expected-note@+1 {{bit_cast from a member pointer type is not allowed in a constant expression}}
constexpr int run_mem_ptr = __builtin_bit_cast(unsigned long, mem_ptr{nullptr});

struct A { char c; /* char padding : 8; */ short s; };
struct B { unsigned char x[4]; };

constexpr B one() {
  A a = {1, 2};
  return bit_cast<B>(a);
}
constexpr char good_one = one().x[0] + one().x[2] + one().x[3];
// expected-error@+2 {{constexpr variable 'bad_one' must be initialized by a constant expression}}
// expected-note@+1 {{read of uninitialized object is not allowed in a constant expression}}
constexpr char bad_one = one().x[1];

constexpr A two() {
  B b = one(); // b.x[1] is indeterminate.
  b.x[0] = 'a';
  b.x[2] = 1;
  b.x[3] = 2;
  return bit_cast<A>(b);
}
constexpr short good_two = two().c + two().s;

namespace std {
enum byte : unsigned char {};
}

enum my_byte : unsigned char {};

struct pad {
  char a;
  int b;
};

constexpr int ok_byte = (__builtin_bit_cast(std::byte[8], pad{1, 2}), 0);
constexpr int ok_uchar = (__builtin_bit_cast(unsigned char[8], pad{1, 2}), 0);

#ifdef __CHAR_UNSIGNED__
// expected-note@+5 {{indeterminate value can only initialize an object of type 'unsigned char', 'char', or 'std::byte'; 'my_byte' is invalid}}}}
#else
// expected-note@+3 {{indeterminate value can only initialize an object of type 'unsigned char' or 'std::byte'; 'my_byte' is invalid}}
#endif
// expected-error@+1 {{constexpr variable 'bad_my_byte' must be initialized by a constant expression}}
constexpr int bad_my_byte = (__builtin_bit_cast(my_byte[8], pad{1, 2}), 0);
#ifndef __CHAR_UNSIGNED__
// expected-error@+3 {{constexpr variable 'bad_char' must be initialized by a constant expression}}
// expected-note@+2 {{indeterminate value can only initialize an object of type 'unsigned char' or 'std::byte'; 'char' is invalid}}
#endif
constexpr int bad_char =  (__builtin_bit_cast(char[8], pad{1, 2}), 0);

struct pad_buffer { unsigned char data[sizeof(pad)]; };
constexpr bool test_pad_buffer() {
  pad x = {1, 2};
  pad_buffer y = __builtin_bit_cast(pad_buffer, x);
  pad z = __builtin_bit_cast(pad, y);
  return x.a == z.a && x.b == z.b;
}
static_assert(test_pad_buffer());
<|endoftext|>


<commit_before>
// STL includes
#include <cerrno>
#include <cstring>

// Local LedDevice includes
#include "LedDeviceTinkerforge.h"

static const unsigned MAX_NUM_LEDS = 320;
static const unsigned MAX_NUM_LEDS_SETTABLE = 16;

LedDeviceTinkerforge::LedDeviceTinkerforge(const std::string & host, uint16_t port, const std::string & uid, const unsigned interval) :
		LedDevice(),
		_host(host),
		_port(port),
		_uid(uid),
		_interval(interval),
		_ipConnection(nullptr),
		_ledStrip(nullptr),
		_colorChannelSize(0)
{
	// empty
}

LedDeviceTinkerforge::~LedDeviceTinkerforge()
{
	// Close the device (if it is opened)
	if (_ipConnection != nullptr && _ledStrip != nullptr)
	{
		switchOff();
	}

	// Clean up claimed resources
	delete _ipConnection;
	delete _ledStrip;
}

int LedDeviceTinkerforge::open()
{
	// Check if connection is already createds
	if (_ipConnection != nullptr)
	{
		std::cout << "Attempt to open existing connection; close before opening" << std::endl;
		return -1;
	}

	// Initialise a new connection
	_ipConnection = new IPConnection;
	ipcon_create(_ipConnection);

	int connectionStatus = ipcon_connect(_ipConnection, _host.c_str(), _port);
	if (connectionStatus < 0)
	{
		std::cerr << "Attempt to connect to master brick (" << _host << ":" << _port << ") failed with status " << connectionStatus << std::endl;
		return -1;
	}

	// Create the 'LedStrip'
	_ledStrip = new LEDStrip;
	led_strip_create(_ledStrip, _uid.c_str(), _ipConnection);

	int frameStatus = led_strip_set_frame_duration(_ledStrip, _interval);
	if (frameStatus < 0)
	{
		std::cerr << "Attempt to connect to led strip bricklet (led_strip_set_frame_duration()) failed with status " << frameStatus << std::endl;
		return -1;
	}

	return 0;
}

int LedDeviceTinkerforge::write(const std::vector<ColorRgb> &ledValues)
{
	unsigned nrLedValues = ledValues.size();

	if (nrLedValues > MAX_NUM_LEDS)
	{
		std::cerr << "Invalid attempt to write led values. Not more than " << MAX_NUM_LEDS << " leds are allowed." << std::endl;
		return -1;
	}

	if (_colorChannelSize < nrLedValues)
	{
		_redChannel.resize(nrLedValues, uint8_t(0));
		_greenChannel.resize(nrLedValues, uint8_t(0));
		_blueChannel.resize(nrLedValues, uint8_t(0));
	}
	_colorChannelSize = nrLedValues;

	auto redIt   = _redChannel.begin();
	auto greenIt = _greenChannel.begin();
	auto blueIt  = _blueChannel.begin();

	for (const ColorRgb &ledValue : ledValues)
	{
		*redIt = ledValue.red;
		++redIt;
		*greenIt = ledValue.green;
		++greenIt;
		*blueIt = ledValue.blue;
		++blueIt;
	}

	return transferLedData(_ledStrip, 0, _colorChannelSize, _redChannel.data(), _greenChannel.data(), _blueChannel.data());
}

int LedDeviceTinkerforge::switchOff()
{
	std::cerr << "Switchoff" << std::endl;
	std::fill(_redChannel.begin(),   _redChannel.end(),   0);
	std::fill(_greenChannel.begin(), _greenChannel.end(), 0);
	std::fill(_blueChannel.begin(),  _blueChannel.end(),  0);

	return transferLedData(_ledStrip, 0, _colorChannelSize, _redChannel.data(), _greenChannel.data(), _blueChannel.data());
}

int LedDeviceTinkerforge::transferLedData(LEDStrip *ledStrip, unsigned index, unsigned length, uint8_t *redChannel, uint8_t *greenChannel, uint8_t *blueChannel)
{
	if (length == 0 || index >= length || length > MAX_NUM_LEDS)
	{
		return E_INVALID_PARAMETER;
	}

	uint8_t * redPtr   = redChannel;
	uint8_t * greenPtr = greenChannel;
	uint8_t * bluePtr  = blueChannel;
	for (unsigned i=index; i<length; i+=MAX_NUM_LEDS_SETTABLE)
	{
		const unsigned copyLength = (i + MAX_NUM_LEDS_SETTABLE > length) ? length - i : MAX_NUM_LEDS_SETTABLE;
		const int status = led_strip_set_rgb_values(ledStrip, i, copyLength, redPtr, greenPtr, bluePtr);
		redPtr   += copyLength;
		greenPtr += copyLength;
		bluePtr  += copyLength;

		if (status != E_OK)
		{
			std::cerr << "Setting led values failed with status " << status << std::endl;
			return status;
		}
	}

	return E_OK;
}
<commit_msg>Fixed call to thinkerforge library<commit_after>
// STL includes
#include <cerrno>
#include <cstring>

// Local LedDevice includes
#include "LedDeviceTinkerforge.h"

static const unsigned MAX_NUM_LEDS = 320;
static const unsigned MAX_NUM_LEDS_SETTABLE = 16;

LedDeviceTinkerforge::LedDeviceTinkerforge(const std::string & host, uint16_t port, const std::string & uid, const unsigned interval) :
		LedDevice(),
		_host(host),
		_port(port),
		_uid(uid),
		_interval(interval),
		_ipConnection(nullptr),
		_ledStrip(nullptr),
		_colorChannelSize(0)
{
	// empty
}

LedDeviceTinkerforge::~LedDeviceTinkerforge()
{
	// Close the device (if it is opened)
	if (_ipConnection != nullptr && _ledStrip != nullptr)
	{
		switchOff();
	}

	// Clean up claimed resources
	delete _ipConnection;
	delete _ledStrip;
}

int LedDeviceTinkerforge::open()
{
	// Check if connection is already createds
	if (_ipConnection != nullptr)
	{
		std::cout << "Attempt to open existing connection; close before opening" << std::endl;
		return -1;
	}

	// Initialise a new connection
	_ipConnection = new IPConnection;
	ipcon_create(_ipConnection);

	int connectionStatus = ipcon_connect(_ipConnection, _host.c_str(), _port);
	if (connectionStatus < 0)
	{
		std::cerr << "Attempt to connect to master brick (" << _host << ":" << _port << ") failed with status " << connectionStatus << std::endl;
		return -1;
	}

	// Create the 'LedStrip'
	_ledStrip = new LEDStrip;
	led_strip_create(_ledStrip, _uid.c_str(), _ipConnection);

	int frameStatus = led_strip_set_frame_duration(_ledStrip, _interval);
	if (frameStatus < 0)
	{
		std::cerr << "Attempt to connect to led strip bricklet (led_strip_set_frame_duration()) failed with status " << frameStatus << std::endl;
		return -1;
	}

	return 0;
}

int LedDeviceTinkerforge::write(const std::vector<ColorRgb> &ledValues)
{
	unsigned nrLedValues = ledValues.size();

	if (nrLedValues > MAX_NUM_LEDS)
	{
		std::cerr << "Invalid attempt to write led values. Not more than " << MAX_NUM_LEDS << " leds are allowed." << std::endl;
		return -1;
	}

	if (_colorChannelSize < nrLedValues)
	{
		_redChannel.resize(nrLedValues, uint8_t(0));
		_greenChannel.resize(nrLedValues, uint8_t(0));
		_blueChannel.resize(nrLedValues, uint8_t(0));
	}
	_colorChannelSize = nrLedValues;

	auto redIt   = _redChannel.begin();
	auto greenIt = _greenChannel.begin();
	auto blueIt  = _blueChannel.begin();

	for (const ColorRgb &ledValue : ledValues)
	{
		*redIt = ledValue.red;
		++redIt;
		*greenIt = ledValue.green;
		++greenIt;
		*blueIt = ledValue.blue;
		++blueIt;
	}

	return transferLedData(_ledStrip, 0, _colorChannelSize, _redChannel.data(), _greenChannel.data(), _blueChannel.data());
}

int LedDeviceTinkerforge::switchOff()
{
	std::fill(_redChannel.begin(),   _redChannel.end(),   0);
	std::fill(_greenChannel.begin(), _greenChannel.end(), 0);
	std::fill(_blueChannel.begin(),  _blueChannel.end(),  0);

	return transferLedData(_ledStrip, 0, _colorChannelSize, _redChannel.data(), _greenChannel.data(), _blueChannel.data());
}

int LedDeviceTinkerforge::transferLedData(LEDStrip *ledStrip, unsigned index, unsigned length, uint8_t *redChannel, uint8_t *greenChannel, uint8_t *blueChannel)
{
	if (length == 0 || index >= length || length > MAX_NUM_LEDS)
	{
		return E_INVALID_PARAMETER;
	}

	uint8_t reds[MAX_NUM_LEDS_SETTABLE];
	uint8_t greens[MAX_NUM_LEDS_SETTABLE];
	uint8_t blues[MAX_NUM_LEDS_SETTABLE];

	for (unsigned i=index; i<length; i+=MAX_NUM_LEDS_SETTABLE)
	{
		const unsigned copyLength = (i + MAX_NUM_LEDS_SETTABLE > length) ? length - i : MAX_NUM_LEDS_SETTABLE;
		memcpy(reds,   redChannel   + i,   copyLength);
		memcpy(greens, greenChannel + i, copyLength);
		memcpy(blues,  blueChannel  + i,  copyLength);

		const int status = led_strip_set_rgb_values(ledStrip, i, copyLength, reds, greens, blues);
		if (status != E_OK)
		{
			std::cerr << "Setting led values failed with status " << status << std::endl;
			return status;
		}
	}

	return E_OK;
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: DragMethod_RotateDiagram.cxx,v $
 * $Revision: 1.5 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

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

#include "SelectionHelper.hxx"
#include "CommonConverters.hxx"
#include "ChartModelHelper.hxx"
#include "macros.hxx"
#include "DiagramHelper.hxx"
#include "ChartTypeHelper.hxx"
#include "ThreeDHelper.hxx"
#include <svx/sdr/overlay/overlaypolypolygon.hxx>
#include <svx/sdr/overlay/overlaymanager.hxx>

// header for class E3dScene
#include <svx/scene3d.hxx>
#include <basegfx/matrix/b3dhommatrix.hxx>
#include <com/sun/star/beans/XPropertySet.hpp>

#define FIXED_SIZE_FOR_3D_CHART_VOLUME (10000.0)

//.............................................................................
namespace chart
{
//.............................................................................

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

DragMethod_RotateDiagram::DragMethod_RotateDiagram( DrawViewWrapper& rDrawViewWrapper
        , const rtl::OUString& rObjectCID
        , const Reference< frame::XModel >& xChartModel
        , RotationDirection eRotationDirection )
    : DragMethod_Base( rDrawViewWrapper, rObjectCID, xChartModel, ActionDescriptionProvider::ROTATE )
    , m_pScene(0)
    , m_aReferenceRect(100,100,100,100)
    , m_aStartPos(0,0)
    , m_aWireframePoly()
    , m_fInitialXAngleRad(0.0)
    , m_fInitialYAngleRad(0.0)
    , m_fInitialZAngleRad(0.0)
    , m_fAdditionalXAngleRad(0.0)
    , m_fAdditionalYAngleRad(0.0)
    , m_fAdditionalZAngleRad(0.0)
    , m_eRotationDirection(eRotationDirection)
    , m_bRightAngledAxes(sal_False)
{
    m_pScene = SelectionHelper::getSceneToRotate( rDrawViewWrapper.getNamedSdrObject( rObjectCID ) );
    SdrObject* pObj = rDrawViewWrapper.getSelectedObject();
    if(pObj && m_pScene)
    {
        m_aReferenceRect = pObj->GetLogicRect();
        Rectangle aTemp = m_pScene->GetLogicRect();

        m_pScene->CreateWireframe(m_aWireframePoly, NULL );

        uno::Reference< chart2::XDiagram > xDiagram( ChartModelHelper::findDiagram(this->getChartModel()) );
        uno::Reference< beans::XPropertySet > xDiagramProperties( xDiagram, uno::UNO_QUERY );
        if( xDiagramProperties.is() )
        {
            ThreeDHelper::getRotationAngleFromDiagram( xDiagramProperties
                , m_fInitialXAngleRad, m_fInitialYAngleRad, m_fInitialZAngleRad );
            if( ChartTypeHelper::isSupportingRightAngledAxes(
                DiagramHelper::getChartTypeByIndex( xDiagram, 0 ) ) )
                xDiagramProperties->getPropertyValue(C2U( "RightAngledAxes" )) >>= m_bRightAngledAxes;
            if(m_bRightAngledAxes)
            {
                if( m_eRotationDirection==ROTATIONDIRECTION_Z )
                    m_eRotationDirection=ROTATIONDIRECTION_FREE;
                ThreeDHelper::adaptRadAnglesForRightAngledAxes( m_fInitialXAngleRad, m_fInitialYAngleRad );
            }
        }
    }
}
DragMethod_RotateDiagram::~DragMethod_RotateDiagram()
{
}
void DragMethod_RotateDiagram::TakeComment(String& /*rStr*/) const
{
}
FASTBOOL DragMethod_RotateDiagram::Beg()
{
    m_aStartPos = DragStat().GetStart();
    SetDragPolys();
    Show();
    return true;
}
void DragMethod_RotateDiagram::Mov(const Point& rPnt)
{
    if( DragStat().CheckMinMoved(rPnt) )
    {
        Hide();

        //calculate new angle
        double fX = F_PI / 2.0 * (double)(rPnt.Y() - m_aStartPos.Y())
                / (double)m_aReferenceRect.GetHeight();
        double fY = F_PI * (double)(rPnt.X() - m_aStartPos.X())
                / (double)m_aReferenceRect.GetWidth();

        if( m_eRotationDirection != ROTATIONDIRECTION_Y )
            m_fAdditionalYAngleRad = fY;
        else
            m_fAdditionalYAngleRad = 0.0;
        if( m_eRotationDirection != ROTATIONDIRECTION_X )
            m_fAdditionalXAngleRad = fX;
        else
            m_fAdditionalXAngleRad = 0.0;
        m_fAdditionalZAngleRad = 0.0;

        if( m_eRotationDirection == ROTATIONDIRECTION_Z )
        {
            m_fAdditionalXAngleRad = 0.0;
            m_fAdditionalYAngleRad = 0.0;

            double fCx = m_aReferenceRect.Center().X();
            double fCy = m_aReferenceRect.Center().Y();

            m_fAdditionalZAngleRad = atan((double)(fCx - m_aStartPos.X())/(m_aStartPos.Y()-fCy))
                + atan((double)(fCx - rPnt.X())/(fCy-rPnt.Y()));
        }

        DragStat().NextMove(rPnt);
        MovAllPoints();

        Show();
    }
}
void DragMethod_RotateDiagram::CreateOverlayGeometry(::sdr::overlay::OverlayManager& rOverlayManager, ::sdr::overlay::OverlayObjectList& rOverlayList)
{
    ::basegfx::B3DHomMatrix aCurrentTransform;
    aCurrentTransform.translate( -FIXED_SIZE_FOR_3D_CHART_VOLUME/2.0,
                                 -FIXED_SIZE_FOR_3D_CHART_VOLUME/2.0,
                                 -FIXED_SIZE_FOR_3D_CHART_VOLUME/2.0 );

    double fResultX = m_fInitialXAngleRad + m_fAdditionalXAngleRad;
    double fResultY = m_fInitialYAngleRad + m_fAdditionalYAngleRad;
    double fResultZ = m_fInitialZAngleRad + m_fAdditionalZAngleRad;

    if(!m_bRightAngledAxes)
        aCurrentTransform.rotate( fResultX, fResultY, fResultZ );
    else
    {
        ThreeDHelper::adaptRadAnglesForRightAngledAxes( fResultX, fResultY );
        aCurrentTransform.shearXY(fResultY,-(fResultX));
    }

    const sal_uInt32 nPntCnt(m_aWireframePoly.count());
     if(nPntCnt > 1L && m_pScene)
    {
        B3dCamera& rCameraSet = m_pScene->GetCameraSet();
        for(sal_uInt32 b(0L); b < nPntCnt; b += 2L)
        {
            ::basegfx::B2DPolygon aLine;
            ::basegfx::B3DPoint aPnt1(aCurrentTransform * m_aWireframePoly.getB3DPoint(b));
            aPnt1 = rCameraSet.WorldToViewCoor(aPnt1);
            aLine.append(::basegfx::B2DPoint(aPnt1.getX(), aPnt1.getY()));

            ::basegfx::B3DPoint aPnt2(aCurrentTransform * m_aWireframePoly.getB3DPoint(b + 1L));
            aPnt2 = rCameraSet.WorldToViewCoor(aPnt2);
            aLine.append(::basegfx::B2DPoint(aPnt2.getX(), aPnt2.getY()));

            basegfx::B2DPolyPolygon aResult(aLine);
            ::sdr::overlay::OverlayPolyPolygonStriped* pNew = new ::sdr::overlay::OverlayPolyPolygonStriped(aResult);
            rOverlayManager.add(*pNew);
            rOverlayList.append(*pNew);
        }
    }
}

FASTBOOL DragMethod_RotateDiagram::End(FASTBOOL /* bCopy */)
{
    Hide();

    double fResultX = m_fInitialXAngleRad + m_fAdditionalXAngleRad;
    double fResultY = m_fInitialYAngleRad + m_fAdditionalYAngleRad;
    double fResultZ = m_fInitialZAngleRad + m_fAdditionalZAngleRad;

    if(m_bRightAngledAxes)
        ThreeDHelper::adaptRadAnglesForRightAngledAxes( fResultX, fResultY );

    ThreeDHelper::setRotationAngleToDiagram( uno::Reference< beans::XPropertySet >( ChartModelHelper::findDiagram( this->getChartModel() ), uno::UNO_QUERY )
        , fResultX, fResultY, fResultZ );

    return true;
}
//.............................................................................
} //namespace chart
//.............................................................................
<commit_msg>INTEGRATION: CWS chart26_DEV300 (1.4.98); FILE MERGED 2008/04/23 19:41:39 iha 1.4.98.1: #i72994# correct 3D rotation<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: DragMethod_RotateDiagram.cxx,v $
 * $Revision: 1.6 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

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

#include "SelectionHelper.hxx"
#include "CommonConverters.hxx"
#include "ChartModelHelper.hxx"
#include "macros.hxx"
#include "DiagramHelper.hxx"
#include "ChartTypeHelper.hxx"
#include "ThreeDHelper.hxx"
#include <svx/sdr/overlay/overlaypolypolygon.hxx>
#include <svx/sdr/overlay/overlaymanager.hxx>

// header for class E3dScene
#include <svx/scene3d.hxx>
#include <basegfx/matrix/b3dhommatrix.hxx>
#include <com/sun/star/beans/XPropertySet.hpp>

#define FIXED_SIZE_FOR_3D_CHART_VOLUME (10000.0)

//.............................................................................
namespace chart
{
//.............................................................................

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

DragMethod_RotateDiagram::DragMethod_RotateDiagram( DrawViewWrapper& rDrawViewWrapper
        , const rtl::OUString& rObjectCID
        , const Reference< frame::XModel >& xChartModel
        , RotationDirection eRotationDirection )
    : DragMethod_Base( rDrawViewWrapper, rObjectCID, xChartModel, ActionDescriptionProvider::ROTATE )
    , m_pScene(0)
    , m_aReferenceRect(100,100,100,100)
    , m_aStartPos(0,0)
    , m_aWireframePoly()
    , m_fInitialXAngleRad(0.0)
    , m_fInitialYAngleRad(0.0)
    , m_fInitialZAngleRad(0.0)
    , m_fAdditionalXAngleRad(0.0)
    , m_fAdditionalYAngleRad(0.0)
    , m_fAdditionalZAngleRad(0.0)
    , m_nInitialHorizontalAngleDegree(0)
    , m_nInitialVerticalAngleDegree(0)
    , m_nAdditionalHorizontalAngleDegree(0)
    , m_nAdditionalVerticalAngleDegree(0)
    , m_eRotationDirection(eRotationDirection)
    , m_bRightAngledAxes(sal_False)
{
    m_pScene = SelectionHelper::getSceneToRotate( rDrawViewWrapper.getNamedSdrObject( rObjectCID ) );
    SdrObject* pObj = rDrawViewWrapper.getSelectedObject();
    if(pObj && m_pScene)
    {
        m_aReferenceRect = pObj->GetLogicRect();
        Rectangle aTemp = m_pScene->GetLogicRect();

        m_pScene->CreateWireframe(m_aWireframePoly, NULL );

        uno::Reference< chart2::XDiagram > xDiagram( ChartModelHelper::findDiagram(this->getChartModel()) );
        uno::Reference< beans::XPropertySet > xDiagramProperties( xDiagram, uno::UNO_QUERY );
        if( xDiagramProperties.is() )
        {
            ThreeDHelper::getRotationFromDiagram( xDiagramProperties
                , m_nInitialHorizontalAngleDegree, m_nInitialVerticalAngleDegree );

            ThreeDHelper::getRotationAngleFromDiagram( xDiagramProperties
                , m_fInitialXAngleRad, m_fInitialYAngleRad, m_fInitialZAngleRad );

            if( ChartTypeHelper::isSupportingRightAngledAxes(
                DiagramHelper::getChartTypeByIndex( xDiagram, 0 ) ) )
                xDiagramProperties->getPropertyValue(C2U( "RightAngledAxes" )) >>= m_bRightAngledAxes;
            if(m_bRightAngledAxes)
            {
                if( m_eRotationDirection==ROTATIONDIRECTION_Z )
                    m_eRotationDirection=ROTATIONDIRECTION_FREE;
                ThreeDHelper::adaptRadAnglesForRightAngledAxes( m_fInitialXAngleRad, m_fInitialYAngleRad );
            }
        }
    }
}
DragMethod_RotateDiagram::~DragMethod_RotateDiagram()
{
}
void DragMethod_RotateDiagram::TakeComment(String& /*rStr*/) const
{
}
FASTBOOL DragMethod_RotateDiagram::Beg()
{
    m_aStartPos = DragStat().GetStart();
    SetDragPolys();
    Show();
    return true;
}
void DragMethod_RotateDiagram::Mov(const Point& rPnt)
{
    if( DragStat().CheckMinMoved(rPnt) )
    {
        Hide();

        //calculate new angle
        double fX = F_PI / 2.0 * (double)(rPnt.Y() - m_aStartPos.Y())
                / (double)m_aReferenceRect.GetHeight();
        double fY = F_PI * (double)(rPnt.X() - m_aStartPos.X())
                / (double)m_aReferenceRect.GetWidth();

        if( m_eRotationDirection != ROTATIONDIRECTION_Y )
            m_fAdditionalYAngleRad = fY;
        else
            m_fAdditionalYAngleRad = 0.0;
        if( m_eRotationDirection != ROTATIONDIRECTION_X )
            m_fAdditionalXAngleRad = fX;
        else
            m_fAdditionalXAngleRad = 0.0;
        m_fAdditionalZAngleRad = 0.0;

        if( m_eRotationDirection == ROTATIONDIRECTION_Z )
        {
            m_fAdditionalXAngleRad = 0.0;
            m_fAdditionalYAngleRad = 0.0;

            double fCx = m_aReferenceRect.Center().X();
            double fCy = m_aReferenceRect.Center().Y();

            m_fAdditionalZAngleRad = atan((double)(fCx - m_aStartPos.X())/(m_aStartPos.Y()-fCy))
                + atan((double)(fCx - rPnt.X())/(fCy-rPnt.Y()));
        }

        m_nAdditionalHorizontalAngleDegree = static_cast<sal_Int32>(m_fAdditionalXAngleRad*180.0/F_PI);
        m_nAdditionalVerticalAngleDegree = -static_cast<sal_Int32>(m_fAdditionalYAngleRad*180.0/F_PI);

        DragStat().NextMove(rPnt);
        MovAllPoints();

        Show();
    }
}
void DragMethod_RotateDiagram::CreateOverlayGeometry(::sdr::overlay::OverlayManager& rOverlayManager, ::sdr::overlay::OverlayObjectList& rOverlayList)
{
    ::basegfx::B3DHomMatrix aCurrentTransform;
    aCurrentTransform.translate( -FIXED_SIZE_FOR_3D_CHART_VOLUME/2.0,
                                 -FIXED_SIZE_FOR_3D_CHART_VOLUME/2.0,
                                 -FIXED_SIZE_FOR_3D_CHART_VOLUME/2.0 );

    double fResultX = m_fInitialXAngleRad + m_fAdditionalXAngleRad;
    double fResultY = m_fInitialYAngleRad + m_fAdditionalYAngleRad;
    double fResultZ = m_fInitialZAngleRad + m_fAdditionalZAngleRad;

    if(!m_bRightAngledAxes)
    {
        if( m_eRotationDirection!=ROTATIONDIRECTION_Z )
        {
            ThreeDHelper::convertElevationRotationDegToXYZAngleRad(
                m_nInitialHorizontalAngleDegree+m_nAdditionalHorizontalAngleDegree, -(m_nInitialVerticalAngleDegree+m_nAdditionalVerticalAngleDegree)
                , fResultX, fResultY, fResultZ );
        }
        aCurrentTransform.rotate( fResultX, fResultY, fResultZ );
    }
    else
    {
        ThreeDHelper::adaptRadAnglesForRightAngledAxes( fResultX, fResultY );
        aCurrentTransform.shearXY(fResultY,-(fResultX));
    }

    const sal_uInt32 nPntCnt(m_aWireframePoly.count());
     if(nPntCnt > 1L && m_pScene)
    {
        B3dCamera& rCameraSet = m_pScene->GetCameraSet();
        for(sal_uInt32 b(0L); b < nPntCnt; b += 2L)
        {
            ::basegfx::B2DPolygon aLine;
            ::basegfx::B3DPoint aPnt1(aCurrentTransform * m_aWireframePoly.getB3DPoint(b));
            aPnt1 = rCameraSet.WorldToViewCoor(aPnt1);
            aLine.append(::basegfx::B2DPoint(aPnt1.getX(), aPnt1.getY()));

            ::basegfx::B3DPoint aPnt2(aCurrentTransform * m_aWireframePoly.getB3DPoint(b + 1L));
            aPnt2 = rCameraSet.WorldToViewCoor(aPnt2);
            aLine.append(::basegfx::B2DPoint(aPnt2.getX(), aPnt2.getY()));

            basegfx::B2DPolyPolygon aResult(aLine);
            ::sdr::overlay::OverlayPolyPolygonStriped* pNew = new ::sdr::overlay::OverlayPolyPolygonStriped(aResult);
            rOverlayManager.add(*pNew);
            rOverlayList.append(*pNew);
        }
    }
}

FASTBOOL DragMethod_RotateDiagram::End(FASTBOOL /* bCopy */)
{
    Hide();

    if( m_bRightAngledAxes || m_eRotationDirection==ROTATIONDIRECTION_Z )
    {
        double fResultX = m_fInitialXAngleRad + m_fAdditionalXAngleRad;
        double fResultY = m_fInitialYAngleRad + m_fAdditionalYAngleRad;
        double fResultZ = m_fInitialZAngleRad + m_fAdditionalZAngleRad;

        if(m_bRightAngledAxes)
            ThreeDHelper::adaptRadAnglesForRightAngledAxes( fResultX, fResultY );

        ThreeDHelper::setRotationAngleToDiagram( uno::Reference< beans::XPropertySet >( ChartModelHelper::findDiagram( this->getChartModel() ), uno::UNO_QUERY )
            , fResultX, fResultY, fResultZ );
    }
    else
    {
        ThreeDHelper::setRotationToDiagram( ( uno::Reference< beans::XPropertySet >( ChartModelHelper::findDiagram( this->getChartModel() ), uno::UNO_QUERY ) )
            , m_nInitialHorizontalAngleDegree+m_nAdditionalHorizontalAngleDegree, m_nInitialVerticalAngleDegree+m_nAdditionalVerticalAngleDegree );
    }

    return true;
}
//.............................................................................
} //namespace chart
//.............................................................................
<|endoftext|>