<commit_before>// kmmsgpart.cpp

#include <qdir.h>

#include "kmmsgpart.h"
#include "kmmessage.h"
#include <kmimemagic.h>
#include <kapp.h>
#include <kconfig.h>

#include <mimelib/enum.h>
#include <mimelib/body.h>
#include <mimelib/bodypart.h>
#include <mimelib/utility.h>

//-----------------------------------------------------------------------------
KMMessagePart::KMMessagePart() :
  mType("text"), mSubtype("plain"), mCte("7bit"), mContentDescription(),
  mContentDisposition(), mBody(), mName()
{
  mBodySize = 0;
}

//-----------------------------------------------------------------------------
KMMessagePart::~KMMessagePart()
{
}

//-----------------------------------------------------------------------------
int KMMessagePart::size(void) const
{
  if (mBodySize < 0)
  {
    ((KMMessagePart*)this)->mBodySize =
      bodyDecoded().size() - 1;
  }
  return mBodySize;
}

//-----------------------------------------------------------------------------
void KMMessagePart::setBody(const QString aStr)
{
  int encoding = contentTransferEncoding();

  mBody = aStr.copy();

  if (encoding!=DwMime::kCteQuotedPrintable &&
      encoding!=DwMime::kCteBase64)
  {
    mBodySize = mBody.size() - 1;
  }
  else mBodySize = -1;
}

//-----------------------------------------------------------------------------
void KMMessagePart::setBodyEncoded(const QByteArray& aStr)
{
  DwString dwResult, dwSrc;
  int encoding = contentTransferEncoding();
  int len;

  mBodySize = aStr.size() - 1;

  switch (encoding)
  {
  case DwMime::kCteQuotedPrintable:
    dwSrc = DwString(aStr.data(), aStr.size()-1);
    DwEncodeQuotedPrintable(dwSrc, dwResult);
    len = dwResult.size();
    mBody.truncate(len);
    memcpy(mBody.data(), dwResult.c_str(), len+1);
    break;
  case DwMime::kCteBase64:
    dwSrc = DwString(aStr.data(), aStr.size()-1);
    DwEncodeBase64(dwSrc, dwResult);
    len = dwResult.size();
    mBody.truncate(len);
    memcpy(mBody.data(), dwResult.c_str(), len+1);
    break;
    len = aStr.size()-1;
    dwSrc = DwString(aStr.data(), len);
    DwEncodeBase64(dwSrc, dwResult);
    mBody = QString(dwResult.c_str(),dwResult.size());
    break;
  default:
    debug("WARNING -- unknown encoding `%s'. Assuming 8bit.",
	  (const char*)cteStr());
  case DwMime::kCte7bit:
  case DwMime::kCte8bit:
  case DwMime::kCteBinary:
    mBody = aStr;
    break;
  }
}

//-----------------------------------------------------------------------------
QByteArray KMMessagePart::bodyDecoded(void) const
{
  DwString dwResult, dwSrc;
  QByteArray result;
  int encoding = contentTransferEncoding();
  int len;

  switch (encoding)
  {
  case DwMime::kCteQuotedPrintable:
    dwSrc = DwString(mBody.data(), mBody.size());
    DwDecodeQuotedPrintable(dwSrc, dwResult);
    len = dwResult.size();
    result.resize(len);
    memcpy((void*)result.data(), (void*)dwResult.c_str(), len);
    break;
  case DwMime::kCteBase64:
    dwSrc = DwString(mBody.data(), mBody.size());
    DwDecodeBase64(dwSrc, dwResult);
    len = dwResult.size();
    result.resize(len);
    memcpy((void*)result.data(), (void*)dwResult.c_str(), len);
    break;
  default:
    debug("WARNING -- unknown encoding `%s'. Assuming 8bit.",
	  (const char*)cteStr());
  case DwMime::kCte7bit:
  case DwMime::kCte8bit:
  case DwMime::kCteBinary:
    len = mBody.length();
    result.resize(len);
    memcpy((void*)result.data(), (void*)mBody.data(), len);
    break;
  }

  return result;
}

//-----------------------------------------------------------------------------
void KMMessagePart::magicSetType(bool aAutoDecode)
{
  QString mimetype, bod;
  int sep;

  KMimeMagic::self()->setFollowLinks(TRUE); // is it necessary ?

  if (aAutoDecode) bod = QCString(bodyDecoded());
  else bod = mBody;

  mimetype = KMimeMagic::self()->findBufferType(bod, bod.length())->mimeType();
  sep = mimetype.find('/');
  mType = mimetype.left(sep);
  mSubtype = mimetype.mid(sep+1, 64);
}

//-----------------------------------------------------------------------------
const QString KMMessagePart::iconName(void) const
{
  QString fileName, icon;
  QDir dir;

  fileName = KApplication::kde_mimedir() + "/" + mType + "/" +
             mSubtype + ".kdelnk";

  if (dir.exists(fileName))
  {
    KConfig config(fileName);
    config.setGroup("KDE Desktop Entry");
    icon = config.readEntry("Icon");
    if(icon.isEmpty()) // If no icon specified.
      icon = "unknown.xpm";
  }
  else
  {
    // not found, use default
    icon = "unknown.xpm";
  }

  return KApplication::kde_icondir() + "/" + icon;
}

//-----------------------------------------------------------------------------
const QString KMMessagePart::typeStr(void) const
{
  return mType;
}

//-----------------------------------------------------------------------------
int KMMessagePart::type(void) const
{
  int type = DwTypeStrToEnum(DwString(mType));
  return type;
}

//-----------------------------------------------------------------------------
void KMMessagePart::setTypeStr(const QString aStr)
{
  mType = aStr.copy();
}

//-----------------------------------------------------------------------------
void KMMessagePart::setType(int aType)
{
  DwString dwType;
  DwTypeEnumToStr(aType, dwType);
  mType = dwType.c_str();

}

//-----------------------------------------------------------------------------
const QString KMMessagePart::subtypeStr(void) const
{
  return mSubtype;
}

//-----------------------------------------------------------------------------
int KMMessagePart::subtype(void) const
{
  int subtype = DwSubtypeStrToEnum(DwString(mSubtype));
  return subtype;
}

//-----------------------------------------------------------------------------
void KMMessagePart::setSubtypeStr(const QString aStr)
{
  mSubtype = aStr;
}

//-----------------------------------------------------------------------------
void KMMessagePart::setSubtype(int aSubtype)
{
  DwString dwSubtype;
  DwSubtypeEnumToStr(aSubtype, dwSubtype);
  mSubtype = dwSubtype.c_str();

}

//-----------------------------------------------------------------------------
const QString KMMessagePart::contentTransferEncodingStr(void) const
{
  return mCte;
}

//-----------------------------------------------------------------------------
int KMMessagePart::contentTransferEncoding(void) const
{
  int cte = DwCteStrToEnum(DwString(mCte));
  return cte;
}

//-----------------------------------------------------------------------------
void KMMessagePart::setContentTransferEncodingStr(const QString aStr)
{
  mCte = aStr.copy();
}

//-----------------------------------------------------------------------------
void KMMessagePart::setContentTransferEncoding(int aCte)
{
  DwString dwCte;
  DwCteEnumToStr(aCte, dwCte);
  mCte = dwCte.c_str();

}

//-----------------------------------------------------------------------------
const QString KMMessagePart::contentDescription(void) const
{
  return mContentDescription;
}

//-----------------------------------------------------------------------------
void KMMessagePart::setContentDescription(const QString aStr)
{
  mContentDescription = aStr.copy();
}

//-----------------------------------------------------------------------------
const QString KMMessagePart::fileName(void) const
{
  int i, j, len;
  QString str;

  i = mContentDisposition.find("filename=", 0, FALSE);
  if (i < 0) return QString::null;
  j = mContentDisposition.find(';', i+9);

  if (j < 0) j = 32767;
  str = mContentDisposition.mid(i+9, j-i-9).stripWhiteSpace();

  len = str.length();
  if (str[0]=='"' && str[len-1]=='"') return str.mid(1, len-2);
  return str;
}

//-----------------------------------------------------------------------------
const QString KMMessagePart::contentDisposition(void) const
{
  return mContentDisposition;
}

//-----------------------------------------------------------------------------
void KMMessagePart::setContentDisposition(const QString aStr)
{
  mContentDisposition = aStr.copy();
}

//-----------------------------------------------------------------------------
const QString KMMessagePart::body(void) const
{
  return mBody;
}

//-----------------------------------------------------------------------------
const QString KMMessagePart::name(void) const
{
  return mName;
}

//-----------------------------------------------------------------------------
void KMMessagePart::setName(const QString aStr)
{
  mName = aStr.copy();
}
#if defined CHARSETS
//-----------------------------------------------------------------------------
const QString KMMessagePart::charset(void) const
{

   return mCharset;
}

//-----------------------------------------------------------------------------
void KMMessagePart::setCharset(const QString aStr)
{

  mCharset=aStr;
}
#endif

<commit_msg>bye bye kde_icondir<commit_after>// kmmsgpart.cpp

#include <qdir.h>

#include "kmmsgpart.h"
#include "kmmessage.h"
#include <kmimemagic.h>
#include <kapp.h>
#include <kconfig.h>
#include <kstddirs.h>
#include <kglobal.h>

#include <mimelib/enum.h>
#include <mimelib/body.h>
#include <mimelib/bodypart.h>
#include <mimelib/utility.h>

//-----------------------------------------------------------------------------
KMMessagePart::KMMessagePart() :
  mType("text"), mSubtype("plain"), mCte("7bit"), mContentDescription(),
  mContentDisposition(), mBody(), mName()
{
  mBodySize = 0;
}

//-----------------------------------------------------------------------------
KMMessagePart::~KMMessagePart()
{
}

//-----------------------------------------------------------------------------
int KMMessagePart::size(void) const
{
  if (mBodySize < 0)
  {
    ((KMMessagePart*)this)->mBodySize =
      bodyDecoded().size() - 1;
  }
  return mBodySize;
}

//-----------------------------------------------------------------------------
void KMMessagePart::setBody(const QString aStr)
{
  int encoding = contentTransferEncoding();

  mBody = aStr.copy();

  if (encoding!=DwMime::kCteQuotedPrintable &&
      encoding!=DwMime::kCteBase64)
  {
    mBodySize = mBody.size() - 1;
  }
  else mBodySize = -1;
}

//-----------------------------------------------------------------------------
void KMMessagePart::setBodyEncoded(const QByteArray& aStr)
{
  DwString dwResult, dwSrc;
  int encoding = contentTransferEncoding();
  int len;

  mBodySize = aStr.size() - 1;

  switch (encoding)
  {
  case DwMime::kCteQuotedPrintable:
    dwSrc = DwString(aStr.data(), aStr.size()-1);
    DwEncodeQuotedPrintable(dwSrc, dwResult);
    len = dwResult.size();
    mBody.truncate(len);
    memcpy(mBody.data(), dwResult.c_str(), len+1);
    break;
  case DwMime::kCteBase64:
    dwSrc = DwString(aStr.data(), aStr.size()-1);
    DwEncodeBase64(dwSrc, dwResult);
    len = dwResult.size();
    mBody.truncate(len);
    memcpy(mBody.data(), dwResult.c_str(), len+1);
    break;
    len = aStr.size()-1;
    dwSrc = DwString(aStr.data(), len);
    DwEncodeBase64(dwSrc, dwResult);
    mBody = QString(dwResult.c_str(),dwResult.size());
    break;
  default:
    debug("WARNING -- unknown encoding `%s'. Assuming 8bit.",
	  (const char*)cteStr());
  case DwMime::kCte7bit:
  case DwMime::kCte8bit:
  case DwMime::kCteBinary:
    mBody = aStr;
    break;
  }
}

