Logo Search packages:      
Sourcecode: kmess version File versions  Download package

accountswidget.cpp

/***************************************************************************
                          accountswidget.cpp  -  description
                             -------------------
    copyright            : (C) 2004 by Madelman
                           (C) 2006 by Diederik van der Boor
    email                : mkb137b@hotmail.com
                           "vdboor" --at-- "codingdomain.com"
 ***************************************************************************/

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

#include "accountswidget.h"

#include <qwidget.h>
#include <qcheckbox.h>
#include <qcombobox.h>
#include <qfileinfo.h>
#include <qfile.h>
#include <qimage.h>
#include <qlabel.h>
#include <qlayout.h>
#include <qlineedit.h>
#include <qpixmap.h>

#include <kmessagebox.h>
#include <kdebug.h>
#include <kdeversion.h>

#include <kpassdlg.h>
#include <krun.h>
#include <kurllabel.h>

#include <kaction.h>
#include <klistbox.h>
#include <kpopupmenu.h>
#include <kpushbutton.h>
#if KDE_IS_VERSION(3,4,0)
  #include <kpixmapregionselectordialog.h>
#else
#endif

#include <kio/netaccess.h>
#include <klocale.h>
#include <kmdcodec.h>
#include <kstandarddirs.h>
#include <kfiledialog.h>



/**
 * Constructor
 */
AccountsWidget::AccountsWidget( QWidget* parent,  const char* name, WFlags fl )
: AccountsWidgetInterface( parent, name, fl ),
  hasTempImage_(false)
{

  // Find the default image
  KStandardDirs *dirs   = KGlobal::dirs();
  QString defaultImage  = dirs->findResource( "data", "kmess/pics/kmesspic.png"  );

  // Load the image in the X-Server:
  defaultPixmap_ = QPixmap(defaultImage);
  customPixmap_  = defaultPixmap_;

  // Create the "Change..." button actions
#if KDE_IS_VERSION(3,4,0)
  KPopupMenu  *browsePopup   = new KPopupMenu( this, "browsemenu" );
  KAction     *browseSimple  = new KAction( i18n("Browse..."),                "folder_open", 0, this, "browsesimple" );
  KAction     *browseResize  = new KAction( i18n("Browse and crop image..."), "editcut",     0, this, "browseresize" );
  connect( browseSimple, SIGNAL(activated()), this,  SLOT(pictureBrowseSimple() ) );
  connect( browseResize, SIGNAL(activated()), this,  SLOT(pictureBrowseResize() ) );

  // Plug the items into the browse menu button
  browseSimple->plug( browsePopup );
  browseResize->plug( browsePopup );

  // Assign the new popup to the button and detach old connection
  browseButton_->setPopup( browsePopup );
  disconnect( browseButton_, SIGNAL( clicked() ) );
#endif

  // Add the items to the initial status combo box
  QStringList statuses;
  statuses << i18n("Online")
           << i18n("Away")
           << i18n("Be Right Back")
           << i18n("Busy")
           << i18n("Out to Lunch")
           << i18n("On the Phone")
           << i18n("Invisible");
  initialStatus_->insertStringList( statuses );
}



/**
 * Destructor
 */
AccountsWidget::~AccountsWidget()
{
  // Clean up the temp file.
  if(hasTempImage_)
  {
    QFile::remove(tempImageFile_);
  }

  // no need to delete child widgets, Qt does it all for us
}



// Return the filename of the currently selected image.
QString AccountsWidget::getPictureFileName() const
{
  if( hasTempImage_ )
  {
    return tempImageFile_;
  }
  else
  {
    return imageFile_;
  }
}



/**
 * Load the dialog settings.
 */