//-----------------------------------------------------------------------------
QByteArray KMMessagePart::bodyDecoded(void) const
{
  DwString dwResult, dwSrc;
  QByteArray result;
  int encoding = contentTransferEncoding();
  int len;

  switch (encoding)
  {
  case DwMime::kCteQuotedPrintable:
    dwSrc = DwString(mBody.data(), mBody.size());
    DwDecodeQuotedPrintable(dwSrc, dwResult);
    len = dwResult.size();
    result.resize(len);
    memcpy((void*)result.data(), (void*)dwResult.c_str(), len);
    break;
  case DwMime::kCteBase64:
    dwSrc = DwString(mBody.data(), mBody.size());
    DwDecodeBase64(dwSrc, dwResult);
    len = dwResult.size();
    result.resize(len);
    memcpy((void*)result.data(), (void*)dwResult.c_str(), len);
    break;
  default:
    debug("WARNING -- unknown encoding `%s'. Assuming 8bit.",
	  (const char*)cteStr());
  case DwMime::kCte7bit:
  case DwMime::kCte8bit:
  case DwMime::kCteBinary:
    len = mBody.length();
    result.resize(len);
    memcpy((void*)result.data(), (void*)mBody.data(), len);
    break;
  }

  return result;
}

//-----------------------------------------------------------------------------
void KMMessagePart::magicSetType(bool aAutoDecode)
{
  QString mimetype, bod;
  int sep;

  KMimeMagic::self()->setFollowLinks(TRUE); // is it necessary ?

  if (aAutoDecode) bod = QCString(bodyDecoded());
  else bod = mBody;

  mimetype = KMimeMagic::self()->findBufferType(bod, bod.length())->mimeType();
  sep = mimetype.find('/');
  mType = mimetype.left(sep);
  mSubtype = mimetype.mid(sep+1, 64);
}

//-----------------------------------------------------------------------------
const QString KMMessagePart::iconName(void) const
{
  QString fileName, icon;
  QDir dir;

  fileName = KApplication::kde_mimedir() + "/" + mType + "/" +
             mSubtype + ".kdelnk";

  if (dir.exists(fileName))
  {
    KConfig config(fileName);
    config.setGroup("KDE Desktop Entry");
    icon = config.readEntry("Icon");
    if(icon.isEmpty()) // If no icon specified.
      icon = "unknown.xpm";
  }
  else
  {
    // not found, use default
    icon = "unknown.xpm";
  }

  return locate("icon", icon);
}

//-----------------------------------------------------------------------------
const QString KMMessagePart::typeStr(void) const
{
  return mType;
}

//-----------------------------------------------------------------------------
int KMMessagePart::type(void) const
{
  int type = DwTypeStrToEnum(DwString(mType));
  return type;
}

//-----------------------------------------------------------------------------
void KMMessagePart::setTypeStr(const QString aStr)
{
  mType = aStr.copy();
}

//-----------------------------------------------------------------------------
void KMMessagePart::setType(int aType)
{
  DwString dwType;
  DwTypeEnumToStr(aType, dwType);
  mType = dwType.c_str();

}

//-----------------------------------------------------------------------------
const QString KMMessagePart::subtypeStr(void) const
{
  return mSubtype;
}

//-----------------------------------------------------------------------------
int KMMessagePart::subtype(void) const
{
  int subtype = DwSubtypeStrToEnum(DwString(mSubtype));
  return subtype;
}

//-----------------------------------------------------------------------------
void KMMessagePart::setSubtypeStr(const QString aStr)
{
  mSubtype = aStr;
}

//-----------------------------------------------------------------------------
void KMMessagePart::setSubtype(int aSubtype)
{
  DwString dwSubtype;
  DwSubtypeEnumToStr(aSubtype, dwSubtype);
  mSubtype = dwSubtype.c_str();

}

//-----------------------------------------------------------------------------
const QString KMMessagePart::contentTransferEncodingStr(void) const
{
  return mCte;
}

//-----------------------------------------------------------------------------
int KMMessagePart::contentTransferEncoding(void) const
{
  int cte = DwCteStrToEnum(DwString(mCte));
  return cte;
}

//-----------------------------------------------------------------------------
void KMMessagePart::setContentTransferEncodingStr(const QString aStr)
{
  mCte = aStr.copy();
}

//-----------------------------------------------------------------------------
void KMMessagePart::setContentTransferEncoding(int aCte)
{
  DwString dwCte;
  DwCteEnumToStr(aCte, dwCte);
  mCte = dwCte.c_str();

}

//-----------------------------------------------------------------------------
const QString KMMessagePart::contentDescription(void) const
{
  return mContentDescription;
}

//-----------------------------------------------------------------------------
void KMMessagePart::setContentDescription(const QString aStr)
{
  mContentDescription = aStr.copy();
}

//-----------------------------------------------------------------------------
const QString KMMessagePart::fileName(void) const
{
  int i, j, len;
  QString str;

  i = mContentDisposition.find("filename=", 0, FALSE);
  if (i < 0) return QString::null;
  j = mContentDisposition.find(';', i+9);

  if (j < 0) j = 32767;
  str = mContentDisposition.mid(i+9, j-i-9).stripWhiteSpace();

  len = str.length();
  if (str[0]=='"' && str[len-1]=='"') return str.mid(1, len-2);
  return str;
}

//-----------------------------------------------------------------------------
const QString KMMessagePart::contentDisposition(void) const
{
  return mContentDisposition;
}

//-----------------------------------------------------------------------------
void KMMessagePart::setContentDisposition(const QString aStr)
{
  mContentDisposition = aStr.copy();
}

//-----------------------------------------------------------------------------
const QString KMMessagePart::body(void) const
{
  return mBody;
}

//-----------------------------------------------------------------------------
const QString KMMessagePart::name(void) const
{
  return mName;
}

//-----------------------------------------------------------------------------
void KMMessagePart::setName(const QString aStr)
{
  mName = aStr.copy();
}
#if defined CHARSETS
//-----------------------------------------------------------------------------
const QString KMMessagePart::charset(void) const
{

   return mCharset;
}

//-----------------------------------------------------------------------------
void KMMessagePart::setCharset(const QString aStr)
{

  mCharset=aStr;
}
#endif

<|endoftext|>


<commit_before>/*
    This file is part of KMail, the KDE mail client.
    Copyright (c) 2000 Don Sanders <sanders@kde.org>

    KMail is free software; you can redistribute it and/or modify it
    under the terms of the GNU General Public License, version 2, as
    published by the Free Software Foundation.

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

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

#include <config.h>

#include "kmstartup.h"

#include "kmkernel.h" //control center
#include "kcursorsaver.h"

#include <klocale.h>
#include <kcomponentdata.h>
#include <kconfig.h>
#include <kstandarddirs.h>
#include <kmessagebox.h>
#include <kcrash.h>
#include <kglobal.h>
#include <kaboutdata.h>
#include <kiconloader.h>
#include <kresolver.h>
#include <kconfiggroup.h>

#include <errno.h>
#include <sys/types.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

#undef Status // stupid X headers

extern "C" {

// Crash recovery signal handler
void kmsignalHandler(int sigId)
{
  kmsetSignalHandler(SIG_DFL);
  fprintf(stderr, "*** KMail got signal %d (Exiting)\n", sigId);
  // try to cleanup all windows
  if (kmkernel) kmkernel->dumpDeadLetters();
  ::exit(-1); //
}

// Crash recovery signal handler
void kmcrashHandler(int sigId)
{
  kmsetSignalHandler(SIG_DFL);
  fprintf(stderr, "*** KMail got signal %d (Crashing)\n", sigId);
  // try to cleanup all windows
  if (kmkernel) kmkernel->dumpDeadLetters();
  // Return to DrKonqi.
}
//-----------------------------------------------------------------------------

void kmsetSignalHandler(void (*handler)(int))
{
  signal(SIGKILL, handler);
  signal(SIGTERM, handler);
  signal(SIGHUP,  handler);
  KCrash::setEmergencySaveFunction(kmcrashHandler);
}

}
//-----------------------------------------------------------------------------

namespace KMail {

void checkConfigUpdates() {
  static const char * const updates[] = {
    "9",
    "3.1-update-identities",
    "3.1-use-identity-uoids",
    "3.1-new-mail-notification",
    "3.2-update-loop-on-goto-unread-settings",
    "3.1.4-dont-use-UOID-0-for-any-identity",
    "3.2-misc",
    "3.2-moves",
    "3.3-use-ID-for-accounts",
    "3.3-update-filter-rules",
    "3.3-move-identities-to-own-file",
    "3.3-aegypten-kpgprc-to-kmailrc",
    "3.3-aegypten-kpgprc-to-libkleopatrarc",
    "3.3-aegypten-emailidentities-split-sign-encr-keys",
    "3.3-misc",
    "3.3b1-misc",
    "3.4-misc",
    "3.4a",
    "3.4b",
    "3.4.1",
    "3.5.4"
  };
  static const int numUpdates = sizeof updates / sizeof *updates;
  // Warning: do not remove entries in the above array, or the update-level check below will break

  KConfig * config = KMKernel::config();
  KConfigGroup startup( config, "Startup" );
  const int configUpdateLevel = startup.readEntry( "update-level", 0 );
  if ( configUpdateLevel == numUpdates ) // Optimize for the common case that everything is OK
    return;

  for ( int i = configUpdateLevel ; i < numUpdates ; ++i ) {
    config->checkUpdate( updates[i], "kmail.upd" );
  }
  startup.writeEntry( "update-level", numUpdates );
}

void lockOrDie() {
// Check and create a lock file to prevent concurrent access to kmail files
  QString appName = KGlobal::mainComponent().componentName();
  if ( appName.isEmpty() )
    appName = "kmail";

  QString programName;
  const KAboutData *about = KGlobal::mainComponent().aboutData();
  if ( about )
    programName = about->programName();
  if ( programName.isEmpty() )
    programName = i18n("KMail");

  QString lockLocation = KStandardDirs::locateLocal("data", "kmail/lock");
  KConfig config(lockLocation, KConfig::OnlyLocal);
  int oldPid = config.readEntry("pid", -1 );
  const QString oldHostName = config.readEntry("hostname");
  const QString oldAppName = config.readEntry( "appName", appName );
  const QString oldProgramName = config.readEntry( "programName", programName );
  const QString hostName = KNetwork::KResolver::localHostName();
  bool first_instance = false;
  if ( oldPid == -1 )
      first_instance = true;
  // check if the lock file is stale by trying to see if
  // the other pid is currently running.
  // Not 100% correct but better safe than sorry
  else if (hostName == oldHostName && oldPid != getpid()) {
      if ( kill(oldPid, 0) == -1 )
          first_instance = ( errno == ESRCH );
  }

  if ( !first_instance ) {
    QString msg;
    if ( oldHostName == hostName ) {
      // this can only happen if the user is running this application on
      // different displays on the same machine. All other cases will be
      // taken care of by KUniqueApplication()
      if ( oldAppName == appName )
        msg = i18n("%1 already seems to be running on another display on "
                   "this machine. Running %2 more than once "
                   "can cause the loss of mail. You should not start %1 "
                   "unless you are sure that it is not already running.",
                   programName, programName );
              // QString::arg( st ) only replaces the first occurrence of %1
              // with st while QString::arg( s1, s2 ) replacess all occurrences
              // of %1 with s1 and all occurrences of %2 with s2. So don't
              // even think about changing the above to .arg( programName ).
      else
        msg = i18n("%1 seems to be running on another display on this "
                   "machine. Running %1 and %2 at the same "
                   "time can cause the loss of mail. You should not start %2 "
                   "unless you are sure that %1 is not running.",
                   oldProgramName, programName );
    }
    else {
      if ( oldAppName == appName )
        msg = i18n("%1 already seems to be running on %2. Running %1 more "
                   "than once can cause the loss of mail. You should not "
                   "start %1 on this computer unless you are sure that it is "
                   "not already running on %2.",
                   programName, oldHostName );
      else
        msg = i18n("%1 seems to be running on %3. Running %1 and %2 at the "
                   "same time can cause the loss of mail. You should not "
                   "start %2 on this computer unless you are sure that %1 is "
                   "not running on %3.",
                    oldProgramName, programName, oldHostName );
    }

    KCursorSaver idle( KBusyPtr::idle() );
    if ( KMessageBox::No ==
         KMessageBox::warningYesNo( 0, msg, QString(),
                                    KGuiItem(i18n("Start %1", programName )),
                                    KGuiItem(i18n("Exit")) ) ) {
      exit(1);
    }
  }

  config.writeEntry("pid", getpid());
  config.writeEntry("hostname", hostName);
  config.writeEntry( "appName", appName );
  config.writeEntry( "programName", programName );
  config.sync();
}

void insertLibraryCataloguesAndIcons() {
  static const char * const catalogues[] = {
    "libkdepim",
    "libksieve",
    "libkleopatra",
    "libkmime"
  };

  KLocale * l = KGlobal::locale();
  KIconLoader * il = KIconLoader::global();
  for ( unsigned int i = 0 ; i < sizeof catalogues / sizeof *catalogues ; ++i ) {
    l->insertCatalog( catalogues[i] );
    il->addAppDir( catalogues[i] );
  }

}

void cleanup()
{
  const QString lockLocation = KStandardDirs::locateLocal("data", "kmail/lock");
  KConfig config(lockLocation, KConfig::OnlyLocal);
  config.writeEntry("pid", -1);
  config.sync();
}
}
<commit_msg>forward port SVN commit 645708 by dfaure:<commit_after>/*
    This file is part of KMail, the KDE mail client.
    Copyright (c) 2000 Don Sanders <sanders@kde.org>

    KMail is free software; you can redistribute it and/or modify it
    under the terms of the GNU General Public License, version 2, as
    published by the Free Software Foundation.

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

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

#include <config.h>

#include "kmstartup.h"

#include "kmkernel.h" //control center
#include "kcursorsaver.h"

#include <klocale.h>
#include <kcomponentdata.h>
#include <kconfig.h>
#include <kstandarddirs.h>
#include <kmessagebox.h>
#include <kcrash.h>
#include <kglobal.h>
#include <kaboutdata.h>
#include <kiconloader.h>
#include <kresolver.h>
#include <kconfiggroup.h>

#include <errno.h>
#include <sys/types.h>
#include <sys/param.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <qfile.h>

#undef Status // stupid X headers

extern "C" {

// Crash recovery signal handler
void kmsignalHandler(int sigId)
{
  kmsetSignalHandler(SIG_DFL);
  fprintf(stderr, "*** KMail got signal %d (Exiting)\n", sigId);
  // try to cleanup all windows
  if (kmkernel) kmkernel->dumpDeadLetters();
  ::exit(-1); //
}

// Crash recovery signal handler
void kmcrashHandler(int sigId)
{
  kmsetSignalHandler(SIG_DFL);
  fprintf(stderr, "*** KMail got signal %d (Crashing)\n", sigId);
  // try to cleanup all windows
  if (kmkernel) kmkernel->dumpDeadLetters();
  // Return to DrKonqi.
}
//-----------------------------------------------------------------------------

void kmsetSignalHandler(void (*handler)(int))
{
  signal(SIGKILL, handler);
  signal(SIGTERM, handler);
  signal(SIGHUP,  handler);
  KCrash::setEmergencySaveFunction(kmcrashHandler);
}

}
//-----------------------------------------------------------------------------

namespace KMail {

void checkConfigUpdates() {
  static const char * const updates[] = {
    "9",
    "3.1-update-identities",
    "3.1-use-identity-uoids",
    "3.1-new-mail-notification",
    "3.2-update-loop-on-goto-unread-settings",
    "3.1.4-dont-use-UOID-0-for-any-identity",
    "3.2-misc",
    "3.2-moves",
    "3.3-use-ID-for-accounts",
    "3.3-update-filter-rules",
    "3.3-move-identities-to-own-file",
    "3.3-aegypten-kpgprc-to-kmailrc",
    "3.3-aegypten-kpgprc-to-libkleopatrarc",
    "3.3-aegypten-emailidentities-split-sign-encr-keys",
    "3.3-misc",
    "3.3b1-misc",
    "3.4-misc",
    "3.4a",
    "3.4b",
    "3.4.1",
    "3.5.4"
  };
  static const int numUpdates = sizeof updates / sizeof *updates;
  // Warning: do not remove entries in the above array, or the update-level check below will break

  KConfig * config = KMKernel::config();
  KConfigGroup startup( config, "Startup" );
  const int configUpdateLevel = startup.readEntry( "update-level", 0 );
  if ( configUpdateLevel == numUpdates ) // Optimize for the common case that everything is OK
    return;

  for ( int i = configUpdateLevel ; i < numUpdates ; ++i ) {
    config->checkUpdate( updates[i], "kmail.upd" );
  }
  startup.writeEntry( "update-level", numUpdates );
}

void lockOrDie() {
// Check and create a lock file to prevent concurrent access to kmail files
  QString appName = KGlobal::mainComponent().componentName();
  if ( appName.isEmpty() )
    appName = "kmail";

  QString programName;
  const KAboutData *about = KGlobal::mainComponent().aboutData();
  if ( about )
    programName = about->programName();
  if ( programName.isEmpty() )
    programName = i18n("KMail");

  QString lockLocation = KStandardDirs::locateLocal("data", "kmail/lock");
  KConfig config(lockLocation, KConfig::OnlyLocal);
  int oldPid = config.readEntry("pid", -1 );
  const QString oldHostName = config.readEntry("hostname");
  const QString oldAppName = config.readEntry( "appName", appName );
  const QString oldProgramName = config.readEntry( "programName", programName );
  const QString hostName = KNetwork::KResolver::localHostName();
  bool first_instance = false;
  if ( oldPid == -1 ) {
    first_instance = true;
  } else if ( hostName == oldHostName && oldPid != getpid() ) {
    // check if the lock file is stale
#ifdef Q_OS_LINUX
    if ( ::access("/proc", X_OK ) == 0 ) {
      // On linux with /proc we can even check that
      // it's really kmail and not something else
      char path_buffer[MAXPATHLEN + 1];
      path_buffer[MAXPATHLEN] = 0;
      const QString procPath = QString( "/proc/%1/exe" ).arg( oldPid );
      const int length =
        readlink( procPath.latin1(), path_buffer, MAXPATHLEN );
      if ( length == -1 ) { // no such pid
        first_instance = true;
      } else {
        path_buffer[length] = '\0';
        const QString path = QFile::decodeName( path_buffer );
        kDebug() << k_funcinfo << path << endl;
        const int pos = path.findRev( '/' );
        const QString fileName = path.mid( pos + 1 );
        kDebug() << "Found process " << oldPid
                 << " running. It's: " << fileName << endl;
        first_instance = fileName != "kmail" && fileName != "kontact";
      }
    } else
#endif
    {
      // Otherwise we just check if the other pid is currently running.
      // Not 100% correct but better safe than sorry.
      if ( kill(oldPid, 0) == -1 )
        first_instance = ( errno == ESRCH );
    }
  }

  if ( !first_instance ) {
    QString msg;
    if ( oldHostName == hostName ) {
      // this can only happen if the user is running this application on
      // different displays on the same machine. All other cases will be
      // taken care of by KUniqueApplication()
      if ( oldAppName == appName )
        msg = i18n("%1 already seems to be running on another display on "
                   "this machine. Running %2 more than once "
                   "can cause the loss of mail. You should not start %1 "
                   "unless you are sure that it is not already running.",
                   programName, programName );
              // QString::arg( st ) only replaces the first occurrence of %1
              // with st while QString::arg( s1, s2 ) replacess all occurrences
              // of %1 with s1 and all occurrences of %2 with s2. So don't
              // even think about changing the above to .arg( programName ).
      else
        msg = i18n("%1 seems to be running on another display on this "
                   "machine. Running %1 and %2 at the same "
                   "time can cause the loss of mail. You should not start %2 "
                   "unless you are sure that %1 is not running.",
                   oldProgramName, programName );
    }
    else {
      if ( oldAppName == appName )
        msg = i18n("%1 already seems to be running on %2. Running %1 more "
                   "than once can cause the loss of mail. You should not "
                   "start %1 on this computer unless you are sure that it is "
                   "not already running on %2.",
                   programName, oldHostName );
      else
        msg = i18n("%1 seems to be running on %3. Running %1 and %2 at the "
                   "same time can cause the loss of mail. You should not "
                   "start %2 on this computer unless you are sure that %1 is "
                   "not running on %3.",
                    oldProgramName, programName, oldHostName );
    }

    KCursorSaver idle( KBusyPtr::idle() );
    if ( KMessageBox::No ==
         KMessageBox::warningYesNo( 0, msg, QString(),
                                    KGuiItem(i18n("Start %1", programName )),
                                    KGuiItem(i18n("Exit")) ) ) {
      exit(1);
    }
  }

  config.writeEntry("pid", getpid());
  config.writeEntry("hostname", hostName);
  config.writeEntry( "appName", appName );
  config.writeEntry( "programName", programName );
  config.sync();
}

void insertLibraryCataloguesAndIcons() {
  static const char * const catalogues[] = {
    "libkdepim",
    "libksieve",
    "libkleopatra",
    "libkmime"
  };

  KLocale * l = KGlobal::locale();
  KIconLoader * il = KIconLoader::global();
  for ( unsigned int i = 0 ; i < sizeof catalogues / sizeof *catalogues ; ++i ) {
    l->insertCatalog( catalogues[i] );
    il->addAppDir( catalogues[i] );
  }

}

void cleanup()
{
  const QString lockLocation = KStandardDirs::locateLocal("data", "kmail/lock");
  KConfig config(lockLocation, KConfig::OnlyLocal);
  config.writeEntry("pid", -1);
  config.sync();
}
}
<|endoftext|>


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

 Program:   Visualization Toolkit
 Module:    vtkUniformGridPartitioner.cxx

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

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

 =========================================================================*/