void AccountsWidget::loadSettings(Account *account, bool isCurrentAccount)
{
  bool showImage;

  // Read settings
  myHandle_      = account->getHandle();
  imageFile_     = account->getCustomImagePath();
  tempImageFile_ = account->getCustomImagePath() + ".tmp";
  showImage      = account->getShowImage();

  // Load default properties
  friendlyNameEdit_ ->setText( account->getFriendlyName() );
  handleEdit_       ->setText( myHandle_ );
  passwordEdit_     ->setText( QString::null );

  autologinCheckBox_      ->setChecked( account->getUseAutologin()   );


  // Make sure the drop down list matches the user's initial status
  int item;
  QString status = account->getInitialStatus();
  if( status == "AWY" )
  { // Change status to AWAY
    item = 1;
  }
  else if( status == "BRB" )
  { // Change status to BE RIGHT BACK
    item = 2;
  }
  else if( status == "BSY" )
  { // Change status to BUSY
    item = 3;
  }
  else if( status == "LUN" )
  { // Change status to OUT TO LUNCH
    item = 4;
  }
  else if( status == "PHN" )
  { // Change status to ON THE PHONE
    item = 5;
  }
  else if( status == "HDN" )
  { // Change status to INVISIBLE
    item = 6;
  }
  else
  { // Change status to ONLINE
    item = 0;
  }
  initialStatus_->setCurrentItem( item );


  // The friendly name edit should only be enabled if this is the current account, and the passport account is verified;
  // the "register" text and link make sense only if this is not the current account;
  // the "verify" text and link should only be visible if the currently logged in account has not been verified.
  if( isCurrentAccount )
  {
    if( account->isVerified() )
    {
      friendlyNameEdit_ ->setEnabled( true );
      registerLabel_    ->hide();
      registerButton_   ->hide();
      verifyLabel_      ->hide();
      verifyButton_     ->hide();
    }
    else
    {
      friendlyNameEdit_ ->setEnabled( false );
      registerLabel_    ->hide();
      registerButton_   ->hide();
      verifyLabel_      ->show();
      verifyButton_     ->show();
    }
  }
  else
  {
    friendlyNameEdit_ ->setEnabled( false );
    registerLabel_    ->show();
    registerButton_   ->show();
    verifyLabel_      ->hide();
    verifyButton_     ->hide();
  }

  // When the account is a guest account, offer a method to upgrade to a real account.
  if( account->isGuestAccount() )
  {
    // Disable settings that require a real account which is saved in the config file.
    rememberMeToggled(false);
  }
  else
  {
    // Hide the upgrade function
    rememberCheckbox_->hide();
  }

  // Load the custom pixmap if we have one.
  customPixmap_ = QPixmap( imageFile_ );

  if(customPixmap_.isNull())
  {
    // Failed to load
    customPixmap_ = defaultPixmap_;
    imageFile_    = QString::null;
  }

  // Load the pixmap
  pictureLabel_->setPixmap(customPixmap_);

  // Set the "Show Image" checkbox
  // Run the event manually this time to update the GUI.
  noPictureCheckbox_->setChecked( ! showImage );
  showImageToggled( ! showImage );
}



// Show the normal browse dialog to change display picture
void AccountsWidget::pictureBrowseSimple()
{
  selectImage( false );
}



// Show the browse dialog to change display picture and then allow the user to crop it
void AccountsWidget::pictureBrowseResize()
{
  selectImage( true );
}



/**
 * Save the settings in the account object.
 */
void AccountsWidget::saveSettings( Account *account )
{
  QString   password;
  QString   imageName     = 0;
  QString   tempImageName = 0;
  QString   initialStatus;
  QDir      imageFolder;
  bool      showImage;
  bool      success;

  // Read settings
  showImage = ! noPictureCheckbox_->isChecked();

  // When the account is a guest account, see if the user wanted to "upgrade" it.
  if( account->isGuestAccount() )
  {
    if( rememberCheckbox_->isChecked() )
    {
      account->setGuestAccount(false);
    }
  }

  // Update the settings
  account->setLoginInformation( handleEdit_->text(), friendlyNameEdit_->text(), passwordEdit_->password() );
  account->setUseAutologin( autologinCheckBox_->isChecked() );
  account->setShowImage( showImage );

  // Update the initial status
  initialStatus = initialStatus_->currentText();
  if( initialStatus == i18n("Away") )
  { // Change status to AWAY
    initialStatus = "AWY";
  }
  else if( initialStatus == i18n("Be Right Back") )
  { // Change status to BE RIGHT BACK
    initialStatus = "BRB";
  }
  else if( initialStatus == i18n("Busy") )
  { // Change status to BUSY
    initialStatus = "BSY";
  }
  else if( initialStatus == i18n("Invisible") )
  { // Change status to INVISIBLE
    initialStatus = "HDN";
  }
  else if( initialStatus == i18n("Out to Lunch") )
  { // Change status to OUT TO LUNCH
    initialStatus = "LUN";
  }
  else if( initialStatus == i18n("On the Phone") )
  { // Change status to ON THE PHONE
    initialStatus = "PHN";
  }
  else
  { // Change status to ONLINE
    initialStatus = "NLN";
  }
  account->setInitialStatus( initialStatus );

  // Update the picture if we have one.
  if(hasTempImage_)
  {
    if( ! showImage)
    {
      // The temporary file is no longer needed.
      QFile::remove(tempImageFile_);
      hasTempImage_ = false;
    }
    else
    {
      imageName = account->getNewCustomImagePath();

      // Rename the temp file, place it over the new file
      imageFolder = QDir( QFileInfo(imageName).dir() );
      success = imageFolder.rename( tempImageFile_, imageName );
      hasTempImage_ = false;

      if( ! success )
      {
        kdWarning() << "The display picture file could not be renamed from \"" << tempImageFile_ << "\" to \"" << imageName << "\"." << endl;
      }
    }
  }

  // Create the MSN Object again.
  account->updateMsnObject();
}