#include "vtkUniformGridPartitioner.h"
#include "vtkObjectFactory.h"
#include "vtkIndent.h"
#include "vtkExtentRCBPartitioner.h"
#include "vtkUniformGrid.h"
#include "vtkMultiBlockDataSet.h"
#include "vtkStructuredData.h"
#include "vtkStructuredExtent.h"
#include "vtkInformation.h"
#include "vtkInformationVector.h"

#include <cassert>

vtkStandardNewMacro( vtkUniformGridPartitioner );

//------------------------------------------------------------------------------
vtkUniformGridPartitioner::vtkUniformGridPartitioner()
{
  this->NumberOfPartitions = 2;
}

//------------------------------------------------------------------------------
vtkUniformGridPartitioner::~vtkUniformGridPartitioner()
{

}

//------------------------------------------------------------------------------
void vtkUniformGridPartitioner::PrintSelf(std::ostream &oss, vtkIndent indent)
{
  this->Superclass::PrintSelf( oss, indent );
}

//------------------------------------------------------------------------------
int vtkUniformGridPartitioner::FillInputPortInformation(
    int vtkNotUsed(port), vtkInformation *info )
{
  info->Set(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(),"vtkImageData" );
  return 1;
}

//------------------------------------------------------------------------------
int vtkUniformGridPartitioner::FillOutputPortInformation(
    int vtkNotUsed(port), vtkInformation *info )
{
  info->Set(vtkDataObject::DATA_TYPE_NAME(),"vtkMultiBlockDataSet");
  return 1;
}

//------------------------------------------------------------------------------
int vtkUniformGridPartitioner::RequestData(
    vtkInformation* vtkNotUsed(request),
    vtkInformationVector** inputVector, vtkInformationVector* outputVector )
{
  // STEP 0: Get input object
  vtkInformation *input = inputVector[0]->GetInformationObject( 0 );
  assert( "pre: input information object is NULL" && (input != NULL) );

  vtkImageData *grd =
    vtkImageData::SafeDownCast( input->Get(vtkDataObject::DATA_OBJECT() ) );
  assert( "pre: input grid is NULL!" && (grd != NULL));

  // STEP 1: Get output object
  vtkInformation *output = outputVector->GetInformationObject( 0 );
  assert( "pre: output information object is NULL" && (output != NULL) );
  vtkMultiBlockDataSet *multiblock =
      vtkMultiBlockDataSet::SafeDownCast(
        output->Get( vtkDataObject::DATA_OBJECT() ) );
  assert( "pre: multiblock grid is NULL!" && (multiblock != NULL) );

  // STEP 2: Get the global extent
  int extent[6];
  int dims[3];
  grd->GetDimensions( dims );
  grd->GetExtent( extent );

  // STEP 3: Setup extent partitioner
  vtkExtentRCBPartitioner *extentPartitioner = vtkExtentRCBPartitioner::New();
  assert( "pre: extent partitioner is NULL" && (extentPartitioner != NULL) );
  extentPartitioner->SetGlobalExtent( extent );
  extentPartitioner->SetNumberOfPartitions( this->NumberOfPartitions );

  // STEP 4: Partition
  extentPartitioner->Partition();

  // STEP 5: Extract partitions into a multi-block dataset.
  multiblock->SetNumberOfBlocks( extentPartitioner->GetNumExtents() );

  // Set the whole extent of the grid
  multiblock->SetWholeExtent( extent );

  unsigned int blockIdx = 0;
  for( ; blockIdx < multiblock->GetNumberOfBlocks(); ++blockIdx )
    {
    int ext[6];
    extentPartitioner->GetPartitionExtent( blockIdx, ext );

    double origin[3];
    int ijk[3];
    ijk[0] = ext[0];
    ijk[1] = ext[1];
    ijk[2] = ext[2];

    int subdims[3];
    vtkStructuredExtent::GetDimensions( ext, subdims );

    int pntIdx = vtkStructuredData::ComputePointId( dims, ijk );

    grd->GetPoint( pntIdx, origin );

    vtkUniformGrid *subgrid = vtkUniformGrid::New();
    subgrid->SetOrigin( origin );
    subgrid->SetSpacing( grd->GetSpacing() );
    subgrid->SetDimensions( subdims );

    // Set the global extent for each block
    vtkInformation *metadata = multiblock->GetMetaData( blockIdx );
    assert( "pre: metadata is NULL" && (metadata != NULL) );
    metadata->Set( vtkDataObject::PIECE_EXTENT(), ext, 6 );

    multiblock->SetBlock( blockIdx, subgrid );
    subgrid->Delete();
    } // END for all blocks

  extentPartitioner->Delete();
  return 1;
}
<commit_msg>BUGFIX: Correct IJK of origin of each sub-grid<commit_after>/*=========================================================================

 Program:   Visualization Toolkit
 Module:    vtkUniformGridPartitioner.cxx

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

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

 =========================================================================*/

#include "vtkUniformGridPartitioner.h"
#include "vtkObjectFactory.h"
#include "vtkIndent.h"
#include "vtkExtentRCBPartitioner.h"
#include "vtkUniformGrid.h"
#include "vtkMultiBlockDataSet.h"
#include "vtkStructuredData.h"
#include "vtkStructuredExtent.h"
#include "vtkInformation.h"
#include "vtkInformationVector.h"

#include <cassert>

vtkStandardNewMacro( vtkUniformGridPartitioner );

//------------------------------------------------------------------------------
vtkUniformGridPartitioner::vtkUniformGridPartitioner()
{
  this->NumberOfPartitions = 2;
}

//------------------------------------------------------------------------------
vtkUniformGridPartitioner::~vtkUniformGridPartitioner()
{

}

//------------------------------------------------------------------------------
void vtkUniformGridPartitioner::PrintSelf(std::ostream &oss, vtkIndent indent)
{
  this->Superclass::PrintSelf( oss, indent );
}

//------------------------------------------------------------------------------
int vtkUniformGridPartitioner::FillInputPortInformation(
    int vtkNotUsed(port), vtkInformation *info )
{
  info->Set(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(),"vtkImageData" );
  return 1;
}

//------------------------------------------------------------------------------
int vtkUniformGridPartitioner::FillOutputPortInformation(
    int vtkNotUsed(port), vtkInformation *info )
{
  info->Set(vtkDataObject::DATA_TYPE_NAME(),"vtkMultiBlockDataSet");
  return 1;
}

//------------------------------------------------------------------------------
int vtkUniformGridPartitioner::RequestData(
    vtkInformation* vtkNotUsed(request),
    vtkInformationVector** inputVector, vtkInformationVector* outputVector )
{
  // STEP 0: Get input object
  vtkInformation *input = inputVector[0]->GetInformationObject( 0 );
  assert( "pre: input information object is NULL" && (input != NULL) );

  vtkImageData *grd =
    vtkImageData::SafeDownCast( input->Get(vtkDataObject::DATA_OBJECT() ) );
  assert( "pre: input grid is NULL!" && (grd != NULL));

  // STEP 1: Get output object
  vtkInformation *output = outputVector->GetInformationObject( 0 );
  assert( "pre: output information object is NULL" && (output != NULL) );
  vtkMultiBlockDataSet *multiblock =
      vtkMultiBlockDataSet::SafeDownCast(
        output->Get( vtkDataObject::DATA_OBJECT() ) );
  assert( "pre: multiblock grid is NULL!" && (multiblock != NULL) );

  // STEP 2: Get the global extent
  int extent[6];
  int dims[3];
  grd->GetDimensions( dims );
  grd->GetExtent( extent );

  // STEP 3: Setup extent partitioner
  vtkExtentRCBPartitioner *extentPartitioner = vtkExtentRCBPartitioner::New();
  assert( "pre: extent partitioner is NULL" && (extentPartitioner != NULL) );
  extentPartitioner->SetGlobalExtent( extent );
  extentPartitioner->SetNumberOfPartitions( this->NumberOfPartitions );

  // STEP 4: Partition
  extentPartitioner->Partition();

  // STEP 5: Extract partitions into a multi-block dataset.
  multiblock->SetNumberOfBlocks( extentPartitioner->GetNumExtents() );

  // Set the whole extent of the grid
  multiblock->SetWholeExtent( extent );

  unsigned int blockIdx = 0;
  for( ; blockIdx < multiblock->GetNumberOfBlocks(); ++blockIdx )
    {
    int ext[6];
    extentPartitioner->GetPartitionExtent( blockIdx, ext );

    double origin[3];
    int ijk[3];
    ijk[0] = ext[0];
    ijk[1] = ext[2];
    ijk[2] = ext[4];

    int subdims[3];
    vtkStructuredExtent::GetDimensions( ext, subdims );

    int pntIdx = vtkStructuredData::ComputePointId( dims, ijk );

    grd->GetPoint( pntIdx, origin );

    vtkUniformGrid *subgrid = vtkUniformGrid::New();
    subgrid->SetOrigin( origin );
    subgrid->SetSpacing( grd->GetSpacing() );
    subgrid->SetDimensions( subdims );

    // Set the global extent for each block
    vtkInformation *metadata = multiblock->GetMetaData( blockIdx );
    assert( "pre: metadata is NULL" && (metadata != NULL) );
    metadata->Set( vtkDataObject::PIECE_EXTENT(), ext, 6 );

    multiblock->SetBlock( blockIdx, subgrid );
    subgrid->Delete();
    } // END for all blocks

  extentPartitioner->Delete();
  return 1;
}
<|endoftext|>


<commit_before>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/memory/p9_mss_draminit.C $ */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2015,2019                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* 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.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */

///
/// @file p9_mss_draminit.C
/// @brief Initialize dram
///
// *HWP HWP Owner: Brian Silver <bsilver@us.ibm.com>
// *HWP HWP Backup: Andre Marin <aamarin@us.ibm.com>
// *HWP Team: Memory
// *HWP Level: 2
// *HWP Consumed by: FSP:HB

#include <fapi2.H>
#include <mss.H>

#include <p9_mss_draminit.H>

using fapi2::TARGET_TYPE_MCBIST;
using fapi2::TARGET_TYPE_MCA;
using fapi2::FAPI2_RC_SUCCESS;

extern "C"
{
///
/// @brief Initialize dram
/// @param[in] i_target, the McBIST of the ports of the dram you're initializing
/// @return FAPI2_RC_SUCCESS iff ok
///
    fapi2::ReturnCode p9_mss_draminit( const fapi2::Target<TARGET_TYPE_MCBIST>& i_target )
    {
        fapi2::buffer<uint64_t> l_data;

        mss::ccs::instruction_t<TARGET_TYPE_MCBIST> l_inst;
        mss::ccs::instruction_t<TARGET_TYPE_MCBIST> l_des = mss::ccs::des_command<TARGET_TYPE_MCBIST>();

        mss::ccs::program<TARGET_TYPE_MCBIST> l_program;

        static const uint64_t PCLK_INITIAL_VALUE = 0x02;
        static const uint64_t NCLK_INITIAL_VALUE = 0x01;

        auto l_mca = i_target.getChildren<TARGET_TYPE_MCA>();

        FAPI_INF("Start draminit: %s", mss::c_str(i_target));

        // If we don't have any ports, lets go.
        if (l_mca.size() == 0)
        {
            FAPI_INF("No ports? %s", mss::c_str(i_target));
            return fapi2::FAPI2_RC_SUCCESS;
        }

        // Configure the CCS engine. Since this is a chunk of McBIST logic, we don't want
        // to do it for every port. If we ever break this code out so f/w can call draminit
        // per-port (separate threads) we'll need to proved them a way to set this up before
        // sapwning per-port threads.
        {
            fapi2::buffer<uint64_t> l_ccs_config;

            FAPI_TRY( mss::ccs::read_mode(i_target, l_ccs_config) );

            // It's unclear if we want to run with this true or false. Right now (10/15) this
            // has to be false. Shelton was unclear if this should be on or off in general BRS
            mss::ccs::stop_on_err(i_target, l_ccs_config, mss::LOW);
            mss::ccs::ue_disable(i_target, l_ccs_config, mss::LOW);
            mss::ccs::copy_cke_to_spare_cke(i_target, l_ccs_config, mss::HIGH);

#ifndef JIM_SAYS_TURN_OFF_ECC
            mss::ccs::disable_ecc(i_target, l_ccs_config);
#endif
            FAPI_TRY( mss::ccs::write_mode(i_target, l_ccs_config) );
        }

        // We initialize dram by iterating over the (ungarded) ports. We could allow the caller
        // to initialize each port's dram on a separate thread if we could synchronize access
        // to the MCBIST (CCS engine.) Right now we can't, so we'll do it this way.

        //
        // We expect to come in to draminit with the following setup:
        // 1. ENABLE_RESET_N (FARB5Q(6)) 0
        // 2. RESET_N (FARB5Q(4)) 0 - driving reset
        // 3. CCS_ADDR_MUX_SEL (FARB5Q(5)) - 1
        // 4. CKE out of high impedence
        //
        for (auto p : l_mca)
        {
            FAPI_TRY( mss::draminit_entry_invariant(p) );
            FAPI_TRY( mss::ddr_resetn(p, mss::HIGH) );

            // Begin driving mem clks, and wait 10ns (we'll do this outside the loop)
            FAPI_TRY( mss::drive_mem_clks(p, PCLK_INITIAL_VALUE, NCLK_INITIAL_VALUE) );
        }

        // Clocks need to be started and stable for 10ns before CKE goes active.
        // Not 100% clear what cycle count to use here. We'll assume 2400 for now. 10ns is 13 cycles freq 2400.
        FAPI_TRY( fapi2::delay(mss::DELAY_10NS, mss::cycles_to_simcycles(13)) );

        // Register DES instruction, which pulls CKE high. Idle 400 cycles, and then begin RCD loading
        // Note: This only is sent to one of the MCA as we still have the mux_addr_sel bit set, meaning
        // we'll PDE/DES all DIMM at the same time.
        l_des.arr1.insertFromRight<MCBIST_CCS_INST_ARR1_00_IDLES, MCBIST_CCS_INST_ARR1_00_IDLES_LEN>(400);
        l_program.iv_instructions.push_back(l_des);
        FAPI_TRY( mss::ccs::execute(i_target, l_program, l_mca[0]) );

        // Per conversation with Shelton and Steve 10/9/15, turn off addr_mux_sel after the CKE CCS but
        // before the RCD/MRS CCSs
        for (auto p : l_mca)
        {
            FAPI_TRY( change_addr_mux_sel(p, mss::LOW) );
        }

        // Load RCD control words
        FAPI_TRY( mss::rcd_load(i_target) );

        // Load MRS
        FAPI_TRY( mss::mrs_load(i_target) );

    fapi_try_exit:
        FAPI_INF("End draminit: %s (0x%lx)", mss::c_str(i_target), uint64_t(fapi2::current_err));
        return fapi2::current_err;
    }
}
<commit_msg>Add count_dimm<commit_after>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/memory/p9_mss_draminit.C $ */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2015,2019                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* 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.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */

///
/// @file p9_mss_draminit.C
/// @brief Initialize dram
///
// *HWP HWP Owner: Brian Silver <bsilver@us.ibm.com>
// *HWP HWP Backup: Andre Marin <aamarin@us.ibm.com>
// *HWP Team: Memory
// *HWP Level: 2
// *HWP Consumed by: FSP:HB

#include <fapi2.H>
#include <mss.H>

#include <p9_mss_draminit.H>
#include <lib/utils/count_dimm.H>

using fapi2::TARGET_TYPE_MCBIST;
using fapi2::TARGET_TYPE_MCA;
using fapi2::TARGET_TYPE_DIMM;
using fapi2::FAPI2_RC_SUCCESS;

extern "C"
{
///
/// @brief Initialize dram
/// @param[in] i_target, the McBIST of the ports of the dram you're initializing
/// @return FAPI2_RC_SUCCESS iff ok
///
    fapi2::ReturnCode p9_mss_draminit( const fapi2::Target<TARGET_TYPE_MCBIST>& i_target )
    {
        fapi2::buffer<uint64_t> l_data;

        mss::ccs::instruction_t<TARGET_TYPE_MCBIST> l_inst;
        mss::ccs::instruction_t<TARGET_TYPE_MCBIST> l_des = mss::ccs::des_command<TARGET_TYPE_MCBIST>();

        mss::ccs::program<TARGET_TYPE_MCBIST> l_program;

        static const uint64_t PCLK_INITIAL_VALUE = 0x02;
        static const uint64_t NCLK_INITIAL_VALUE = 0x01;

        auto l_mca = i_target.getChildren<TARGET_TYPE_MCA>();

        FAPI_INF("Start draminit: %s", mss::c_str(i_target));

        // If we don't have any ports, lets go.
        if (l_mca.size() == 0)
        {
            FAPI_INF("++++ No ports? %s ++++", mss::c_str(i_target));
            return fapi2::FAPI2_RC_SUCCESS;
        }

        // If we don't have any DIMM, lets go.
        if (mss::count_dimm(i_target) == 0)
        {
            FAPI_INF("++++ NO DIMM on %s ++++", mss::c_str(i_target));
            return fapi2::FAPI2_RC_SUCCESS;
        }

        // Configure the CCS engine. Since this is a chunk of McBIST logic, we don't want
        // to do it for every port. If we ever break this code out so f/w can call draminit
        // per-port (separate threads) we'll need to proved them a way to set this up before
        // sapwning per-port threads.
        {
            fapi2::buffer<uint64_t> l_ccs_config;

            FAPI_TRY( mss::ccs::read_mode(i_target, l_ccs_config) );

            // It's unclear if we want to run with this true or false. Right now (10/15) this
            // has to be false. Shelton was unclear if this should be on or off in general BRS
            mss::ccs::stop_on_err(i_target, l_ccs_config, mss::LOW);
            mss::ccs::ue_disable(i_target, l_ccs_config, mss::LOW);
            mss::ccs::copy_cke_to_spare_cke(i_target, l_ccs_config, mss::HIGH);

#ifndef JIM_SAYS_TURN_OFF_ECC
            mss::ccs::disable_ecc(i_target, l_ccs_config);
#endif
            FAPI_TRY( mss::ccs::write_mode(i_target, l_ccs_config) );
        }

        // We initialize dram by iterating over the (ungarded) ports. We could allow the caller
        // to initialize each port's dram on a separate thread if we could synchronize access
        // to the MCBIST (CCS engine.) Right now we can't, so we'll do it this way.

        //
        // We expect to come in to draminit with the following setup:
        // 1. ENABLE_RESET_N (FARB5Q(6)) 0
        // 2. RESET_N (FARB5Q(4)) 0 - driving reset
        // 3. CCS_ADDR_MUX_SEL (FARB5Q(5)) - 1
        // 4. CKE out of high impedence
        //
        for (auto p : l_mca)
        {
            FAPI_TRY( mss::draminit_entry_invariant(p) );
            FAPI_TRY( mss::ddr_resetn(p, mss::HIGH) );

            // Begin driving mem clks, and wait 10ns (we'll do this outside the loop)
            FAPI_TRY( mss::drive_mem_clks(p, PCLK_INITIAL_VALUE, NCLK_INITIAL_VALUE) );
        }

        // Clocks need to be started and stable for 10ns before CKE goes active.
        // Not 100% clear what cycle count to use here. We'll assume 2400 for now. 10ns is 13 cycles freq 2400.
        FAPI_TRY( fapi2::delay(mss::DELAY_10NS, mss::cycles_to_simcycles(13)) );

        // Register DES instruction, which pulls CKE high. Idle 400 cycles, and then begin RCD loading
        // Note: This only is sent to one of the MCA as we still have the mux_addr_sel bit set, meaning
        // we'll PDE/DES all DIMM at the same time.
        l_des.arr1.insertFromRight<MCBIST_CCS_INST_ARR1_00_IDLES, MCBIST_CCS_INST_ARR1_00_IDLES_LEN>(400);
        l_program.iv_instructions.push_back(l_des);
        FAPI_TRY( mss::ccs::execute(i_target, l_program, l_mca[0]) );

        // Per conversation with Shelton and Steve 10/9/15, turn off addr_mux_sel after the CKE CCS but
        // before the RCD/MRS CCSs
        for (auto p : l_mca)
        {
            FAPI_TRY( change_addr_mux_sel(p, mss::LOW) );
        }

        // Load RCD control words
        FAPI_TRY( mss::rcd_load(i_target) );

        // Load MRS
        FAPI_TRY( mss::mrs_load(i_target) );

    fapi_try_exit:
        FAPI_INF("End draminit: %s (0x%lx)", mss::c_str(i_target), uint64_t(fapi2::current_err));
        return fapi2::current_err;
    }
}
<|endoftext|>


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

#include "chrome/browser/extensions/api/declarative/rules_registry_storage_delegate.h"

#include "base/bind.h"
#include "base/metrics/histogram.h"
#include "base/time.h"
#include "chrome/browser/extensions/extension_info_map.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/extensions/extension_system.h"
#include "chrome/browser/extensions/state_store.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/common/chrome_notification_types.h"
#include "chrome/common/extensions/extension.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/notification_details.h"
#include "content/public/browser/notification_source.h"