/**
 * The user toggled the remember me option
 */
void AccountsWidget::rememberMeToggled(bool noGuest)
{
  autologinCheckBox_->setEnabled( noGuest );
  initialStatus_->setEnabled( noGuest );
}



/*
 * Allow the user to select an image, and convert it to 96x96, place it in a temp file.
 */
void AccountsWidget::selectImage( bool resize )
{
  // This code is partially borrowed from Kopete.

  KStandardDirs *dirs   = KGlobal::dirs();
  bool    isRemoteFile  = false;
  QString safeHandle    = 0;
  KURL    filePath      = 0;
  QString localFilePath = 0;
  QString tempImageName = 0;
  QImage  imageData     = 0;

  // all images:  dirs->findAllResources("data", "kdm/pics/users/*.png")
  // default dir: dirs->findResource("data", "kdm/pics/users/");

  // Get the resourcedir which contains the largest collection of images.
  // This fixes a problem with SuSE, where /etc/opt/kde/share is returned instead of /opt/kde3/share
  QString startDir;
  QStringList kdmDirs = dirs->findDirs("data", "kdm/pics/users/");
  QDir kdmDir;
  uint fileCount = 0;
  for( QStringList::Iterator it = kdmDirs.begin(); it != kdmDirs.end(); ++it )
  {
    kdmDir.setPath(*it);
    QStringList pngFiles = kdmDir.entryList("*.png");
    if( pngFiles.size() > fileCount )
    {
      fileCount = pngFiles.size();
      startDir = *it;
    }
  }

  // Show the open file dialog
  filePath = KFileDialog::getImageOpenURL( startDir, this, i18n( "Display Picture" ) );
  if(filePath.isEmpty())
  {
    return;
  }

  // Read the path.
  if(filePath.isLocalFile())
  {
    localFilePath = filePath.path();
  }
  else
  {
    // File is remote, download it to a local folder
    // first because QPixmap doesn't have KIO magic.
    // KIO::NetAccess::download fills the localFilePath field.
#if KDE_IS_VERSION(3,2,0)
    if(! KIO::NetAccess::download(filePath, localFilePath, this ))
#else
    if(! KIO::NetAccess::download(filePath, localFilePath ))
#endif
    {
      KMessageBox::sorry(this, i18n("Downloading of display image failed"), i18n("KMess"));
      return;
    }

    isRemoteFile = true;
  }


  // Convert the image to the correct format.
  // We use a temporary filename first and replace the original if you press OK.
  imageData = QImage(localFilePath);  // Load image data

#if KDE_IS_VERSION(3,4,0)
  // Allow the user to select a region of the image
  if( resize )
  {
    imageData = KPixmapRegionSelectorDialog::getSelectedImage( QPixmap(imageData), 96, 96, this );
  }
#else
  resize = false; // Avoid a compiler warning about unused variables.
#endif

  imageData = imageData.smoothScale(96, 96, QImage::ScaleMax); // Makes smallest edge 96 pixels, preserving aspect ratio

  if(! imageData.isNull() && (imageData.width() != 96 || imageData.height() != 96))
  {
    // Copy the middle part of the image.
    imageData = imageData.copy( (imageData.width() - 96) / 2,  // X
                                (imageData.height() - 96) / 2, // Y
                                96, 96 );
  }


  if(! imageData.isNull() && imageData.save(tempImageFile_, "PNG") )
  {
    // Sucess! Update the preview image
    customPixmap_ = QPixmap(tempImageFile_);
    pictureLabel_->setPixmap(customPixmap_);
    hasTempImage_ = true;
  }
  else
  {
    KMessageBox::sorry( this,
                        i18n( "An error occurred when trying to change the display picture.\n"
                              "Make sure that you have selected a correct image file" ),
                        i18n( "KMess" ) );
  }

  // Remove any temporary files
  if(isRemoteFile)
  {
    KIO::NetAccess::removeTempFile(localFilePath);
  }
}



// Slot running when the "Show image" checkbox was toggled.
void AccountsWidget::showImageToggled(bool noImage)
{
  browseButton_       -> setEnabled( ! noImage );
  pictureLabel_       -> setEnabled( ! noImage );
}



// The user pressed the "Create new account" button
void AccountsWidget::showRegisterPassport()
{
  new KRun("http://register.passport.com/");  // auto-deletes itself.
}


#include "accountswidget.moc"

Generated by  Doxygen 1.6.0   Back to index