namespace extensions {

namespace {

scoped_ptr<base::Value> RulesToValue(
    const std::vector<linked_ptr<RulesRegistry::Rule> >& rules) {
  scoped_ptr<base::ListValue> list(new base::ListValue());
  for (size_t i = 0; i < rules.size(); ++i)
    list->Append(rules[i]->ToValue().release());
  return list.PassAs<base::Value>();
}

std::vector<linked_ptr<RulesRegistry::Rule> > RulesFromValue(
    base::Value* value) {
  std::vector<linked_ptr<RulesRegistry::Rule> > rules;

  base::ListValue* list = NULL;
  if (!value || !value->GetAsList(&list))
    return rules;

  for (size_t i = 0; i < list->GetSize(); ++i) {
    base::DictionaryValue* dict = NULL;
    if (!list->GetDictionary(i, &dict))
      continue;
    linked_ptr<RulesRegistry::Rule> rule(new RulesRegistry::Rule());
    if (RulesRegistry::Rule::Populate(*dict, rule.get()))
      rules.push_back(rule);
  }

  return rules;
}

}  // namespace

// This class coordinates information between the UI and RulesRegistry threads.
// It may outlive the RulesRegistry, which owns the delegate. Methods/variables
// should be used on the UI thread unless otherwise noted.
class RulesRegistryStorageDelegate::Inner
    : public content::NotificationObserver,
      public base::RefCountedThreadSafe<Inner> {
 public:
  Inner(Profile* profile,
        RulesRegistryWithCache* rules_registry,
        const std::string& storage_key);

 private:
  friend class base::RefCountedThreadSafe<Inner>;
  friend class RulesRegistryStorageDelegate;

  virtual ~Inner();

  // Initialization of the storage delegate if it is used in the context of
  // an incognito profile.
  void InitForOTRProfile();

  // NotificationObserver
  virtual void Observe(
      int type,
      const content::NotificationSource& source,
      const content::NotificationDetails& details) OVERRIDE;

  // Read/write a list of rules serialized to Values.
  void ReadFromStorage(const std::string& extension_id);
  void ReadFromStorageCallback(const std::string& extension_id,
                       scoped_ptr<base::Value> value);
  void WriteToStorage(const std::string& extension_id,
                      scoped_ptr<base::Value> value);

  // Check if we are done reading all data from storage on startup, and notify
  // the RulesRegistry on its thread if so. The notification is delivered
  // exactly once.
  void CheckIfReady();

  // Deserialize the rules from the given Value object and add them to the
  // RulesRegistry.
  void ReadFromStorageOnRegistryThread(const std::string& extension_id,
                                       scoped_ptr<base::Value> value);

  // Notify the RulesRegistry that we are now ready.
  void NotifyReadyOnRegistryThread();

  scoped_ptr<content::NotificationRegistrar> registrar_;
  Profile* profile_;

  // The key under which rules are stored.
  const std::string storage_key_;

  // A set of extension IDs that have rules we are reading from storage.
  std::set<std::string> waiting_for_extensions_;

  // The thread that our RulesRegistry lives on.
  content::BrowserThread::ID rules_registry_thread_;

  // The following are only accessible on rules_registry_thread_.

  // The RulesRegistry whose delegate we are.
  RulesRegistryWithCache* rules_registry_;

  // True when we have finished reading from storage for all extensions that
  // are loaded on startup.
  bool ready_;

  // We measure the time spent on loading rules on init. The result is logged
  // with UMA once per the delegate instance, unless in Incognito.
  base::Time storage_init_time_;
  bool log_storage_init_delay_;
  // TODO(vabr): Could |ready_| be used instead of |log_storage_init_delay_|?
  // http://crbug.com/176926
};

RulesRegistryStorageDelegate::RulesRegistryStorageDelegate() {
}

RulesRegistryStorageDelegate::~RulesRegistryStorageDelegate() {
  // RulesRegistry owns us, which means it has been deleted.
  inner_->rules_registry_ = NULL;
}

void RulesRegistryStorageDelegate::InitOnUIThread(
    Profile* profile,
    RulesRegistryWithCache* rules_registry,
    const std::string& storage_key) {
  DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
  extensions::StateStore* store = ExtensionSystem::Get(profile)->rules_store();
  if (store)
    store->RegisterKey(storage_key);
  inner_ = new Inner(profile, rules_registry, storage_key);
}

void RulesRegistryStorageDelegate::CleanupOnUIThread() {
  // The registrar must be deleted on the UI thread.
  inner_->registrar_.reset();
  inner_->profile_ = NULL;  // no longer safe to use.
}

bool RulesRegistryStorageDelegate::IsReady() {
  DCHECK(content::BrowserThread::CurrentlyOn(inner_->rules_registry_thread_));
  return inner_->ready_;
}

void RulesRegistryStorageDelegate::OnRulesChanged(
    RulesRegistryWithCache* rules_registry,
    const std::string& extension_id) {
  DCHECK(content::BrowserThread::CurrentlyOn(inner_->rules_registry_thread_));
  std::vector<linked_ptr<RulesRegistry::Rule> > new_rules;
  std::string error = rules_registry->GetAllRules(extension_id, &new_rules);
  DCHECK_EQ("", error);
  content::BrowserThread::PostTask(
      content::BrowserThread::UI, FROM_HERE,
      base::Bind(&Inner::WriteToStorage, inner_.get(), extension_id,
                 base::Passed(RulesToValue(new_rules))));
}

RulesRegistryStorageDelegate::Inner::Inner(
    Profile* profile,
    RulesRegistryWithCache* rules_registry,
    const std::string& storage_key)
    : registrar_(new content::NotificationRegistrar()),
      profile_(profile),
      storage_key_(storage_key),
      rules_registry_thread_(rules_registry->GetOwnerThread()),
      rules_registry_(rules_registry),
      ready_(false),
      log_storage_init_delay_(true) {
  if (!profile_->IsOffTheRecord()) {
    registrar_->Add(this, chrome::NOTIFICATION_EXTENSION_LOADED,
                    content::Source<Profile>(profile));
    registrar_->Add(this, chrome::NOTIFICATION_EXTENSIONS_READY,
                    content::Source<Profile>(profile));
  } else {
    log_storage_init_delay_ = false;
    registrar_->Add(this, chrome::NOTIFICATION_EXTENSION_LOADED,
                    content::Source<Profile>(profile->GetOriginalProfile()));
    InitForOTRProfile();
  }
}

RulesRegistryStorageDelegate::Inner::~Inner() {
  DCHECK(!registrar_.get());
}

void RulesRegistryStorageDelegate::Inner::InitForOTRProfile() {
  ExtensionService* extension_service =
      extensions::ExtensionSystem::Get(profile_)->extension_service();
  const ExtensionSet* extensions = extension_service->extensions();
  for (ExtensionSet::const_iterator i = extensions->begin();
       i != extensions->end(); ++i) {
    if (((*i)->HasAPIPermission(APIPermission::kDeclarativeContent) ||
         (*i)->HasAPIPermission(APIPermission::kDeclarativeWebRequest)) &&
        extension_service->IsIncognitoEnabled((*i)->id()))
      ReadFromStorage((*i)->id());
  }
  ready_ = true;
}

void RulesRegistryStorageDelegate::Inner::Observe(
    int type,
    const content::NotificationSource& source,
    const content::NotificationDetails& details) {
  DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
  if (type == chrome::NOTIFICATION_EXTENSION_LOADED) {
    const extensions::Extension* extension =
        content::Details<const extensions::Extension>(details).ptr();
    // TODO(mpcomplete): This API check should generalize to any use of
    // declarative rules, not just webRequest.
    if (extension->HasAPIPermission(APIPermission::kDeclarativeContent) ||
        extension->HasAPIPermission(APIPermission::kDeclarativeWebRequest)) {
      ExtensionInfoMap* extension_info_map =
          ExtensionSystem::Get(profile_)->info_map();
      if (profile_->IsOffTheRecord() &&
          !extension_info_map->IsIncognitoEnabled(extension->id())) {
        // Ignore this extension.
      } else {
        ReadFromStorage(extension->id());
      }
    }
  } else if (type == chrome::NOTIFICATION_EXTENSIONS_READY) {
    CheckIfReady();
  }
}

void RulesRegistryStorageDelegate::Inner::ReadFromStorage(
    const std::string& extension_id) {
  DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
  if (!profile_)
    return;

  if (storage_init_time_.is_null())
    storage_init_time_ = base::Time::Now();

  extensions::StateStore* store = ExtensionSystem::Get(profile_)->rules_store();
  if (store) {
    waiting_for_extensions_.insert(extension_id);
    store->GetExtensionValue(extension_id, storage_key_,
        base::Bind(&Inner::ReadFromStorageCallback, this, extension_id));
  }

  // TODO(mpcomplete): Migration code. Remove when declarativeWebRequest goes
  // to stable.
  // http://crbug.com/166474
  store = ExtensionSystem::Get(profile_)->state_store();
  if (store) {
    waiting_for_extensions_.insert(extension_id);
    store->GetExtensionValue(extension_id, storage_key_,
        base::Bind(&Inner::ReadFromStorageCallback, this, extension_id));
    store->RemoveExtensionValue(extension_id, storage_key_);
  }
}

void RulesRegistryStorageDelegate::Inner::ReadFromStorageCallback(
    const std::string& extension_id, scoped_ptr<base::Value> value) {
  DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
  content::BrowserThread::PostTask(
      rules_registry_thread_, FROM_HERE,
      base::Bind(&Inner::ReadFromStorageOnRegistryThread, this, extension_id,
                 base::Passed(&value)));

  waiting_for_extensions_.erase(extension_id);
  CheckIfReady();
  if (log_storage_init_delay_ && waiting_for_extensions_.empty()) {
    UMA_HISTOGRAM_TIMES("Extensions.DeclarativeRulesStorageInitialization",
                        base::Time::Now() - storage_init_time_);
    log_storage_init_delay_ = false;
  }
}

void RulesRegistryStorageDelegate::Inner::WriteToStorage(
    const std::string& extension_id, scoped_ptr<base::Value> value) {
  DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
  if (!profile_)
    return;

  StateStore* store = ExtensionSystem::Get(profile_)->rules_store();
  if (store)
    store->SetExtensionValue(extension_id, storage_key_, value.Pass());
}

void RulesRegistryStorageDelegate::Inner::CheckIfReady() {
  DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
  if (!waiting_for_extensions_.empty())
    return;

  content::BrowserThread::PostTask(
      rules_registry_thread_, FROM_HERE,
      base::Bind(&Inner::NotifyReadyOnRegistryThread, this));
}

void RulesRegistryStorageDelegate::Inner::ReadFromStorageOnRegistryThread(
    const std::string& extension_id, scoped_ptr<base::Value> value) {
  DCHECK(content::BrowserThread::CurrentlyOn(rules_registry_thread_));
  if (!rules_registry_)
    return;  // registry went away

  rules_registry_->AddRules(extension_id, RulesFromValue(value.get()));
}

void RulesRegistryStorageDelegate::Inner::NotifyReadyOnRegistryThread() {
  DCHECK(content::BrowserThread::CurrentlyOn(rules_registry_thread_));
  if (ready_)
    return;  // we've already notified our readiness

  ready_ = true;
  rules_registry_->OnReady();
}

}  // namespace extensions
<commit_msg>Declarative Web Request: avoid premature ready_=true in InitForOTRProfile<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/extensions/api/declarative/rules_registry_storage_delegate.h"

#include "base/bind.h"
#include "base/metrics/histogram.h"
#include "base/time.h"
#include "chrome/browser/extensions/extension_info_map.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/extensions/extension_system.h"
#include "chrome/browser/extensions/state_store.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/common/chrome_notification_types.h"
#include "chrome/common/extensions/extension.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/notification_details.h"
#include "content/public/browser/notification_source.h"

namespace extensions {

namespace {

scoped_ptr<base::Value> RulesToValue(
    const std::vector<linked_ptr<RulesRegistry::Rule> >& rules) {
  scoped_ptr<base::ListValue> list(new base::ListValue());
  for (size_t i = 0; i < rules.size(); ++i)
    list->Append(rules[i]->ToValue().release());
  return list.PassAs<base::Value>();
}

std::vector<linked_ptr<RulesRegistry::Rule> > RulesFromValue(
    base::Value* value) {
  std::vector<linked_ptr<RulesRegistry::Rule> > rules;

  base::ListValue* list = NULL;
  if (!value || !value->GetAsList(&list))
    return rules;

  for (size_t i = 0; i < list->GetSize(); ++i) {
    base::DictionaryValue* dict = NULL;
    if (!list->GetDictionary(i, &dict))
      continue;
    linked_ptr<RulesRegistry::Rule> rule(new RulesRegistry::Rule());
    if (RulesRegistry::Rule::Populate(*dict, rule.get()))
      rules.push_back(rule);
  }

  return rules;
}

}  // namespace

// This class coordinates information between the UI and RulesRegistry threads.
// It may outlive the RulesRegistry, which owns the delegate. Methods/variables
// should be used on the UI thread unless otherwise noted.
class RulesRegistryStorageDelegate::Inner
    : public content::NotificationObserver,
      public base::RefCountedThreadSafe<Inner> {
 public:
  Inner(Profile* profile,
        RulesRegistryWithCache* rules_registry,
        const std::string& storage_key);

 private:
  friend class base::RefCountedThreadSafe<Inner>;
  friend class RulesRegistryStorageDelegate;

  virtual ~Inner();

  // Initialization of the storage delegate if it is used in the context of
  // an incognito profile.
  void InitForOTRProfile();

  // NotificationObserver
  virtual void Observe(
      int type,
      const content::NotificationSource& source,
      const content::NotificationDetails& details) OVERRIDE;

  // Read/write a list of rules serialized to Values.
  void ReadFromStorage(const std::string& extension_id);
  void ReadFromStorageCallback(const std::string& extension_id,
                       scoped_ptr<base::Value> value);
  void WriteToStorage(const std::string& extension_id,
                      scoped_ptr<base::Value> value);

  // Check if we are done reading all data from storage on startup, and notify
  // the RulesRegistry on its thread if so. The notification is delivered
  // exactly once.
  void CheckIfReady();

  // Deserialize the rules from the given Value object and add them to the
  // RulesRegistry.
  void ReadFromStorageOnRegistryThread(const std::string& extension_id,
                                       scoped_ptr<base::Value> value);

  // Notify the RulesRegistry that we are now ready.
  void NotifyReadyOnRegistryThread();

  scoped_ptr<content::NotificationRegistrar> registrar_;
  Profile* profile_;

  // The key under which rules are stored.
  const std::string storage_key_;

  // A set of extension IDs that have rules we are reading from storage.
  std::set<std::string> waiting_for_extensions_;

  // The thread that our RulesRegistry lives on.
  content::BrowserThread::ID rules_registry_thread_;

  // The following are only accessible on rules_registry_thread_.

  // The RulesRegistry whose delegate we are.
  RulesRegistryWithCache* rules_registry_;

  // True when we have finished reading from storage for all extensions that
  // are loaded on startup.
  bool ready_;

  // We measure the time spent on loading rules on init. The result is logged
  // with UMA once per the delegate instance, unless in Incognito.
  base::Time storage_init_time_;
  bool log_storage_init_delay_;
  // TODO(vabr): Could |ready_| be used instead of |log_storage_init_delay_|?
  // http://crbug.com/176926
};

RulesRegistryStorageDelegate::RulesRegistryStorageDelegate() {
}

RulesRegistryStorageDelegate::~RulesRegistryStorageDelegate() {
  // RulesRegistry owns us, which means it has been deleted.
  inner_->rules_registry_ = NULL;
}

void RulesRegistryStorageDelegate::InitOnUIThread(
    Profile* profile,
    RulesRegistryWithCache* rules_registry,
    const std::string& storage_key) {
  DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
  extensions::StateStore* store = ExtensionSystem::Get(profile)->rules_store();
  if (store)
    store->RegisterKey(storage_key);
  inner_ = new Inner(profile, rules_registry, storage_key);
}

void RulesRegistryStorageDelegate::CleanupOnUIThread() {
  // The registrar must be deleted on the UI thread.
  inner_->registrar_.reset();
  inner_->profile_ = NULL;  // no longer safe to use.
}

bool RulesRegistryStorageDelegate::IsReady() {
  DCHECK(content::BrowserThread::CurrentlyOn(inner_->rules_registry_thread_));
  return inner_->ready_;
}

void RulesRegistryStorageDelegate::OnRulesChanged(
    RulesRegistryWithCache* rules_registry,
    const std::string& extension_id) {
  DCHECK(content::BrowserThread::CurrentlyOn(inner_->rules_registry_thread_));
  std::vector<linked_ptr<RulesRegistry::Rule> > new_rules;
  std::string error = rules_registry->GetAllRules(extension_id, &new_rules);
  DCHECK_EQ("", error);
  content::BrowserThread::PostTask(
      content::BrowserThread::UI, FROM_HERE,
      base::Bind(&Inner::WriteToStorage, inner_.get(), extension_id,
                 base::Passed(RulesToValue(new_rules))));
}

RulesRegistryStorageDelegate::Inner::Inner(
    Profile* profile,
    RulesRegistryWithCache* rules_registry,
    const std::string& storage_key)
    : registrar_(new content::NotificationRegistrar()),
      profile_(profile),
      storage_key_(storage_key),
      rules_registry_thread_(rules_registry->GetOwnerThread()),
      rules_registry_(rules_registry),
      ready_(false),
      log_storage_init_delay_(true) {
  if (!profile_->IsOffTheRecord()) {
    registrar_->Add(this, chrome::NOTIFICATION_EXTENSION_LOADED,
                    content::Source<Profile>(profile));
    registrar_->Add(this, chrome::NOTIFICATION_EXTENSIONS_READY,
                    content::Source<Profile>(profile));
  } else {
    log_storage_init_delay_ = false;
    registrar_->Add(this, chrome::NOTIFICATION_EXTENSION_LOADED,
                    content::Source<Profile>(profile->GetOriginalProfile()));
    InitForOTRProfile();
  }
}

RulesRegistryStorageDelegate::Inner::~Inner() {
  DCHECK(!registrar_.get());
}

void RulesRegistryStorageDelegate::Inner::InitForOTRProfile() {
  ExtensionService* extension_service =
      extensions::ExtensionSystem::Get(profile_)->extension_service();
  const ExtensionSet* extensions = extension_service->extensions();
  for (ExtensionSet::const_iterator i = extensions->begin();
       i != extensions->end(); ++i) {
    if (((*i)->HasAPIPermission(APIPermission::kDeclarativeContent) ||
         (*i)->HasAPIPermission(APIPermission::kDeclarativeWebRequest)) &&
        extension_service->IsIncognitoEnabled((*i)->id()))
      ReadFromStorage((*i)->id());
  }
  CheckIfReady();
}

void RulesRegistryStorageDelegate::Inner::Observe(
    int type,
    const content::NotificationSource& source,
    const content::NotificationDetails& details) {
  DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
  if (type == chrome::NOTIFICATION_EXTENSION_LOADED) {
    const extensions::Extension* extension =
        content::Details<const extensions::Extension>(details).ptr();
    // TODO(mpcomplete): This API check should generalize to any use of
    // declarative rules, not just webRequest.
    if (extension->HasAPIPermission(APIPermission::kDeclarativeContent) ||
        extension->HasAPIPermission(APIPermission::kDeclarativeWebRequest)) {
      ExtensionInfoMap* extension_info_map =
          ExtensionSystem::Get(profile_)->info_map();
      if (profile_->IsOffTheRecord() &&
          !extension_info_map->IsIncognitoEnabled(extension->id())) {
        // Ignore this extension.
      } else {
        ReadFromStorage(extension->id());
      }
    }
  } else if (type == chrome::NOTIFICATION_EXTENSIONS_READY) {
    CheckIfReady();
  }
}

void RulesRegistryStorageDelegate::Inner::ReadFromStorage(
    const std::string& extension_id) {
  DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
  if (!profile_)
    return;

  if (storage_init_time_.is_null())
    storage_init_time_ = base::Time::Now();

  extensions::StateStore* store = ExtensionSystem::Get(profile_)->rules_store();
  if (store) {
    waiting_for_extensions_.insert(extension_id);
    store->GetExtensionValue(extension_id, storage_key_,
        base::Bind(&Inner::ReadFromStorageCallback, this, extension_id));
  }

  // TODO(mpcomplete): Migration code. Remove when declarativeWebRequest goes
  // to stable.
  // http://crbug.com/166474
  store = ExtensionSystem::Get(profile_)->state_store();
  if (store) {
    waiting_for_extensions_.insert(extension_id);
    store->GetExtensionValue(extension_id, storage_key_,
        base::Bind(&Inner::ReadFromStorageCallback, this, extension_id));
    store->RemoveExtensionValue(extension_id, storage_key_);
  }
}

void RulesRegistryStorageDelegate::Inner::ReadFromStorageCallback(
    const std::string& extension_id, scoped_ptr<base::Value> value) {
  DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
  content::BrowserThread::PostTask(
      rules_registry_thread_, FROM_HERE,
      base::Bind(&Inner::ReadFromStorageOnRegistryThread, this, extension_id,
                 base::Passed(&value)));

  waiting_for_extensions_.erase(extension_id);
  CheckIfReady();
  if (log_storage_init_delay_ && waiting_for_extensions_.empty()) {
    UMA_HISTOGRAM_TIMES("Extensions.DeclarativeRulesStorageInitialization",
                        base::Time::Now() - storage_init_time_);
    log_storage_init_delay_ = false;
  }
}

void RulesRegistryStorageDelegate::Inner::WriteToStorage(
    const std::string& extension_id, scoped_ptr<base::Value> value) {
  DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
  if (!profile_)
    return;

  StateStore* store = ExtensionSystem::Get(profile_)->rules_store();
  if (store)
    store->SetExtensionValue(extension_id, storage_key_, value.Pass());
}

void RulesRegistryStorageDelegate::Inner::CheckIfReady() {
  DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
  if (!waiting_for_extensions_.empty())
    return;

  content::BrowserThread::PostTask(
      rules_registry_thread_, FROM_HERE,
      base::Bind(&Inner::NotifyReadyOnRegistryThread, this));
}

void RulesRegistryStorageDelegate::Inner::ReadFromStorageOnRegistryThread(
    const std::string& extension_id, scoped_ptr<base::Value> value) {
  DCHECK(content::BrowserThread::CurrentlyOn(rules_registry_thread_));
  if (!rules_registry_)
    return;  // registry went away

  rules_registry_->AddRules(extension_id, RulesFromValue(value.get()));
}

void RulesRegistryStorageDelegate::Inner::NotifyReadyOnRegistryThread() {
  DCHECK(content::BrowserThread::CurrentlyOn(rules_registry_thread_));
  if (ready_)
    return;  // we've already notified our readiness

  ready_ = true;
  rules_registry_->OnReady();
}

}  // namespace extensions
<|endoftext|>


<commit_before>#ifndef __REQUEST_POSTURE_H_INCLUDE__
#define __REQUEST_POSTURE_H_INCLUDE__

#include <vector>
#include <string>
#include <map>

class RequestPosture {
public:
  virtual ~RequestPosure(){};
  virtual void requestPosture(std::vector<double>& posture) = 0;
}

void getRequestPosture(std::map<std::string, RequestPosture*>& map);
void delRequestPosture(std::map<std::string, RequestPosture*>& map);

#endif

<commit_msg>Update request posture factory to class from funcs<commit_after>#ifndef __REQUEST_POSTURE_H_INCLUDE__
#define __REQUEST_POSTURE_H_INCLUDE__

#include <vector>
#include <string>

class RequestPosture {
public:
  virtual ~RequestPosure(){};
  virtual void requestPosture(std::vector<double>& posture) = 0;
}

class RequestPostureFactory {
private:
  RequestPostureFactory();

public:
  static RequestPosture* get(std::string);
  static std::map<std::string, RequestPosture*> reqs;
}

#endif

<|endoftext|>


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

Licensed to the OpenCOR team under one or more contributor license agreements.
See the NOTICE.txt file distributed with this work for additional information
regarding copyright ownership. The OpenCOR team licenses this file to you under
the Apache License, Version 2.0 (the "License"); you may not use this file
except in compliance with the License. You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

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.

*******************************************************************************/

//==============================================================================
// CellML file manager
//==============================================================================

#include "cellmlfilemanager.h"
#include "cellmlsupportplugin.h"
#include "corecliutils.h"
#include "filemanager.h"

//==============================================================================

namespace OpenCOR {
namespace CellMLSupport {

//==============================================================================

CellmlFileManager::CellmlFileManager() :
    mCellmlFiles(CellmlFiles())
{
    // Create some connections to keep track of some events related to our
    // 'global' file manager

    Core::FileManager *fileManagerInstance = Core::FileManager::instance();

    connect(fileManagerInstance, SIGNAL(fileManaged(const QString &)),
            this, SLOT(manageFile(const QString &)));
    connect(fileManagerInstance, SIGNAL(fileUnmanaged(const QString &)),
            this, SLOT(unmanageFile(const QString &)));

    connect(fileManagerInstance, SIGNAL(fileReloaded(const QString &)),
            this, SLOT(reloadFile(const QString &)));

    connect(fileManagerInstance, SIGNAL(fileRenamed(const QString &, const QString &)),
            this, SLOT(renameFile(const QString &, const QString &)));
}

//==============================================================================

CellmlFileManager::~CellmlFileManager()
{
    // Remove all the managed files

    foreach (CellmlFile *cellmlFile, mCellmlFiles)
        delete cellmlFile;
}

//==============================================================================

CellmlFileManager * CellmlFileManager::instance()
{
    // Return the 'global' instance of our CellML file manager class

    static CellmlFileManager instance;

    return static_cast<CellmlFileManager *>(Core::globalInstance("OpenCOR::CellMLSupport::CellmlFileManager",
                                                                 &instance));
}

//==============================================================================

CellmlFile * CellmlFileManager::cellmlFile(const QString &pFileName)
{
    // Return the CellmlFile object, if any, associated with our given file

    return mCellmlFiles.value(Core::nativeCanonicalFileName(pFileName));
}

//==============================================================================

void CellmlFileManager::manageFile(const QString &pFileName)
{
    QString nativeFileName = Core::nativeCanonicalFileName(pFileName);

    if (!cellmlFile(nativeFileName) && isCellmlFile(nativeFileName))
        // We are dealing with a CellML file, which is not already managed, so
        // we can add it to our list of managed CellML files

        mCellmlFiles.insert(nativeFileName, new CellmlFile(nativeFileName));
}

//==============================================================================

void CellmlFileManager::unmanageFile(const QString &pFileName)
{
    CellmlFile *crtCellmlFile = cellmlFile(pFileName);

    if (crtCellmlFile) {
        // We are dealing with a CellML file, so we can remove it from our list
        // of managed CellML files after having deleted it

        delete crtCellmlFile;

        mCellmlFiles.remove(Core::nativeCanonicalFileName(pFileName));
    }
}

//==============================================================================

void CellmlFileManager::reloadFile(const QString &pFileName)
{
    // The file is to be reloaded, so reload it
    // Note: to reload a file here ensures that our different CellML-based views
    //       won't each do it, thus saving time and ensuring that a CellML-based
    //       view doesn't forget to do it...

    CellmlFile *crtCellmlFile = cellmlFile(pFileName);

    if (crtCellmlFile) {
        // The file is managed, but should it still be (i.e. can it still be
        // considered as being a CellML file)?

        if (isCellmlFile(pFileName))
            crtCellmlFile->reload();
        else
            unmanageFile(pFileName);
    } else {
        // The file is not managed, which means that previously it wasn't
        // considered as being a CellML file, but things may be different now,
        // so try to remanage it and load it, if possible

        manageFile(pFileName);

        crtCellmlFile = cellmlFile(pFileName);

        if (crtCellmlFile)
            crtCellmlFile->load();
    }
}

//==============================================================================

void CellmlFileManager::renameFile(const QString &pOldFileName,
                                   const QString &pNewFileName)
{
    // The file has been renamed, so we need to update our CellML files mapping,
    // if needed

    CellmlFile *crtCellmlFile = cellmlFile(pOldFileName);

    if (!crtCellmlFile)
        return;

    mCellmlFiles.insert(pNewFileName, crtCellmlFile);
    mCellmlFiles.remove(pOldFileName);

    // We also need to ensure that our CellML file object has its file name
    // updated

    crtCellmlFile->setFileName(pNewFileName);
}

//==============================================================================

}   // namespace CellMLSupport
}   // namespace OpenCOR

//==============================================================================
// End of file
//==============================================================================
<commit_msg>Some minor cleaning up [ci skip].<commit_after>/*******************************************************************************

Licensed to the OpenCOR team under one or more contributor license agreements.
See the NOTICE.txt file distributed with this work for additional information
regarding copyright ownership. The OpenCOR team licenses this file to you under
the Apache License, Version 2.0 (the "License"); you may not use this file
except in compliance with the License. You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

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.

*******************************************************************************/

//==============================================================================
// CellML file manager
//==============================================================================

#include "cellmlfilemanager.h"
#include "cellmlsupportplugin.h"
#include "corecliutils.h"
#include "filemanager.h"

//==============================================================================

namespace OpenCOR {
namespace CellMLSupport {

//==============================================================================

CellmlFileManager::CellmlFileManager() :
    mCellmlFiles(CellmlFiles())
{
    // Create some connections to keep track of some events related to our
    // 'global' file manager

    Core::FileManager *fileManagerInstance = Core::FileManager::instance();

    connect(fileManagerInstance, SIGNAL(fileManaged(const QString &)),
            this, SLOT(manageFile(const QString &)));
    connect(fileManagerInstance, SIGNAL(fileUnmanaged(const QString &)),
            this, SLOT(unmanageFile(const QString &)));

    connect(fileManagerInstance, SIGNAL(fileReloaded(const QString &)),
            this, SLOT(reloadFile(const QString &)));

    connect(fileManagerInstance, SIGNAL(fileRenamed(const QString &, const QString &)),
            this, SLOT(renameFile(const QString &, const QString &)));
}

//==============================================================================

CellmlFileManager::~CellmlFileManager()
{
    // Remove all the managed files

    foreach (CellmlFile *cellmlFile, mCellmlFiles)
        delete cellmlFile;
}

//==============================================================================

CellmlFileManager * CellmlFileManager::instance()
{
    // Return the 'global' instance of our CellML file manager class

    static CellmlFileManager instance;

    return static_cast<CellmlFileManager *>(Core::globalInstance("OpenCOR::CellMLSupport::CellmlFileManager",
                                                                 &instance));
}

//==============================================================================

CellmlFile * CellmlFileManager::cellmlFile(const QString &pFileName)
{
    // Return the CellmlFile object, if any, associated with our given file

    return mCellmlFiles.value(Core::nativeCanonicalFileName(pFileName));
}

//==============================================================================

void CellmlFileManager::manageFile(const QString &pFileName)
{
    QString nativeFileName = Core::nativeCanonicalFileName(pFileName);

    if (!cellmlFile(nativeFileName) && isCellmlFile(nativeFileName)) {
        // We are dealing with a CellML file, which is not already managed, so
        // we can add it to our list of managed CellML files

        mCellmlFiles.insert(nativeFileName, new CellmlFile(nativeFileName));
    }
}

//==============================================================================

void CellmlFileManager::unmanageFile(const QString &pFileName)
{
    CellmlFile *crtCellmlFile = cellmlFile(pFileName);

    if (crtCellmlFile) {
        // We are dealing with a CellML file, so we can remove it from our list
        // of managed CellML files after having deleted it

        delete crtCellmlFile;

        mCellmlFiles.remove(Core::nativeCanonicalFileName(pFileName));
    }
}

//==============================================================================

void CellmlFileManager::reloadFile(const QString &pFileName)
{
    // The file is to be reloaded, so reload it
    // Note: to reload a file here ensures that our different CellML-based views
    //       won't each do it, thus saving time and ensuring that a CellML-based
    //       view doesn't forget to do it...

    CellmlFile *crtCellmlFile = cellmlFile(pFileName);

    if (crtCellmlFile) {
        // The file is managed, but should it still be (i.e. can it still be
        // considered as being a CellML file)?

        if (isCellmlFile(pFileName))
            crtCellmlFile->reload();
        else
            unmanageFile(pFileName);
    } else {
        // The file is not managed, which means that previously it wasn't
        // considered as being a CellML file, but things may be different now,
        // so try to remanage it and load it, if possible

        manageFile(pFileName);

        crtCellmlFile = cellmlFile(pFileName);

        if (crtCellmlFile)
            crtCellmlFile->load();
    }
}

//==============================================================================

void CellmlFileManager::renameFile(const QString &pOldFileName,
                                   const QString &pNewFileName)
{
    // The file has been renamed, so we need to update our CellML files mapping,
    // if needed

    CellmlFile *crtCellmlFile = cellmlFile(pOldFileName);

    if (!crtCellmlFile)
        return;

    mCellmlFiles.insert(pNewFileName, crtCellmlFile);
    mCellmlFiles.remove(pOldFileName);

    // We also need to ensure that our CellML file object has its file name
    // updated

    crtCellmlFile->setFileName(pNewFileName);
}

//==============================================================================

}   // namespace CellMLSupport
}   // namespace OpenCOR

//==============================================================================
// End of file
//==============================================================================
<|endoftext|>