<commit_before>#include <dirent.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>

#include <qdir.h>
#include <qstring.h>

#include <kdebug.h>
#include <kmessagebox.h>
#include <klocale.h>
#include <kapp.h>
#include <kstddirs.h>

#include <kmailIface.h>

#include "kmkernel.h"
#include "kmmainwin.h"
#include "kmcomposewin.h"
#include "kmmessage.h"
#include "kmfoldermgr.h"
#include "kmfolder.h"
#include "kmfiltermgr.h"
#include "kmreaderwin.h"
#include "kmsender.h"
#include "kmundostack.h"
#include "kmidentity.h"
#include "kmacctmgr.h"
#include "kbusyptr.h"
#include "kmaddrbook.h"

#include <X11/Xlib.h>

KMKernel *KMKernel::mySelf = 0;

/********************************************************************/
/*                     Constructor and destructor                   */
/********************************************************************/
KMKernel::KMKernel (QObject *parent, const char *name) :
  QObject(parent, name),  DCOPObject("KMailIface")
{
  //debug ("KMKernel::KMKernel");
  mySelf = this;
}

KMKernel::~KMKernel ()
{
  mySelf = 0;
  debug ("KMKernel::~KMKernel");
}

/********************************************************************/
/*             DCOP-callable, and command line actions              */
/********************************************************************/
void KMKernel::checkMail () //might create a new reader but wont show!!
{
  debug ("KMKernel::checkMail called");
  KMMainWin *mWin = 0;

  if (kapp->mainWidget() && kapp->mainWidget()->isA("KMMainWin"))
    mWin = (KMMainWin *) kapp->mainWidget();
  else
    mWin = new KMMainWin;
  mWin->slotCheckMail();
}

void KMKernel::openReader( KURL /*messageFile*/)
{
#warning Ugly hack! (sven)
  KMMainWin *mWin = 0;
  KTMainWindow *ktmw = 0;
  debug ("KMKernel::openReader called");

  if (KTMainWindow::memberList)
    for (ktmw = KTMainWindow::memberList->first(); ktmw;
         ktmw = KTMainWindow::memberList->next())
      if (ktmw->isA("KMMainWin"))
        break;

  if (ktmw)
    mWin = (KMMainWin *) ktmw;
  else
    mWin = new KMMainWin;
  mWin->show();
  //and "Activate" by kwin?

  //if (!messageFile.isEmpty())
  //  mWin->viewMessage(messageFile);
}

int KMKernel::openComposer (QString to, QString cc,
                            QString bcc, QString subject, int hidden)
{
  debug ("KMKernel::openComposer called");

  KMMessage *msg = new KMMessage;
  msg->initHeader();
  if (!cc.isEmpty()) msg->setCc(cc);
  if (!bcc.isEmpty()) msg->setBcc(bcc);
  if (!subject.isEmpty()) msg->setSubject(subject);
  if (!to.isEmpty()) msg->setTo(to);

  KMComposeWin *cWin = new KMComposeWin(msg);
  if (hidden == 0)
    cWin->show();
  //return cWin->composerId()
  return 1;
}

int KMKernel::setBody (int /*composerId*/, QString /*body*/)
{
  debug ("KMKernel::setBody called");
  return 1;
}

int KMKernel::addAttachment(int /*composerId*/, KURL /*url*/,
                            QString /*comment*/)
{
  debug ("KMKernel::addAttachment called");
  return 1;
}

int KMKernel::send(int /*composerId*/, int /*when*/)
{
  debug ("KMKernel::send called");
  return 1;
}

int KMKernel::ready()
{
  debug ("KMKernel::ready called");
  return 1;
}

/********************************************************************/
/*                        Kernel methods                            */
/********************************************************************/

void KMKernel::quit()
{
  // Called when all windows are closed. Will take care of compacting,
  // sending... should handle session management too!!

  if (msgSender() && msgSender()->sending()) // sender working?
  {
    kernel->msgSender()->quitWhenFinished(); // tell him to quit app when finished
    return;                        // don't quit now
  }
  kapp->quit();                           // sender not working, quit
}
  /* TODO later:
   Asuming that:
     - msgsender is nonblocking
       (our own, QSocketNotifier based. Pops up errors and sends signal
        senderFinished when done)
     - compacting is non blocking (insert processEvents there)

   o If we are getting mail, stop it (but dont lose something!)
   o If we are sending mail, go on UNLESS this was called by SM,
       in which case stop ASAP that too (can we warn? should we continue
       on next start?)
   o If we are compacting, or expunging, go on UNLESS this was SM call.
       In that case stop compacting ASAP and continue on next start, before
       touching any folders.

   KMKernel::quit ()
   {
     SM call?
       if compacting, stop;
       if sending, stop;
       if receiving, stop;
       Windows will take care of themselves (composer should dump
        its messages, if any but not in deadMail)
       declare us ready for the End of the Session

     No, normal quit call
       All windows are off. Anything to do, should compact or sender sends?
         Yes, maybe put an icon in panel as a sign of life
         Folder manager, go compacting (*except* outbox and sent-mail!)
         if sender sending, connect us to his finished slot, declare us ready
                            for quit and wait for senderFinished
         if not, Folder manager, go compact sent-mail and outbox
}                (= call slotFinished())

void KMKernel::slotSenderFinished()
{
  good, Folder manager go compact sent-mail and outbox
  clean up stage1 (release folders and config, unregister from dcop)
    -- another kmail may start now ---
  kapp->quit();
}

void KMKernel::
void KMKernel::
*/

/********************************************************************/
/*            Init, Exit, and handler  methods                      */
/********************************************************************/
void KMKernel::testDir(const char *_name)
{
  DIR *dp;
  QString c = getenv("HOME");
  if(c.isEmpty())
  {
      KMessageBox::sorry(0, i18n("$HOME is not set!\n"
                                 "KMail cannot start without it.\n"));
      exit(-1);
  }

  c += _name;
  dp = opendir(c.data());
  if (dp == NULL) ::mkdir(c.data(), S_IRWXU);
  else closedir(dp);
}

//-----------------------------------------------------------------------------
// Open a composer for each message found in ~/dead.letter
//to control
void KMKernel::recoverDeadLetters(void)
{
  KMComposeWin* win;
  KMMessage* msg;
  QDir dir = QDir::home();
  QString fname = dir.path();
  int i, rc, num;

  if (!dir.exists("dead.letter")) return;
  fname += "/dead.letter";
  KMFolder folder(0, fname);

  folder.setAutoCreateIndex(FALSE);
  rc = folder.open();
  if (rc)
  {
    perror("cannot open file "+fname);
    return;
  }

  folder.quiet(TRUE);
  folder.open();

  num = folder.count();
  for (i=0; i<num; i++)
  {
    msg = folder.take(0);
    if (msg)
    {
      win = new KMComposeWin;
      win->setMsg(msg, FALSE);
      win->show();
    }
  }
  folder.close();
  unlink(fname);
}

void KMKernel::initFolders(KConfig* cfg)
{
  QString name;

  name = cfg->readEntry("inboxFolder");

  // Currently the folder manager cannot manage folders which are not
  // in the base folder directory.
  //if (name.isEmpty()) name = getenv("MAIL");

  if (name.isEmpty()) name = "inbox";

  the_inboxFolder  = (KMFolder*)the_folderMgr->findOrCreate(name);
  // inboxFolder->open();

  the_outboxFolder = the_folderMgr->findOrCreate(cfg->readEntry("outboxFolder", "outbox"));
  the_outboxFolder->setType("Out");
  the_outboxFolder->setWhoField("To");
  the_outboxFolder->setSystemFolder(TRUE);
  the_outboxFolder->open();

  the_sentFolder = the_folderMgr->findOrCreate(cfg->readEntry("sentFolder", "sent-mail"));
  the_sentFolder->setType("St");
  the_sentFolder->setWhoField("To");
  the_sentFolder->setSystemFolder(TRUE);
  the_sentFolder->open();

  the_trashFolder  = the_folderMgr->findOrCreate(cfg->readEntry("trashFolder", "trash"));
  the_trashFolder->setType("Tr");
  the_trashFolder->setSystemFolder(TRUE);
  the_trashFolder->open();

}

void KMKernel::init()
{
  debug ("entering KMKernel::init()");
  QCString  acctPath, foldersPath;
  KConfig* cfg;

  the_checkingMail = false;
  the_shuttingDown = false;
  the_server_is_ready = false;

  the_kbp = new KBusyPtr;
  cfg = kapp->config();
  //debug ("1");
  // Stefan: Yes, we really want this message handler. Without it,
  // kmail does not show vital warning() dialogs.
  //qInstallMsgHandler(&kmailMsgHandler);

  QDir dir;
  QString d = locateLocal("data", "kmail/");

  cfg->setGroup("General");
  the_firstStart = cfg->readBoolEntry("first-start", true);
  foldersPath = cfg->readEntry("folders", "");
  acctPath = cfg->readEntry("accounts", foldersPath + "/.kmail-accounts");

  if (foldersPath.isEmpty())
  {
    foldersPath = QDir::homeDirPath() + QString("/Mail");
    transferMail();
  }

  the_folderMgr = new KMFolderMgr(foldersPath);
  the_undoStack = new KMUndoStack(20);
  the_acctMgr   = new KMAcctMgr(acctPath);
  the_filterMgr = new KMFilterMgr;
  the_filterActionDict = new KMFilterActionDict;
  the_addrBook  = new KMAddrBook;

  initFolders(cfg);
  the_acctMgr->readConfig();
  the_filterMgr->readConfig();
  the_addrBook->readConfig();
  if(the_addrBook->load() == IO_FatalError)
  {
      KMessageBox::sorry(0, i18n("The addressbook could not be loaded."));
  }
  KMMessage::readConfig();
  the_msgSender = new KMSender;

  the_server_is_ready = true;

  // filterMgr->dump();
  debug ("exiting KMKernel::init()");
}

bool KMKernel::doSessionManagement()
{

  // Do session management
  if (kapp->isRestored()){
    int n = 1;
    while (KTMainWindow::canBeRestored(n)){
      //only restore main windows! (Matthias);
      if (KTMainWindow::classNameOfToplevel(n) == "KMMainWin")
        (new KMMainWin)->restore(n);
      n++;
    }
    return true; // we were restored by SM
  }
  return false;  // no, we were not restored
}

void KMKernel::cleanup(void)
{
  the_shuttingDown = TRUE;
  KConfig* config =  kapp->config();

  if (the_trashFolder) {
    the_trashFolder->close(TRUE);
    config->setGroup("General");
    if (config->readNumEntry("empty-trash-on-exit", 0))
      the_trashFolder->expunge();
  }

  if (the_folderMgr) {
    if (config->readNumEntry("compact-all-on-exit", 0))
      the_folderMgr->compactAll(); // I can compact for ages in peace now!
  }

  if (the_inboxFolder) the_inboxFolder->close(TRUE);
  if (the_outboxFolder) the_outboxFolder->close(TRUE);
  if (the_sentFolder) the_sentFolder->close(TRUE);

  if (the_msgSender) delete the_msgSender;
  if (the_addrBook) delete the_addrBook;
  if (the_filterMgr) delete the_filterMgr;
  if (the_acctMgr) delete the_acctMgr;
  if (the_folderMgr) delete the_folderMgr;
  if (the_kbp) delete the_kbp;

  //qInstallMsgHandler(oldMsgHandler);
  kapp->config()->sync();
  //--- Sven's save attachments to /tmp start ---
  //debug ("cleaned");
  QString cmd;
  // This is a dir with attachments and it is not critical if they are
  // left behind.
  if (!KMReaderWin::attachDir().isEmpty())
  {
    cmd.sprintf("rm -rf '%s'", (const char*)KMReaderWin::attachDir());
    system (cmd.data()); // delete your owns only
  }
  //--- Sven's save attachments to /tmp end ---
}

//Isnt this obsolete? (sven)
void KMKernel::transferMail(void)
{
  QDir dir = QDir::home();
  int rc;

  // Stefan: This function is for all the whiners who think that KMail is
  // broken because they cannot read mail with pine and do not
  // know how to fix this problem with a simple symbolic link  =;-)
  // Markus: lol ;-)
  if (!dir.cd("KMail")) return;

  rc = KMessageBox::questionYesNo(0,
         i18n(
	    "The directory ~/KMail exists. From now on, KMail uses the\n"
	    "directory ~/Mail for its messages.\n"
	    "KMail can move the contents of the directory ~/KMail into\n"
	    "~/Mail, but this will replace existing files with the same\n"
	    "name in the directory ~/Mail (e.g. inbox).\n\n"
	    "Shall KMail move the mail folders now ?"));

  if (rc == KMessageBox::No) return;

  dir.cd("/");  // otherwise we lock the directory
  testDir("/Mail");
  system("mv -f ~/KMail/* ~/Mail");
  system("mv -f ~/KMail/.??* ~/Mail");
  system("rmdir ~/KMail");
}

void KMKernel::ungrabPtrKb(void)
{
  if(!KTMainWindow::memberList) return;
  QWidget* widg = KTMainWindow::memberList->first();
  Display* dpy;

  if (!widg) return;
  dpy = widg->x11Display();
  XUngrabKeyboard(dpy, CurrentTime);
  XUngrabPointer(dpy, CurrentTime);
}

// Message handler
void KMKernel::kmailMsgHandler(QtMsgType aType, const char* aMsg)
{
  QString appName = kapp->caption();
  QString msg = aMsg;
  static int recurse=-1;

  recurse++;

  switch (aType)
  {
  case QtDebugMsg:
    kDebugInfo(0, msg);
    break;

  case QtWarningMsg:
    fprintf(stderr, "%s: %s\n", (const char*)kapp->name(), msg.data());
    kDebugInfo(0, msg);
    break;

  case QtFatalMsg:
    ungrabPtrKb();
    fprintf(stderr, appName+" "+i18n("fatal error")+": %s\n", msg.data());
    KMessageBox::error(0, aMsg);
    abort();
  }

  recurse--;
}
void KMKernel::dumpDeadLetters()
{
  QWidget *win;

  while (KTMainWindow::memberList->first() != 0)
  {
    win = KTMainWindow::memberList->take();
    if (win->inherits("KMComposeWin")) ((KMComposeWin*)win)->deadLetter();
    delete win;
  }
  cleanup();
  ::exit (1);
}

void KMKernel::action(bool mailto, bool check, QString to, QString cc,
                      QString bcc, QString subj, KURL messageFile)
{

  if (mailto)
    openComposer (to, cc, bcc, subj, 0);
  else
    openReader(messageFile);

  if (check)
    checkMail();
  //Anything else?
}

#include "kmkernel.moc"
<commit_msg>Need to create the undostack before the account manager. Otherwise when someone used KMail for the first time it would create folders in ~/Mail the when those folders were closed KMail would try to push the action onto the nonexistent undostack.<commit_after>#include <dirent.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>

#include <qdir.h>
#include <qstring.h>

#include <kdebug.h>
#include <kmessagebox.h>
#include <klocale.h>
#include <kapp.h>
#include <kstddirs.h>

#include <kmailIface.h>

#include "kmkernel.h"
#include "kmmainwin.h"
#include "kmcomposewin.h"
#include "kmmessage.h"
#include "kmfoldermgr.h"
#include "kmfolder.h"
#include "kmfiltermgr.h"
#include "kmreaderwin.h"
#include "kmsender.h"
#include "kmundostack.h"
#include "kmidentity.h"
#include "kmacctmgr.h"
#include "kbusyptr.h"
#include "kmaddrbook.h"

#include <X11/Xlib.h>

KMKernel *KMKernel::mySelf = 0;

/********************************************************************/
/*                     Constructor and destructor                   */
/********************************************************************/
KMKernel::KMKernel (QObject *parent, const char *name) :
  QObject(parent, name),  DCOPObject("KMailIface")
{
  //debug ("KMKernel::KMKernel");
  mySelf = this;
}

KMKernel::~KMKernel ()
{
  mySelf = 0;
  debug ("KMKernel::~KMKernel");
}

/********************************************************************/
/*             DCOP-callable, and command line actions              */
/********************************************************************/
void KMKernel::checkMail () //might create a new reader but wont show!!
{
  debug ("KMKernel::checkMail called");
  KMMainWin *mWin = 0;

  if (kapp->mainWidget() && kapp->mainWidget()->isA("KMMainWin"))
    mWin = (KMMainWin *) kapp->mainWidget();
  else
    mWin = new KMMainWin;
  mWin->slotCheckMail();
}

void KMKernel::openReader( KURL /*messageFile*/)
{
#warning Ugly hack! (sven)
  KMMainWin *mWin = 0;
  KTMainWindow *ktmw = 0;
  debug ("KMKernel::openReader called");

  if (KTMainWindow::memberList)
    for (ktmw = KTMainWindow::memberList->first(); ktmw;
         ktmw = KTMainWindow::memberList->next())
      if (ktmw->isA("KMMainWin"))
        break;

  if (ktmw)
    mWin = (KMMainWin *) ktmw;
  else
    mWin = new KMMainWin;
  mWin->show();
  //and "Activate" by kwin?

  //if (!messageFile.isEmpty())
  //  mWin->viewMessage(messageFile);
}

int KMKernel::openComposer (QString to, QString cc,
                            QString bcc, QString subject, int hidden)
{
  debug ("KMKernel::openComposer called");

  KMMessage *msg = new KMMessage;
  msg->initHeader();
  if (!cc.isEmpty()) msg->setCc(cc);
  if (!bcc.isEmpty()) msg->setBcc(bcc);
  if (!subject.isEmpty()) msg->setSubject(subject);
  if (!to.isEmpty()) msg->setTo(to);

  KMComposeWin *cWin = new KMComposeWin(msg);
  if (hidden == 0)
    cWin->show();
  //return cWin->composerId()
  return 1;
}

int KMKernel::setBody (int /*composerId*/, QString /*body*/)
{
  debug ("KMKernel::setBody called");
  return 1;
}

int KMKernel::addAttachment(int /*composerId*/, KURL /*url*/,
                            QString /*comment*/)
{
  debug ("KMKernel::addAttachment called");
  return 1;
}

int KMKernel::send(int /*composerId*/, int /*when*/)
{
  debug ("KMKernel::send called");
  return 1;
}

int KMKernel::ready()
{
  debug ("KMKernel::ready called");
  return 1;
}

/********************************************************************/
/*                        Kernel methods                            */
/********************************************************************/

void KMKernel::quit()
{
  // Called when all windows are closed. Will take care of compacting,
  // sending... should handle session management too!!

  if (msgSender() && msgSender()->sending()) // sender working?
  {
    kernel->msgSender()->quitWhenFinished(); // tell him to quit app when finished
    return;                        // don't quit now
  }
  kapp->quit();                           // sender not working, quit
}
  /* TODO later:
   Asuming that:
     - msgsender is nonblocking
       (our own, QSocketNotifier based. Pops up errors and sends signal
        senderFinished when done)
     - compacting is non blocking (insert processEvents there)

   o If we are getting mail, stop it (but dont lose something!)
   o If we are sending mail, go on UNLESS this was called by SM,
       in which case stop ASAP that too (can we warn? should we continue
       on next start?)
   o If we are compacting, or expunging, go on UNLESS this was SM call.
       In that case stop compacting ASAP and continue on next start, before
       touching any folders.

   KMKernel::quit ()
   {
     SM call?
       if compacting, stop;
       if sending, stop;
       if receiving, stop;
       Windows will take care of themselves (composer should dump
        its messages, if any but not in deadMail)
       declare us ready for the End of the Session

     No, normal quit call
       All windows are off. Anything to do, should compact or sender sends?
         Yes, maybe put an icon in panel as a sign of life
         Folder manager, go compacting (*except* outbox and sent-mail!)
         if sender sending, connect us to his finished slot, declare us ready
                            for quit and wait for senderFinished
         if not, Folder manager, go compact sent-mail and outbox
}                (= call slotFinished())

void KMKernel::slotSenderFinished()
{
  good, Folder manager go compact sent-mail and outbox
  clean up stage1 (release folders and config, unregister from dcop)
    -- another kmail may start now ---
  kapp->quit();
}

void KMKernel::
void KMKernel::
*/

/********************************************************************/
/*            Init, Exit, and handler  methods                      */
/********************************************************************/
void KMKernel::testDir(const char *_name)
{
  DIR *dp;
  QString c = getenv("HOME");
  if(c.isEmpty())
  {
      KMessageBox::sorry(0, i18n("$HOME is not set!\n"
                                 "KMail cannot start without it.\n"));
      exit(-1);
  }

  c += _name;
  dp = opendir(c.data());
  if (dp == NULL) ::mkdir(c.data(), S_IRWXU);
  else closedir(dp);
}

//-----------------------------------------------------------------------------
// Open a composer for each message found in ~/dead.letter
//to control
void KMKernel::recoverDeadLetters(void)
{
  KMComposeWin* win;
  KMMessage* msg;
  QDir dir = QDir::home();
  QString fname = dir.path();
  int i, rc, num;

  if (!dir.exists("dead.letter")) return;
  fname += "/dead.letter";
  KMFolder folder(0, fname);

  folder.setAutoCreateIndex(FALSE);
  rc = folder.open();
  if (rc)
  {
    perror("cannot open file "+fname);
    return;
  }

  folder.quiet(TRUE);
  folder.open();

  num = folder.count();
  for (i=0; i<num; i++)
  {
    msg = folder.take(0);
    if (msg)
    {
      win = new KMComposeWin;
      win->setMsg(msg, FALSE);
      win->show();
    }
  }
  folder.close();
  unlink(fname);
}

void KMKernel::initFolders(KConfig* cfg)
{
  QString name;

  name = cfg->readEntry("inboxFolder");

  // Currently the folder manager cannot manage folders which are not
  // in the base folder directory.
  //if (name.isEmpty()) name = getenv("MAIL");

  if (name.isEmpty()) name = "inbox";

  the_inboxFolder  = (KMFolder*)the_folderMgr->findOrCreate(name);
  // inboxFolder->open();

  the_outboxFolder = the_folderMgr->findOrCreate(cfg->readEntry("outboxFolder", "outbox"));
  the_outboxFolder->setType("Out");
  the_outboxFolder->setWhoField("To");
  the_outboxFolder->setSystemFolder(TRUE);
  the_outboxFolder->open();

  the_sentFolder = the_folderMgr->findOrCreate(cfg->readEntry("sentFolder", "sent-mail"));
  the_sentFolder->setType("St");
  the_sentFolder->setWhoField("To");
  the_sentFolder->setSystemFolder(TRUE);
  the_sentFolder->open();

  the_trashFolder  = the_folderMgr->findOrCreate(cfg->readEntry("trashFolder", "trash"));
  the_trashFolder->setType("Tr");
  the_trashFolder->setSystemFolder(TRUE);
  the_trashFolder->open();

}

void KMKernel::init()
{
  debug ("entering KMKernel::init()");
  QCString  acctPath, foldersPath;
  KConfig* cfg;

  the_checkingMail = false;
  the_shuttingDown = false;
  the_server_is_ready = false;

  the_kbp = new KBusyPtr;
  cfg = kapp->config();
  //debug ("1");
  // Stefan: Yes, we really want this message handler. Without it,
  // kmail does not show vital warning() dialogs.
  //qInstallMsgHandler(&kmailMsgHandler);

  QDir dir;
  QString d = locateLocal("data", "kmail/");

  cfg->setGroup("General");
  the_firstStart = cfg->readBoolEntry("first-start", true);
  foldersPath = cfg->readEntry("folders", "");
  acctPath = cfg->readEntry("accounts", foldersPath + "/.kmail-accounts");

  if (foldersPath.isEmpty())
  {
    foldersPath = QDir::homeDirPath() + QString("/Mail");
    transferMail();
  }

  the_undoStack = new KMUndoStack(20);
  the_folderMgr = new KMFolderMgr(foldersPath);
  the_acctMgr   = new KMAcctMgr(acctPath);
  the_filterMgr = new KMFilterMgr;
  the_filterActionDict = new KMFilterActionDict;
  the_addrBook  = new KMAddrBook;

  initFolders(cfg);
  the_acctMgr->readConfig();
  the_filterMgr->readConfig();
  the_addrBook->readConfig();
  if(the_addrBook->load() == IO_FatalError)
  {
      KMessageBox::sorry(0, i18n("The addressbook could not be loaded."));
  }
  KMMessage::readConfig();
  the_msgSender = new KMSender;

  the_server_is_ready = true;

  // filterMgr->dump();
  debug ("exiting KMKernel::init()");
}

bool KMKernel::doSessionManagement()
{

  // Do session management
  if (kapp->isRestored()){
    int n = 1;
    while (KTMainWindow::canBeRestored(n)){
      //only restore main windows! (Matthias);
      if (KTMainWindow::classNameOfToplevel(n) == "KMMainWin")
        (new KMMainWin)->restore(n);
      n++;
    }
    return true; // we were restored by SM
  }
  return false;  // no, we were not restored
}

void KMKernel::cleanup(void)
{
  the_shuttingDown = TRUE;
  KConfig* config =  kapp->config();

  if (the_trashFolder) {
    the_trashFolder->close(TRUE);
    config->setGroup("General");
    if (config->readNumEntry("empty-trash-on-exit", 0))
      the_trashFolder->expunge();
  }

  if (the_folderMgr) {
    if (config->readNumEntry("compact-all-on-exit", 0))
      the_folderMgr->compactAll(); // I can compact for ages in peace now!
  }

  if (the_inboxFolder) the_inboxFolder->close(TRUE);
  if (the_outboxFolder) the_outboxFolder->close(TRUE);
  if (the_sentFolder) the_sentFolder->close(TRUE);

  if (the_msgSender) delete the_msgSender;
  if (the_addrBook) delete the_addrBook;
  if (the_filterMgr) delete the_filterMgr;
  if (the_acctMgr) delete the_acctMgr;
  if (the_folderMgr) delete the_folderMgr;
  if (the_kbp) delete the_kbp;

  //qInstallMsgHandler(oldMsgHandler);
  kapp->config()->sync();
  //--- Sven's save attachments to /tmp start ---
  //debug ("cleaned");
  QString cmd;
  // This is a dir with attachments and it is not critical if they are
  // left behind.
  if (!KMReaderWin::attachDir().isEmpty())
  {
    cmd.sprintf("rm -rf '%s'", (const char*)KMReaderWin::attachDir());
    system (cmd.data()); // delete your owns only
  }
  //--- Sven's save attachments to /tmp end ---
}

//Isnt this obsolete? (sven)
void KMKernel::transferMail(void)
{
  QDir dir = QDir::home();
  int rc;

  // Stefan: This function is for all the whiners who think that KMail is
  // broken because they cannot read mail with pine and do not
  // know how to fix this problem with a simple symbolic link  =;-)
  // Markus: lol ;-)
  if (!dir.cd("KMail")) return;

  rc = KMessageBox::questionYesNo(0,
         i18n(
	    "The directory ~/KMail exists. From now on, KMail uses the\n"
	    "directory ~/Mail for its messages.\n"
	    "KMail can move the contents of the directory ~/KMail into\n"
	    "~/Mail, but this will replace existing files with the same\n"
	    "name in the directory ~/Mail (e.g. inbox).\n\n"
	    "Shall KMail move the mail folders now ?"));

  if (rc == KMessageBox::No) return;

  dir.cd("/");  // otherwise we lock the directory
  testDir("/Mail");
  system("mv -f ~/KMail/* ~/Mail");
  system("mv -f ~/KMail/.??* ~/Mail");
  system("rmdir ~/KMail");
}

void KMKernel::ungrabPtrKb(void)
{
  if(!KTMainWindow::memberList) return;
  QWidget* widg = KTMainWindow::memberList->first();
  Display* dpy;

  if (!widg) return;
  dpy = widg->x11Display();
  XUngrabKeyboard(dpy, CurrentTime);
  XUngrabPointer(dpy, CurrentTime);
}

// Message handler
void KMKernel::kmailMsgHandler(QtMsgType aType, const char* aMsg)
{
  QString appName = kapp->caption();
  QString msg = aMsg;
  static int recurse=-1;

  recurse++;

  switch (aType)
  {
  case QtDebugMsg:
    kDebugInfo(0, msg);
    break;

  case QtWarningMsg:
    fprintf(stderr, "%s: %s\n", (const char*)kapp->name(), msg.data());
    kDebugInfo(0, msg);
    break;

  case QtFatalMsg:
    ungrabPtrKb();
    fprintf(stderr, appName+" "+i18n("fatal error")+": %s\n", msg.data());
    KMessageBox::error(0, aMsg);
    abort();
  }

  recurse--;
}
void KMKernel::dumpDeadLetters()
{
  QWidget *win;

  while (KTMainWindow::memberList->first() != 0)
  {
    win = KTMainWindow::memberList->take();
    if (win->inherits("KMComposeWin")) ((KMComposeWin*)win)->deadLetter();
    delete win;
  }
  cleanup();
  ::exit (1);
}

void KMKernel::action(bool mailto, bool check, QString to, QString cc,
                      QString bcc, QString subj, KURL messageFile)
{

  if (mailto)
    openComposer (to, cc, bcc, subj, 0);
  else
    openReader(messageFile);

  if (check)
    checkMail();
  //Anything else?
}

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


<commit_before>/*
 *  dumbo_moveit_example.cpp
 *
 *  Created on: Nov 19, 2013
 *  Authors:   Francisco Viña
 *            fevb <at> kth.se
 */

/* Copyright (c) 2013, Francisco Viña, CVAP, KTH
   All rights reserved.

   Redistribution and use in source and binary forms, with or without
   modification, are permitted provided that the following conditions are met:
      * Redistributions of source code must retain the above copyright
        notice, this list of conditions and the following disclaimer.
      * Redistributions in binary form must reproduce the above copyright
        notice, this list of conditions and the following disclaimer in the
        documentation and/or other materials provided with the distribution.
      * Neither the name of KTH nor the
        names of its contributors may be used to endorse or promote products
        derived from this software without specific prior written permission.

   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
   ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
   WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
   DISCLAIMED. IN NO EVENT SHALL KTH BE LIABLE FOR ANY
   DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
   (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
   LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
   ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
   (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
   SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

#include <ros/ros.h>
#include <moveit/move_group_interface/move_group.h>

int main(int argc, char **argv)
{

	ros::init(argc, argv, "dumbo_move_group_example");

	ros::AsyncSpinner spinner(1);
	spinner.start();

	move_group_interface::MoveGroup l_group("left_arm");
	move_group_interface::MoveGroup r_group("right_arm");

	// set position and orientation of left_arm_7_link with respect to arm_base_link
	geometry_msgs::Pose p;

	p.position.x = -0.486;
	p.position.y = 0.367;
	p.position.z = 0.0;

	double roll = 1.571;
	double pitch = 1.571;
	double yaw = 3.13;
	tf::Quaternion q;
	q.setRPY(roll, pitch, yaw);
	tf::quaternionTFToMsg(q, p.orientation);

	l_group.setPoseTarget(p);
	l_group.setGoalPositionTolerance(0.1);
	l_group.setGoalOrientationTolerance(0.1);

	l_group.move();

	ros::Duration(3.0).sleep();

	l_group.setNamedTarget("l_default");
	r_group.setNamedTarget("r_default");

	l_group.move();

	r_group.move();

	ros::shutdown();
	return 0;

}
<commit_msg>fixed move group example, tested and working<commit_after>/*
 *  dumbo_moveit_example.cpp
 *
 *  Created on: Nov 19, 2013
 *  Authors:   Francisco Viña
 *            fevb <at> kth.se
 */

/* Copyright (c) 2013, Francisco Viña, CVAP, KTH
   All rights reserved.

   Redistribution and use in source and binary forms, with or without
   modification, are permitted provided that the following conditions are met:
      * Redistributions of source code must retain the above copyright
        notice, this list of conditions and the following disclaimer.
      * Redistributions in binary form must reproduce the above copyright
        notice, this list of conditions and the following disclaimer in the
        documentation and/or other materials provided with the distribution.
      * Neither the name of KTH nor the
        names of its contributors may be used to endorse or promote products
        derived from this software without specific prior written permission.

   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
   ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
   WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
   DISCLAIMED. IN NO EVENT SHALL KTH BE LIABLE FOR ANY
   DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
   (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
   LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
   ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
   (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
   SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

#include <ros/ros.h>
#include <moveit/move_group_interface/move_group.h>

int main(int argc, char **argv)
{

	ros::init(argc, argv, "dumbo_move_group_example");

	ros::AsyncSpinner spinner(1);
	spinner.start();

	move_group_interface::MoveGroup l_group("left_arm");
	move_group_interface::MoveGroup r_group("right_arm");

	// set position and orientation of left_arm_7_link with respect to arm_base_link
	geometry_msgs::Pose p;

	p.position.x = -0.486;
	p.position.y = 0.367;
	p.position.z = 0.0;

	double roll = 1.571;
	double pitch = 1.571;
	double yaw = 3.13;
	tf::Quaternion q;
	q.setRPY(roll, pitch, yaw);
	tf::quaternionTFToMsg(q, p.orientation);

	geometry_msgs::PoseStamped p_stamped;
	p_stamped.pose = p;
	p_stamped.header.frame_id = "arm_base_link";
	p_stamped.header.stamp = ros::Time::now();

	l_group.setPoseTarget(p_stamped);

	l_group.move();

	ros::Duration(3.0).sleep();

	l_group.setNamedTarget("l_default");
	r_group.setNamedTarget("r_default");

	l_group.move();

	r_group.move();

	ros::shutdown();
	return 0;

}
<|endoftext|>


<commit_before>#ifndef DUNE_STUFF_DISCRETEFUNCTION_PROJECTION_HETEROGENOUS_HH
#define DUNE_STUFF_DISCRETEFUNCTION_PROJECTION_HETEROGENOUS_HH

#include <dune/common/fvector.hh>
#include <dune/grid/common/backuprestore.hh>
#include <dune/grid/common/grid.hh>
#include <dune/grid/common/entity.hh>
#include <dune/stuff/common/ranges.hh>
#include <dune/stuff/aliases.hh>
#include <dune/stuff/fem/namespace.hh>

#ifdef HAVE_DUNE_FEM
  #include <dune/fem/function/common/discretefunction.hh>
  #include <dune/fem/quadrature/cachingquadrature.hh>
#endif

#include <dune/grid/io/file/vtk/function.hh>

#include <dune/stuff/grid/search.hh>

namespace Dune {
namespace Stuff {

#if 1 //def 1 // HAVE_DUNE_FEM
template< template< class > class SearchStrategy = Grid::EntityInlevelSearch >
class HeterogenousProjection
{
public:
  /** If your SearchStrategy only takes a leafview of the source grid, you may use this signature.
   * Otherwise you'll have to provide an instance of the SearchStrategy to the method below
   **/
  template < class SourceDFImp, class TargetDFImp >
  static void project(const Dune::Fem::DiscreteFunctionInterface<SourceDFImp>& source,
                      Dune::Fem::DiscreteFunctionInterface<TargetDFImp>& target)
  {
    SearchStrategy<typename SourceDFImp::GridType::LeafGridView> search(source.gridPart().grid().leafView());
    project(source, target, search);
  }

  //! signature for non-default SearchStrategy constructions
  template < class SourceDFImp, class TargetDFImp, class SearchStrategyImp >
  static void project(const Dune::Fem::DiscreteFunctionInterface<SourceDFImp>& source,
                      Dune::Fem::DiscreteFunctionInterface<TargetDFImp>& target,
                      SearchStrategyImp& search)
  {
    typedef typename TargetDFImp::DiscreteFunctionSpaceType TargetDiscreteFunctionSpaceType;
    typedef typename TargetDFImp::DofType TargetDofType;
    static const int target_dimRange = TargetDiscreteFunctionSpaceType::dimRange;

    const auto& space =  target.space();
    const auto infinity = DSC::numeric_limits< TargetDofType >::infinity();

    // set all DoFs to infinity
    const auto dend = target.dend();
    for( auto dit = target.dbegin(); dit != dend; ++dit )
      *dit = infinity;

    const auto endit = space.end();
    for(auto it = space.begin(); it != endit ; ++it)
    {
      const auto& target_entity = *it;
      const auto& target_geometry = target_entity.geometry();
      auto target_local_function = target.localFunction(target_entity);
      const auto& target_lagrangepoint_set = space.lagrangePointSet(target_entity);
      const auto quadNop = target_lagrangepoint_set.nop();

      typename TargetDiscreteFunctionSpaceType::RangeType source_value;

      std::vector<typename TargetDiscreteFunctionSpaceType::DomainType> global_quads(quadNop);
      for(size_t qP = 0; qP < quadNop ; ++qP) {
        global_quads[qP] = target_geometry.global(target_lagrangepoint_set.point(qP));
      }
      const auto evaluation_entity_ptrs = search(global_quads);
      assert(evaluation_entity_ptrs.size() >= global_quads.size());

      int k = 0;
      for(size_t qP = 0; qP < quadNop ; ++qP)
      {
        if(std::isinf(target_local_function[ k ]))
        {
          const auto& global_point = global_quads[qP];
          // evaluate source function
          const auto& source_entity_unique_ptr = evaluation_entity_ptrs[qP];
          if (source_entity_unique_ptr) {
            const auto& source_entity_ptr = (*source_entity_unique_ptr);
            const auto& source_geometry = source_entity_ptr->geometry();
            const auto& source_local_point = source_geometry.local(global_point);
            const auto& source_local_function = source.localFunction(*source_entity_ptr);
            source_local_function.evaluate(source_local_point, source_value);
            for(int i = 0; i < target_dimRange; ++i, ++k)
              target_local_function[k] = source_value[i];
          }
          else {
            for(int i = 0; i < target_dimRange; ++i, ++k)
              target_local_function[k] = TargetDofType(0);
          }
        }
        else
          k += target_dimRange;
      }
    }
  } // ... project(...)
}; // class HeterogenousProjection
#endif // HAVE_DUNE_FEM

} // namespace Stuff
} // namespace Dune

#endif // DUNE_STUFF_DISCRETEFUNCTION_PROJECTION_HETEROGENOUS_HH
<commit_msg>[df] made het. projection to work for FiniteVolume spaces too<commit_after>#ifndef DUNE_STUFF_DISCRETEFUNCTION_PROJECTION_HETEROGENOUS_HH
#define DUNE_STUFF_DISCRETEFUNCTION_PROJECTION_HETEROGENOUS_HH

#include <dune/common/fvector.hh>
#include <dune/grid/common/backuprestore.hh>
#include <dune/grid/common/grid.hh>
#include <dune/grid/common/entity.hh>
#include <dune/stuff/common/ranges.hh>
#include <dune/stuff/aliases.hh>
#include <dune/stuff/fem/namespace.hh>

#ifdef HAVE_DUNE_FEM
  #include <dune/fem/function/common/discretefunction.hh>
  #include <dune/fem/quadrature/cachingquadrature.hh>
  #include <dune/fem/space/finitevolume.hh>
  #include <dune/fem/space/lagrange.hh>
#endif

#include <dune/grid/io/file/vtk/function.hh>

#include <dune/stuff/grid/search.hh>

namespace Dune {
namespace Stuff {

#if HAVE_DUNE_FEM

template< class F, class G, int p, template< class > class S >
std::vector<typename Dune::Fem::LagrangeDiscreteFunctionSpace<F,G,p,S>::DomainType>
global_evaluation_points(const Dune::Fem::LagrangeDiscreteFunctionSpace<F,G,p,S>& space,
         const typename Dune::Fem::LagrangeDiscreteFunctionSpace<F,G,p,S>::EntityType& target_entity)
{
  const auto& target_lagrangepoint_set = space.lagrangePointSet(target_entity);
  const auto& target_geometry = target_entity.geometry();
  const auto quadNop = target_lagrangepoint_set.nop();
  std::vector<typename Dune::Fem::LagrangeDiscreteFunctionSpace<F,G,p,S>::DomainType> points(quadNop);
  for(size_t qP = 0; qP < quadNop ; ++qP) {
    points[qP] = target_geometry.global(target_lagrangepoint_set.point(qP));
  }
  return points;
}

template< class F, class G, int p, template< class > class S >
std::vector<typename Dune::Fem::FiniteVolumeSpace<F,G,p,S>::DomainType>
global_evaluation_points(const Dune::Fem::FiniteVolumeSpace<F,G,p,S>& /*space*/,
         const typename Dune::Fem::FiniteVolumeSpace<F,G,p,S>::EntityType& target_entity)
{
  assert(false);
  typedef std::vector<typename Dune::Fem::FiniteVolumeSpace<F,G,p,S>::DomainType> Ret;
  return Ret(1, target_entity.geometry().center());
}

template< template< class > class SearchStrategy = Grid::EntityInlevelSearch >
class HeterogenousProjection
{
public:
  /** If your SearchStrategy only takes a leafview of the source grid, you may use this signature.
   * Otherwise you'll have to provide an instance of the SearchStrategy to the method below
   **/
  template < class SourceDFImp, class TargetDFImp >
  static void project(const Dune::Fem::DiscreteFunctionInterface<SourceDFImp>& source,
                      Dune::Fem::DiscreteFunctionInterface<TargetDFImp>& target)
  {
    SearchStrategy<typename SourceDFImp::GridType::LeafGridView> search(source.gridPart().grid().leafView());
    project(source, target, search);
  }

  //! signature for non-default SearchStrategy constructions
  template < class SourceDFImp, class TargetDFImp, class SearchStrategyImp >
  static void project(const Dune::Fem::DiscreteFunctionInterface<SourceDFImp>& source,
                      Dune::Fem::DiscreteFunctionInterface<TargetDFImp>& target,
                      SearchStrategyImp& search)
  {
    typedef typename TargetDFImp::DiscreteFunctionSpaceType TargetDiscreteFunctionSpaceType;
    typedef typename TargetDFImp::DofType TargetDofType;
    static const int target_dimRange = TargetDiscreteFunctionSpaceType::dimRange;

    const auto& space =  target.space();
    const auto infinity = DSC::numeric_limits< TargetDofType >::infinity();

    // set all DoFs to infinity
    const auto dend = target.dend();
    for( auto dit = target.dbegin(); dit != dend; ++dit )
      *dit = infinity;

    const auto endit = space.end();
    for(auto it = space.begin(); it != endit ; ++it)
    {
      const auto& target_entity = *it;
      auto target_local_function = target.localFunction(target_entity);
      const auto global_quads = global_evaluation_points(space, target_entity);
      const auto evaluation_entity_ptrs = search(global_quads);
      assert(evaluation_entity_ptrs.size() >= global_quads.size());

      int k = 0;
      typename TargetDiscreteFunctionSpaceType::RangeType source_value;
      for(size_t qP = 0; qP < global_quads.size() ; ++qP)
      {
        if(std::isinf(target_local_function[ k ]))
        {
          const auto& source_entity_unique_ptr = evaluation_entity_ptrs[qP];
          if (source_entity_unique_ptr) {
            const auto& source_entity_ptr = (*source_entity_unique_ptr);
            const auto& source_geometry = source_entity_ptr->geometry();
            const auto& global_point = global_quads[qP];
            const auto& source_local_point = source_geometry.local(global_point);
            const auto& source_local_function = source.localFunction(*source_entity_ptr);
            source_local_function.evaluate(source_local_point, source_value);
            for(int i = 0; i < target_dimRange; ++i, ++k)
              target_local_function[k] = source_value[i];
          }
          else {
            for(int i = 0; i < target_dimRange; ++i, ++k)
              target_local_function[k] = TargetDofType(6);
          }
        }
        else
          k += target_dimRange;
      }
    }
  } // ... project(...)
}; // class HeterogenousProjection
#endif // HAVE_DUNE_FEM

} // namespace Stuff
} // namespace Dune

#endif // DUNE_STUFF_DISCRETEFUNCTION_PROJECTION_HETEROGENOUS_HH
<|endoftext|>


<commit_before>/*******************************************************************************
* Copyright 2018 ROBOTIS CO., LTD.
*
* 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.
*******************************************************************************/

/* Authors: Taehun Lim (Darby) */

#include <ros/ros.h>
#include <dynamixel_workbench_toolbox/dynamixel_workbench.h>

#define BAUDRATE_NUM 7

int main(int argc, char *argv[])
{
  std::string port_name = "/dev/ttyUSB0";

  if (argc < 2)
  {
    printf("Please set '-port_name'arguments for connected Dynamixels");
    return 0;
  }
  else
  {
    port_name = argv[1];
  }

  DynamixelWorkbench dxl_wb;

  const char *log;
  bool result = false;

  uint8_t scanned_id[100];
  uint8_t dxl_cnt = 0;

  uint32_t baudrate[BAUDRATE_NUM] = {9600, 57600, 115200, 1000000, 2000000, 3000000, 4000000};
  uint8_t range = 253;

  uint8_t index = 0;

  while (index < BAUDRATE_NUM)
  {
    result = dxl_wb.init(port_name.c_str(), baudrate[index], &log);
    if (result == false)
    {
      ROS_WARN("%s", log);
      ROS_WARN("Failed to init");
    }
    else
    {
      ROS_INFO("Succeed to init(%d)", baudrate[index]);
    }

    dxl_cnt = 0;
    for (uint8_t num = 0; num < 100; num++) scanned_id[num] = 0;

    ROS_INFO("Wait for scanning...");
    result = dxl_wb.scan(scanned_id, &dxl_cnt, range, &log);
    if (result == false)
    {
      ROS_WARN("%s", log);
      ROS_WARN("Failed to scan");
    }
    else
    {
      ROS_INFO("Find %d Dynamixels", dxl_cnt);

      for (int cnt = 0; cnt < dxl_cnt; cnt++)
        ROS_INFO("id : %d, model name : %s", scanned_id[cnt], dxl_wb.getModelName(scanned_id[cnt]));
    }

    index++;
  }

  return 0;
}
<commit_msg>update<commit_after>/*******************************************************************************
* Copyright 2018 ROBOTIS CO., LTD.
*
* 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.
*******************************************************************************/

/* Authors: Taehun Lim (Darby) */

#include <ros/ros.h>
#include <dynamixel_workbench_toolbox/dynamixel_workbench.h>

#define BAUDRATE_NUM 7

int main(int argc, char *argv[])
{
  std::string port_name = "/dev/ttyUSB0";

  if (argc < 2)
  {
    printf("Please set '-port_name'arguments for connected Dynamixels\n");
    return 0;
  }
  else
  {
    port_name = argv[1];
  }

  DynamixelWorkbench dxl_wb;

  const char *log;
  bool result = false;

  uint8_t scanned_id[100];
  uint8_t dxl_cnt = 0;

  uint32_t baudrate[BAUDRATE_NUM] = {9600, 57600, 115200, 1000000, 2000000, 3000000, 4000000};
  uint8_t range = 253;

  uint8_t index = 0;

  while (index < BAUDRATE_NUM)
  {
    result = dxl_wb.init(port_name.c_str(), baudrate[index], &log);
    if (result == false)
    {
      ROS_WARN("%s", log);
      ROS_WARN("Failed to init");
    }
    else
    {
      ROS_INFO("Succeed to init(%d)", baudrate[index]);
    }

    dxl_cnt = 0;
    for (uint8_t num = 0; num < 100; num++) scanned_id[num] = 0;

    ROS_INFO("Wait for scanning...");
    result = dxl_wb.scan(scanned_id, &dxl_cnt, range, &log);
    if (result == false)
    {
      ROS_WARN("%s", log);
      ROS_WARN("Failed to scan");
    }
    else
    {
      ROS_INFO("Find %d Dynamixels", dxl_cnt);

      for (int cnt = 0; cnt < dxl_cnt; cnt++)
        ROS_INFO("id : %d, model name : %s", scanned_id[cnt], dxl_wb.getModelName(scanned_id[cnt]));
    }

    index++;
  }

  return 0;
}
<|endoftext|>


<commit_before>
#include "CGamePad.h"

#include <windows.h>
#include <xinput.h>

static HMODULE hXInputModule = 0;
typedef DWORD (WINAPI *PFn_XInputGetState)(DWORD dwUserIndex, XINPUT_STATE* pState);
static PFn_XInputGetState pXInputGetState = 0;

vec2f const & CGamePad::GetLeftStick() const
{
	return LeftStick;
}

vec2f const & CGamePad::GetRightStick() const
{
	return RightStick;
}

f32 CGamePad::GetLeftTrigger() const
{
	return LeftTrigger;
}

f32 CGamePad::GetRightTrigger() const
{
	return RightTrigger;
}

bool CGamePad::IsButtonPressed(EGamePadButton const Button)
{
	return ButtonPressed[(int) Button];
}

static inline f32 GamepadStick(s16 in)
{
	f32 v;
	if (abs(in) < 9000)
		return 0;
	else if (in > 9000)
		v = in - 9000.f;
	else
		v = in + 9000.f;
	return v / (32767 - 9000);
}

static inline f32 GamepadTrigger(u8 in)
{
	if (in < 30)
		return 0;
	else
		return (in - 30) / 225.f;
}

void CGamePad::UpdateState()
{
	if (pXInputGetState)
	{
		XINPUT_STATE XInputState;

		if (pXInputGetState(0, & XInputState))
			return;

		LeftTrigger = GamepadTrigger(XInputState.Gamepad.bLeftTrigger);
		RightTrigger = GamepadTrigger(XInputState.Gamepad.bRightTrigger);
		LeftStick.X = GamepadStick(XInputState.Gamepad.sThumbLX);
		LeftStick.Y = GamepadStick(XInputState.Gamepad.sThumbLY);
		RightStick.X = GamepadStick(XInputState.Gamepad.sThumbRX);
		RightStick.Y = GamepadStick(XInputState.Gamepad.sThumbRY);

		ButtonPressed[(int) EGamePadButton::A] = (XInputState.Gamepad.wButtons & VK_PAD_A) != 0;
		ButtonPressed[(int) EGamePadButton::B] = (XInputState.Gamepad.wButtons & VK_PAD_B) != 0;
		ButtonPressed[(int) EGamePadButton::X] = (XInputState.Gamepad.wButtons & VK_PAD_X) != 0;
		ButtonPressed[(int) EGamePadButton::Y] = (XInputState.Gamepad.wButtons & VK_PAD_Y) != 0;
		ButtonPressed[(int) EGamePadButton::LeftShoulder] = (XInputState.Gamepad.wButtons & VK_PAD_RSHOULDER) != 0;
		ButtonPressed[(int) EGamePadButton::RightShoulder] = (XInputState.Gamepad.wButtons & VK_PAD_LSHOULDER) != 0;
		ButtonPressed[(int) EGamePadButton::DPadUp] = (XInputState.Gamepad.wButtons & VK_PAD_DPAD_UP) != 0;
		ButtonPressed[(int) EGamePadButton::DPadDown] = (XInputState.Gamepad.wButtons & VK_PAD_DPAD_DOWN) != 0;
		ButtonPressed[(int) EGamePadButton::DPadLeft] = (XInputState.Gamepad.wButtons & VK_PAD_DPAD_LEFT) != 0;
		ButtonPressed[(int) EGamePadButton::DPadRight] = (XInputState.Gamepad.wButtons & VK_PAD_DPAD_RIGHT) != 0;
		ButtonPressed[(int) EGamePadButton::Start] = (XInputState.Gamepad.wButtons & VK_PAD_START) != 0;
		ButtonPressed[(int) EGamePadButton::Back] = (XInputState.Gamepad.wButtons & VK_PAD_BACK) != 0;
		ButtonPressed[(int) EGamePadButton::LeftThumb] = (XInputState.Gamepad.wButtons & VK_PAD_LTHUMB_PRESS) != 0;
		ButtonPressed[(int) EGamePadButton::RightThumb] = (XInputState.Gamepad.wButtons & VK_PAD_RTHUMB_PRESS) != 0;
	}
}

CGamePad::CGamePad()
{
	if (! hXInputModule)
		hXInputModule = ::LoadLibraryA("Xinput9_1_0.dll");

	if (! pXInputGetState && hXInputModule)
		pXInputGetState = (PFn_XInputGetState) ::GetProcAddress(hXInputModule, "XInputGetState");
}
<commit_msg>+ Fixed game pad initialization<commit_after>
#include "CGamePad.h"

#include <windows.h>
#include <xinput.h>

static HMODULE hXInputModule = 0;
typedef DWORD (WINAPI *PFn_XInputGetState)(DWORD dwUserIndex, XINPUT_STATE* pState);
static PFn_XInputGetState pXInputGetState = 0;

vec2f const & CGamePad::GetLeftStick() const
{
	return LeftStick;
}

vec2f const & CGamePad::GetRightStick() const
{
	return RightStick;
}

f32 CGamePad::GetLeftTrigger() const
{
	return LeftTrigger;
}

f32 CGamePad::GetRightTrigger() const
{
	return RightTrigger;
}

bool CGamePad::IsButtonPressed(EGamePadButton const Button)
{
	return ButtonPressed[(int) Button];
}

static inline f32 GamepadStick(s16 in)
{
	f32 v;
	if (abs(in) < 9000)
		return 0;
	else if (in > 9000)
		v = in - 9000.f;
	else
		v = in + 9000.f;
	return v / (32767 - 9000);
}

static inline f32 GamepadTrigger(u8 in)
{
	if (in < 30)
		return 0;
	else
		return (in - 30) / 225.f;
}

void CGamePad::UpdateState()
{
	if (pXInputGetState)
	{
		XINPUT_STATE XInputState;

		if (pXInputGetState(0, & XInputState))
			return;

		LeftTrigger = GamepadTrigger(XInputState.Gamepad.bLeftTrigger);
		RightTrigger = GamepadTrigger(XInputState.Gamepad.bRightTrigger);
		LeftStick.X = GamepadStick(XInputState.Gamepad.sThumbLX);
		LeftStick.Y = GamepadStick(XInputState.Gamepad.sThumbLY);
		RightStick.X = GamepadStick(XInputState.Gamepad.sThumbRX);
		RightStick.Y = GamepadStick(XInputState.Gamepad.sThumbRY);

		ButtonPressed[(int) EGamePadButton::A] = (XInputState.Gamepad.wButtons & VK_PAD_A) != 0;
		ButtonPressed[(int) EGamePadButton::B] = (XInputState.Gamepad.wButtons & VK_PAD_B) != 0;
		ButtonPressed[(int) EGamePadButton::X] = (XInputState.Gamepad.wButtons & VK_PAD_X) != 0;
		ButtonPressed[(int) EGamePadButton::Y] = (XInputState.Gamepad.wButtons & VK_PAD_Y) != 0;
		ButtonPressed[(int) EGamePadButton::LeftShoulder] = (XInputState.Gamepad.wButtons & VK_PAD_RSHOULDER) != 0;
		ButtonPressed[(int) EGamePadButton::RightShoulder] = (XInputState.Gamepad.wButtons & VK_PAD_LSHOULDER) != 0;
		ButtonPressed[(int) EGamePadButton::DPadUp] = (XInputState.Gamepad.wButtons & VK_PAD_DPAD_UP) != 0;
		ButtonPressed[(int) EGamePadButton::DPadDown] = (XInputState.Gamepad.wButtons & VK_PAD_DPAD_DOWN) != 0;
		ButtonPressed[(int) EGamePadButton::DPadLeft] = (XInputState.Gamepad.wButtons & VK_PAD_DPAD_LEFT) != 0;
		ButtonPressed[(int) EGamePadButton::DPadRight] = (XInputState.Gamepad.wButtons & VK_PAD_DPAD_RIGHT) != 0;
		ButtonPressed[(int) EGamePadButton::Start] = (XInputState.Gamepad.wButtons & VK_PAD_START) != 0;
		ButtonPressed[(int) EGamePadButton::Back] = (XInputState.Gamepad.wButtons & VK_PAD_BACK) != 0;
		ButtonPressed[(int) EGamePadButton::LeftThumb] = (XInputState.Gamepad.wButtons & VK_PAD_LTHUMB_PRESS) != 0;
		ButtonPressed[(int) EGamePadButton::RightThumb] = (XInputState.Gamepad.wButtons & VK_PAD_RTHUMB_PRESS) != 0;
	}
}

CGamePad::CGamePad()
	: LeftTrigger(0), RightTrigger(0)
{
	if (! hXInputModule)
		hXInputModule = ::LoadLibraryA("Xinput9_1_0.dll");

	if (! pXInputGetState && hXInputModule)
		pXInputGetState = (PFn_XInputGetState) ::GetProcAddress(hXInputModule, "XInputGetState");

	for (int i = 0; i < (int) EGamePadButton::Count; ++ i)
		ButtonPressed[i] = false;
}
<|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the test suite of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial Usage
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QDebug>
#include <QHostInfo>
#include <QStringList>
#include <QString>

#include <qtest.h>
#include <qtesteventloop.h>

class tst_qhostinfo : public QObject
{
    Q_OBJECT
private slots:
    void lookupSpeed();
};

class SignalReceiver : public QObject
{
    Q_OBJECT
public:
    SignalReceiver(int nrc) : receiveCount(0), neededReceiveCount(nrc) {};
    int receiveCount;
    int neededReceiveCount;
public slots:
    void resultsReady(const QHostInfo) {
        receiveCount++;
        if (receiveCount == neededReceiveCount)
            QTestEventLoop::instance().exitLoop();
    }
};

void tst_qhostinfo::lookupSpeed()
{
    QStringList hostnameList;
    hostnameList << "www.ovi.com" << "www.nokia.com" << "qt.nokia.com" << "www.trolltech.com" << "troll.no"
            << "www.qtcentre.org" << "forum.nokia.com" << "www.forum.nokia.com" << "wiki.forum.nokia.com"
            << "www.nokia.no" << "nokia.de" << "127.0.0.1" << "----";
    // also add some duplicates:
    hostnameList << "www.nokia.com" << "127.0.0.1" << "www.trolltech.com";
    const int COUNT = hostnameList.size();

    SignalReceiver receiver(COUNT);

    QBENCHMARK {
        for (int i = 0; i < hostnameList.size(); i++)
            QHostInfo::lookupHost(hostnameList.at(i), &receiver, SLOT(resultsReady(const QHostInfo)));
        QTestEventLoop::instance().enterLoop(20);
        QVERIFY(!QTestEventLoop::instance().timeout());
    }
}

QTEST_MAIN(tst_qhostinfo)

#include "main.moc"
<commit_msg>tst_qhostinfo benchmark: Fix license header<commit_after>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the test suite of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include <QDebug>
#include <QHostInfo>
#include <QStringList>
#include <QString>

#include <qtest.h>
#include <qtesteventloop.h>

class tst_qhostinfo : public QObject
{
    Q_OBJECT
private slots:
    void lookupSpeed();
};

class SignalReceiver : public QObject
{
    Q_OBJECT
public:
    SignalReceiver(int nrc) : receiveCount(0), neededReceiveCount(nrc) {};
    int receiveCount;
    int neededReceiveCount;
public slots:
    void resultsReady(const QHostInfo) {
        receiveCount++;
        if (receiveCount == neededReceiveCount)
            QTestEventLoop::instance().exitLoop();
    }
};

void tst_qhostinfo::lookupSpeed()
{
    QStringList hostnameList;
    hostnameList << "www.ovi.com" << "www.nokia.com" << "qt.nokia.com" << "www.trolltech.com" << "troll.no"
            << "www.qtcentre.org" << "forum.nokia.com" << "www.forum.nokia.com" << "wiki.forum.nokia.com"
            << "www.nokia.no" << "nokia.de" << "127.0.0.1" << "----";
    // also add some duplicates:
    hostnameList << "www.nokia.com" << "127.0.0.1" << "www.trolltech.com";
    const int COUNT = hostnameList.size();

    SignalReceiver receiver(COUNT);

    QBENCHMARK {
        for (int i = 0; i < hostnameList.size(); i++)
            QHostInfo::lookupHost(hostnameList.at(i), &receiver, SLOT(resultsReady(const QHostInfo)));
        QTestEventLoop::instance().enterLoop(20);
        QVERIFY(!QTestEventLoop::instance().timeout());
    }
}

QTEST_MAIN(tst_qhostinfo)

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


<commit_before>// Copyright (c) 2012, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

#include "platform/assert.h"
#include "vm/class_finalizer.h"
#include "vm/compiler.h"
#include "vm/object.h"
#include "vm/pages.h"
#include "vm/stack_frame.h"
#include "vm/symbols.h"
#include "vm/unit_test.h"

namespace dart {

TEST_CASE(FindCodeObject) {
#if defined(TARGET_ARCH_IA32) || defined(TARGET_ARCH_X64)
  const int kLoopCount = 50000;
#else
  const int kLoopCount = 25000;
#endif
  const int kScriptSize = 512 * KB;
  const int kNumFunctions = 1024;
  char scriptChars[kScriptSize];
  String& url = String::Handle(String::New("dart-test:FindCodeObject"));
  String& source = String::Handle();
  Script& script = Script::Handle();
  Library& lib = Library::Handle();
  Class& clsA = Class::Handle();
  Class& clsB = Class::Handle();
  String& function_name = String::Handle();
  Function& function = Function::Handle();
  char buffer[256];

  // Get access to the code index table.
  Isolate* isolate = Isolate::Current();
  ASSERT(isolate != NULL);

  lib = Library::CoreLibrary();

  // Load up class A with 1024 functions.
  int written = OS::SNPrint(scriptChars, kScriptSize, "class A {");
  for (int i = 0; i < kNumFunctions; i++) {
    OS::SNPrint(buffer,
                256,
                "static foo%d([int i=1,int j=2,int k=3]){return i+j+k;}", i);
    written += OS::SNPrint((scriptChars + written),
                           (kScriptSize - written),
                           "%s",
                           buffer);
  }
  OS::SNPrint((scriptChars + written), (kScriptSize - written), "}");
  source = String::New(scriptChars);
  script = Script::New(url, source, RawScript::kScriptTag);
  EXPECT(CompilerTest::TestCompileScript(lib, script));
  clsA = lib.LookupClass(String::Handle(Symbols::New("A")));
  EXPECT(!clsA.IsNull());
  ClassFinalizer::FinalizeTypeHierarchy();
  for (int i = 0; i < kNumFunctions; i++) {
    OS::SNPrint(buffer, 256, "foo%d", i);
    function_name = String::New(buffer);
    function = clsA.LookupStaticFunction(function_name);
    EXPECT(!function.IsNull());
    EXPECT(CompilerTest::TestCompileFunction(function));
    EXPECT(function.HasCode());
  }

  // Now load up class B with 1024 functions.
  written = OS::SNPrint(scriptChars, kScriptSize, "class B {");
  // Create one large function.
  OS::SNPrint(buffer, sizeof(buffer), "static moo0([var i=1]) { ");
  written += OS::SNPrint((scriptChars + written),
                         (kScriptSize - written),
                         "%s",
                         buffer);
  // Generate a large function so that the code for this function when
  // compiled will reside in a large page.
  for (int i = 0; i < kLoopCount; i++) {
    OS::SNPrint(buffer, sizeof(buffer), "i = i+i;");
    written += OS::SNPrint((scriptChars + written),
                           (kScriptSize - written),
                           "%s",
                           buffer);
  }
  OS::SNPrint(buffer, sizeof(buffer), "return i; }");
  written += OS::SNPrint((scriptChars + written),
                         (kScriptSize - written),
                         "%s",
                         buffer);
  for (int i = 1; i < kNumFunctions; i++) {
    OS::SNPrint(buffer,
                256,
                "static moo%d([int i=1,int j=2,int k=3]){return i+j+k;}", i);
    written += OS::SNPrint((scriptChars + written),
                           (kScriptSize - written),
                           "%s",
                           buffer);
  }
  OS::SNPrint((scriptChars + written), (kScriptSize - written), "}");
  url = String::New("dart-test:FindCodeObject");
  source = String::New(scriptChars);
  script = Script::New(url, source, RawScript::kScriptTag);
  EXPECT(CompilerTest::TestCompileScript(lib, script));
  clsB = lib.LookupClass(String::Handle(Symbols::New("B")));
  EXPECT(!clsB.IsNull());
  ClassFinalizer::FinalizeTypeHierarchy();
  for (int i = 0; i < kNumFunctions; i++) {
    OS::SNPrint(buffer, 256, "moo%d", i);
    function_name = String::New(buffer);
    function = clsB.LookupStaticFunction(function_name);
    EXPECT(!function.IsNull());
    EXPECT(CompilerTest::TestCompileFunction(function));
    EXPECT(function.HasCode());
  }

  // Now try and access these functions using the code index table.
  Code& code = Code::Handle();
  uword pc;
  OS::SNPrint(buffer, 256, "foo%d", 123);
  function_name = String::New(buffer);
  function = clsA.LookupStaticFunction(function_name);
  EXPECT(!function.IsNull());
  code = function.CurrentCode();
  EXPECT(code.Size() > 16);
  pc = code.EntryPoint() + 16;
  EXPECT(Code::LookupCode(pc) == code.raw());

  OS::SNPrint(buffer, 256, "moo%d", 54);
  function_name = String::New(buffer);
  function = clsB.LookupStaticFunction(function_name);
  EXPECT(!function.IsNull());
  code = function.CurrentCode();
  EXPECT(code.Size() > 16);
  pc = code.EntryPoint() + 16;
  EXPECT(Code::LookupCode(pc) == code.raw());

  // Lookup the large function
  OS::SNPrint(buffer, 256, "moo%d", 0);
  function_name = String::New(buffer);
  function = clsB.LookupStaticFunction(function_name);
  EXPECT(!function.IsNull());
  code = function.CurrentCode();
  EXPECT(code.Size() > 16);
  pc = code.EntryPoint() + 16;
#if defined(TARGET_ARCH_MIPS)
  // MIPS can only Branch +/- 128KB
  EXPECT(code.Size() > ((PageSpace::kPageSizeInWords << kWordSizeLog2) / 2));
  EXPECT(Code::LookupCode(pc) == code.raw());
  pc = code.EntryPoint() + ((PageSpace::kPageSizeInWords << kWordSizeLog2) / 4);
  EXPECT(Code::LookupCode(pc) == code.raw());
#else
  EXPECT(code.Size() > (PageSpace::kPageSizeInWords << kWordSizeLog2));
  EXPECT(Code::LookupCode(pc) == code.raw());
  EXPECT(code.Size() > (1 * MB));
  pc = code.EntryPoint() + (1 * MB);
  EXPECT(Code::LookupCode(pc) == code.raw());
#endif  // defined(TARGET_ARCH_MIPS)
}

}  // namespace dart
<commit_msg>Removes obsolete MIPS ifdef from FindCodeObject test.<commit_after>// Copyright (c) 2012, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

#include "platform/assert.h"
#include "vm/class_finalizer.h"
#include "vm/compiler.h"
#include "vm/object.h"
#include "vm/pages.h"
#include "vm/stack_frame.h"
#include "vm/symbols.h"
#include "vm/unit_test.h"

namespace dart {

TEST_CASE(FindCodeObject) {
#if defined(TARGET_ARCH_IA32) || defined(TARGET_ARCH_X64)
  const int kLoopCount = 50000;
#else
  const int kLoopCount = 25000;
#endif
  const int kScriptSize = 512 * KB;
  const int kNumFunctions = 1024;
  char scriptChars[kScriptSize];
  String& url = String::Handle(String::New("dart-test:FindCodeObject"));
  String& source = String::Handle();
  Script& script = Script::Handle();
  Library& lib = Library::Handle();
  Class& clsA = Class::Handle();
  Class& clsB = Class::Handle();
  String& function_name = String::Handle();
  Function& function = Function::Handle();
  char buffer[256];

  // Get access to the code index table.
  Isolate* isolate = Isolate::Current();
  ASSERT(isolate != NULL);

  lib = Library::CoreLibrary();

  // Load up class A with 1024 functions.
  int written = OS::SNPrint(scriptChars, kScriptSize, "class A {");
  for (int i = 0; i < kNumFunctions; i++) {
    OS::SNPrint(buffer,
                256,
                "static foo%d([int i=1,int j=2,int k=3]){return i+j+k;}", i);
    written += OS::SNPrint((scriptChars + written),
                           (kScriptSize - written),
                           "%s",
                           buffer);
  }
  OS::SNPrint((scriptChars + written), (kScriptSize - written), "}");
  source = String::New(scriptChars);
  script = Script::New(url, source, RawScript::kScriptTag);
  EXPECT(CompilerTest::TestCompileScript(lib, script));
  clsA = lib.LookupClass(String::Handle(Symbols::New("A")));
  EXPECT(!clsA.IsNull());
  ClassFinalizer::FinalizeTypeHierarchy();
  for (int i = 0; i < kNumFunctions; i++) {
    OS::SNPrint(buffer, 256, "foo%d", i);
    function_name = String::New(buffer);
    function = clsA.LookupStaticFunction(function_name);
    EXPECT(!function.IsNull());
    EXPECT(CompilerTest::TestCompileFunction(function));
    EXPECT(function.HasCode());
  }

  // Now load up class B with 1024 functions.
  written = OS::SNPrint(scriptChars, kScriptSize, "class B {");
  // Create one large function.
  OS::SNPrint(buffer, sizeof(buffer), "static moo0([var i=1]) { ");
  written += OS::SNPrint((scriptChars + written),
                         (kScriptSize - written),
                         "%s",
                         buffer);
  // Generate a large function so that the code for this function when
  // compiled will reside in a large page.
  for (int i = 0; i < kLoopCount; i++) {
    OS::SNPrint(buffer, sizeof(buffer), "i = i+i;");
    written += OS::SNPrint((scriptChars + written),
                           (kScriptSize - written),
                           "%s",
                           buffer);
  }
  OS::SNPrint(buffer, sizeof(buffer), "return i; }");
  written += OS::SNPrint((scriptChars + written),
                         (kScriptSize - written),
                         "%s",
                         buffer);
  for (int i = 1; i < kNumFunctions; i++) {
    OS::SNPrint(buffer,
                256,
                "static moo%d([int i=1,int j=2,int k=3]){return i+j+k;}", i);
    written += OS::SNPrint((scriptChars + written),
                           (kScriptSize - written),
                           "%s",
                           buffer);
  }
  OS::SNPrint((scriptChars + written), (kScriptSize - written), "}");
  url = String::New("dart-test:FindCodeObject");
  source = String::New(scriptChars);
  script = Script::New(url, source, RawScript::kScriptTag);
  EXPECT(CompilerTest::TestCompileScript(lib, script));
  clsB = lib.LookupClass(String::Handle(Symbols::New("B")));
  EXPECT(!clsB.IsNull());
  ClassFinalizer::FinalizeTypeHierarchy();
  for (int i = 0; i < kNumFunctions; i++) {
    OS::SNPrint(buffer, 256, "moo%d", i);
    function_name = String::New(buffer);
    function = clsB.LookupStaticFunction(function_name);
    EXPECT(!function.IsNull());
    EXPECT(CompilerTest::TestCompileFunction(function));
    EXPECT(function.HasCode());
  }

  // Now try and access these functions using the code index table.
  Code& code = Code::Handle();
  uword pc;
  OS::SNPrint(buffer, 256, "foo%d", 123);
  function_name = String::New(buffer);
  function = clsA.LookupStaticFunction(function_name);
  EXPECT(!function.IsNull());
  code = function.CurrentCode();
  EXPECT(code.Size() > 16);
  pc = code.EntryPoint() + 16;
  EXPECT(Code::LookupCode(pc) == code.raw());

  OS::SNPrint(buffer, 256, "moo%d", 54);
  function_name = String::New(buffer);
  function = clsB.LookupStaticFunction(function_name);
  EXPECT(!function.IsNull());
  code = function.CurrentCode();
  EXPECT(code.Size() > 16);
  pc = code.EntryPoint() + 16;
  EXPECT(Code::LookupCode(pc) == code.raw());

  // Lookup the large function
  OS::SNPrint(buffer, 256, "moo%d", 0);
  function_name = String::New(buffer);
  function = clsB.LookupStaticFunction(function_name);
  EXPECT(!function.IsNull());
  code = function.CurrentCode();
  EXPECT(code.Size() > 16);
  pc = code.EntryPoint() + 16;
  EXPECT(code.Size() > (PageSpace::kPageSizeInWords << kWordSizeLog2));
  EXPECT(Code::LookupCode(pc) == code.raw());
  EXPECT(code.Size() > (1 * MB));
  pc = code.EntryPoint() + (1 * MB);
  EXPECT(Code::LookupCode(pc) == code.raw());
}

}  // namespace dart
<|endoftext|>


<commit_before>// Copyright (c) 2015 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.

#include "atom/browser/net/js_asker.h"

#include <vector>

#include "atom/common/native_mate_converters/callback.h"
#include "atom/common/native_mate_converters/v8_value_converter.h"
#include "native_mate/function_template.h"

namespace atom {

namespace internal {

namespace {

struct CallbackHolder {
  ResponseCallback callback;
};

// Cached JavaScript version of |HandlerCallback|.
v8::Persistent<v8::FunctionTemplate> g_handler_callback_;

// The callback which is passed to |handler|.
void HandlerCallback(v8::Isolate* isolate,
                     v8::Local<v8::External> external,
                     v8::Local<v8::Object> state,
                     mate::Arguments* args) {
  // Check if the callback has already been called.
  v8::Local<v8::String> called_symbol = mate::StringToSymbol(isolate, "called");
  if (state->Has(called_symbol))
    return;  // no nothing
  else
    state->Set(called_symbol, v8::Boolean::New(isolate, true));

  // If there is no argument passed then we failed.
  scoped_ptr<CallbackHolder> holder(
      static_cast<CallbackHolder*>(external->Value()));
  CHECK(holder);
  v8::Local<v8::Value> value;
  if (!args->GetNext(&value)) {
    holder->callback.Run(false, nullptr);
    return;
  }

  // Pass whatever user passed to the actaul request job.
  V8ValueConverter converter;
  v8::Local<v8::Context> context = args->isolate()->GetCurrentContext();
  scoped_ptr<base::Value> options(converter.FromV8Value(value, context));
  content::BrowserThread::PostTask(
      content::BrowserThread::IO, FROM_HERE,
      base::Bind(holder->callback, true, base::Passed(&options)));
}

// func.bind(func, arg1, arg2).
// NB(zcbenz): Using C++11 version crashes VS.
v8::Local<v8::Value> BindFunctionWith(v8::Isolate* isolate,
                                      v8::Local<v8::Context> context,
                                      v8::Local<v8::Function> func,
                                      v8::Local<v8::Value> arg1,
                                      v8::Local<v8::Value> arg2) {
  v8::MaybeLocal<v8::Value> bind = func->Get(mate::StringToV8(isolate, "bind"));
  CHECK(!bind.IsEmpty());
  v8::Local<v8::Function> bind_func =
      v8::Local<v8::Function>::Cast(bind.ToLocalChecked());
  v8::Local<v8::Value> converted[] = { func, arg1, arg2 };
  return bind_func->Call(
      context, func, arraysize(converted), converted).ToLocalChecked();
}

// Generate the callback that will be passed to |handler|.
v8::MaybeLocal<v8::Value> GenerateCallback(v8::Isolate* isolate,
                                           v8::Local<v8::Context> context,
                                           const ResponseCallback& callback) {
  // The FunctionTemplate is cached.
  if (g_handler_callback_.IsEmpty())
    g_handler_callback_.Reset(
        isolate,
        mate::CreateFunctionTemplate(isolate, base::Bind(&HandlerCallback)));

  v8::Local<v8::FunctionTemplate> handler_callback =
      v8::Local<v8::FunctionTemplate>::New(isolate, g_handler_callback_);
  CallbackHolder* holder = new CallbackHolder;
  holder->callback = callback;
  return BindFunctionWith(isolate, context, handler_callback->GetFunction(),
                          v8::External::New(isolate, holder),
                          v8::Object::New(isolate));
}

}  // namespace

void AskForOptions(v8::Isolate* isolate,
                   const JavaScriptHandler& handler,
                   net::URLRequest* request,
                   const ResponseCallback& callback) {
  DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
  v8::Locker locker(isolate);
  v8::HandleScope handle_scope(isolate);
  v8::Local<v8::Context> context = isolate->GetCurrentContext();
  v8::Context::Scope context_scope(context);
  // We don't convert the callback to C++ directly because creating
  // FunctionTemplate will cause memory leak since V8 never releases it. So we
  // have to create the function object in JavaScript to work around it.
  v8::MaybeLocal<v8::Value> wrapped_callback = GenerateCallback(
      isolate, context, callback);
  if (wrapped_callback.IsEmpty()) {
    callback.Run(false, nullptr);
    return;
  }
  handler.Run(request, wrapped_callback.ToLocalChecked());
}

bool IsErrorOptions(base::Value* value, int* error) {
  if (value->IsType(base::Value::TYPE_DICTIONARY)) {
    base::DictionaryValue* dict = static_cast<base::DictionaryValue*>(value);
    if (dict->GetInteger("error", error))
      return true;
  } else if (value->IsType(base::Value::TYPE_INTEGER)) {
    if (value->GetAsInteger(error))
      return true;
  }
  return false;
}

}  // namespace internal

}  // namespace atom
<commit_msg>Completion callback is called on IO thread<commit_after>// Copyright (c) 2015 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.

#include "atom/browser/net/js_asker.h"

#include <vector>

#include "atom/common/native_mate_converters/callback.h"
#include "atom/common/native_mate_converters/v8_value_converter.h"
#include "native_mate/function_template.h"

namespace atom {

namespace internal {

namespace {

struct CallbackHolder {
  ResponseCallback callback;
};

// Cached JavaScript version of |HandlerCallback|.
v8::Persistent<v8::FunctionTemplate> g_handler_callback_;

// The callback which is passed to |handler|.
void HandlerCallback(v8::Isolate* isolate,
                     v8::Local<v8::External> external,
                     v8::Local<v8::Object> state,
                     mate::Arguments* args) {
  // Check if the callback has already been called.
  v8::Local<v8::String> called_symbol = mate::StringToSymbol(isolate, "called");
  if (state->Has(called_symbol))
    return;  // no nothing
  else
    state->Set(called_symbol, v8::Boolean::New(isolate, true));

  // If there is no argument passed then we failed.
  scoped_ptr<CallbackHolder> holder(
      static_cast<CallbackHolder*>(external->Value()));
  CHECK(holder);
  v8::Local<v8::Value> value;
  if (!args->GetNext(&value)) {
    content::BrowserThread::PostTask(
        content::BrowserThread::IO, FROM_HERE,
        base::Bind(holder->callback, false, nullptr));
    return;
  }

  // Pass whatever user passed to the actaul request job.
  V8ValueConverter converter;
  v8::Local<v8::Context> context = args->isolate()->GetCurrentContext();
  scoped_ptr<base::Value> options(converter.FromV8Value(value, context));
  content::BrowserThread::PostTask(
      content::BrowserThread::IO, FROM_HERE,
      base::Bind(holder->callback, true, base::Passed(&options)));
}

// func.bind(func, arg1, arg2).
// NB(zcbenz): Using C++11 version crashes VS.
v8::Local<v8::Value> BindFunctionWith(v8::Isolate* isolate,
                                      v8::Local<v8::Context> context,
                                      v8::Local<v8::Function> func,
                                      v8::Local<v8::Value> arg1,
                                      v8::Local<v8::Value> arg2) {
  v8::MaybeLocal<v8::Value> bind = func->Get(mate::StringToV8(isolate, "bind"));
  CHECK(!bind.IsEmpty());
  v8::Local<v8::Function> bind_func =
      v8::Local<v8::Function>::Cast(bind.ToLocalChecked());
  v8::Local<v8::Value> converted[] = { func, arg1, arg2 };
  return bind_func->Call(
      context, func, arraysize(converted), converted).ToLocalChecked();
}

// Generate the callback that will be passed to |handler|.
v8::MaybeLocal<v8::Value> GenerateCallback(v8::Isolate* isolate,
                                           v8::Local<v8::Context> context,
                                           const ResponseCallback& callback) {
  // The FunctionTemplate is cached.
  if (g_handler_callback_.IsEmpty())
    g_handler_callback_.Reset(
        isolate,
        mate::CreateFunctionTemplate(isolate, base::Bind(&HandlerCallback)));

  v8::Local<v8::FunctionTemplate> handler_callback =
      v8::Local<v8::FunctionTemplate>::New(isolate, g_handler_callback_);
  CallbackHolder* holder = new CallbackHolder;
  holder->callback = callback;
  return BindFunctionWith(isolate, context, handler_callback->GetFunction(),
                          v8::External::New(isolate, holder),
                          v8::Object::New(isolate));
}

}  // namespace

void AskForOptions(v8::Isolate* isolate,
                   const JavaScriptHandler& handler,
                   net::URLRequest* request,
                   const ResponseCallback& callback) {
  DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
  v8::Locker locker(isolate);
  v8::HandleScope handle_scope(isolate);
  v8::Local<v8::Context> context = isolate->GetCurrentContext();
  v8::Context::Scope context_scope(context);
  // We don't convert the callback to C++ directly because creating
  // FunctionTemplate will cause memory leak since V8 never releases it. So we
  // have to create the function object in JavaScript to work around it.
  v8::MaybeLocal<v8::Value> wrapped_callback = GenerateCallback(
      isolate, context, callback);
  if (wrapped_callback.IsEmpty()) {
    callback.Run(false, nullptr);
    return;
  }
  handler.Run(request, wrapped_callback.ToLocalChecked());
}

bool IsErrorOptions(base::Value* value, int* error) {
  if (value->IsType(base::Value::TYPE_DICTIONARY)) {
    base::DictionaryValue* dict = static_cast<base::DictionaryValue*>(value);
    if (dict->GetInteger("error", error))
      return true;
  } else if (value->IsType(base::Value::TYPE_INTEGER)) {
    if (value->GetAsInteger(error))
      return true;
  }
  return false;
}

}  // namespace internal

}  // namespace atom
<|endoftext|>


<commit_before>#include "visualization.h"
#include "audiopath.h"
#include "abstractvideooutput.h"
#include <phonon/ifaces/abstractvideooutput.h>

namespace Phonon
{
namespace Fake
{

Visualization::Visualization( QObject* parent )
	: QObject( parent )
{
}

int Visualization::visualization() const
{
	return m_visualization;
}

void Visualization::setVisualization( int newVisualization )
{
	m_visualization = newVisualization;
}

void Visualization::setAudioPath( Ifaces::AudioPath* audioPath )
{
	Q_ASSERT( audioPath );
	AudioPath* ap = qobject_cast<AudioPath*>( audioPath->qobject() );
	Q_ASSERT( ap );
	m_audioPath = ap;
}

void Visualization::setVideoOutput( Ifaces::AbstractVideoOutput* videoOutputIface )
{
	Q_ASSERT( videoOutputIface );
	AbstractVideoOutput* vo = reinterpret_cast<Phonon::Fake::AbstractVideoOutput*>( videoOutputIface->internal1() );
	Q_ASSERT( vo );
	m_videoOutput = vo;
}

}} //namespace Phonon::Fake

#include "visualization.moc"
// vim: sw=4 ts=4 noet
<commit_msg>SVN_SILENT: add missing license header<commit_after>/*  This file is part of the KDE project
    Copyright (C) 2006 Matthias Kretz <kretz@kde.org>

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

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

    You should have received a copy of the GNU Library General Public License
    along with this library; see the file COPYING.LIB.  If not, write to
    the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
    Boston, MA 02110-1301, USA.

*/

#include "visualization.h"
#include "audiopath.h"
#include "abstractvideooutput.h"
#include <phonon/ifaces/abstractvideooutput.h>

namespace Phonon
{
namespace Fake
{

Visualization::Visualization( QObject* parent )
	: QObject( parent )
{
}

int Visualization::visualization() const
{
	return m_visualization;
}

void Visualization::setVisualization( int newVisualization )
{
	m_visualization = newVisualization;
}

void Visualization::setAudioPath( Ifaces::AudioPath* audioPath )
{
	Q_ASSERT( audioPath );
	AudioPath* ap = qobject_cast<AudioPath*>( audioPath->qobject() );
	Q_ASSERT( ap );
	m_audioPath = ap;
}

void Visualization::setVideoOutput( Ifaces::AbstractVideoOutput* videoOutputIface )
{
	Q_ASSERT( videoOutputIface );
	AbstractVideoOutput* vo = reinterpret_cast<Phonon::Fake::AbstractVideoOutput*>( videoOutputIface->internal1() );
	Q_ASSERT( vo );
	m_videoOutput = vo;
}

}} //namespace Phonon::Fake

#include "visualization.moc"
// vim: sw=4 ts=4 noet
<|endoftext|>


<commit_before><commit_msg>added ability to see and download archived logs<commit_after><|endoftext|>


<commit_before>// Copyright 2020 Google LLC
//
// 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.

#include "p4_symbolic/ir/table_entries.h"

#include <iostream>
#include <regex>
#include <string>

#include "absl/strings/str_format.h"
#include "absl/strings/str_split.h"
#include "p4_symbolic/util/io.h"

namespace p4_symbolic {
namespace ir {

// TODO(babman): unclear if we need this right now.
//               Ideally, we want to represent everything as bitvectors,
//               However, Z3 API may provide a better way to encode/transform
//               to hex.
pdpi::StatusOr<int> FormatBitStringAsHex(std::string str) {
  // detect the format: either a number, an IP, an IP range or a mac address.
  std::regex number("^(-?)([0-9]+)$");
  std::regex ip("^([0-9]+)\\.([0-9]+)\\.([0-9]+)\\.([0-9]+)$");
  std::regex ip_range("^([0-9]+)\\.([0-9]+)\\.([0-9]+)\\.([0-9]+)/([0-9]+)$");
  std::regex mac("^(?:([0-9A-Fa-f]{2}):){5}([0-9A-Fa-f]{2})$");

  std::smatch sm;
  if (std::regex_match(str, sm, number)) {
    return std::atoi(str.c_str());
  } else if (std::regex_match(str, sm, ip)) {
  } else if (std::regex_match(str, sm, ip_range)) {
  } else if (std::regex_match(str, sm, mac)) {
  } else {
    return absl::Status(absl::StatusCode::kInvalidArgument,
                        absl::StrFormat("Malformed table entry value %s", str));
  }

  return -1;
}

pdpi::StatusOr<std::pair<std::string, TableEntry>> ParseLine(
    const std::string &line) {
  std::vector<std::string> tokens =
      absl::StrSplit(line, ' ', absl::SkipWhitespace());
  if (tokens.size() < 3) {
    return absl::Status(
        absl::StatusCode::kInvalidArgument,
        absl::StrFormat("Malformed table entry, found %s", line));
  }
  if (tokens[0] != "table_add") {
    return absl::Status(
        absl::StatusCode::kInvalidArgument,
        absl::StrFormat("Malformed table entry command %s, found %s", tokens[0],
                        line));
  }

  // Parse table entries.
  TableEntry output;
  output.set_action(tokens[2]);
  bool found_delimiter = false;  // true when "=>" is found.
  for (size_t i = 3; i < tokens.size(); i++) {
    if (tokens[i] == "=>") {
      found_delimiter = true;
      continue;
    }

    ASSIGN_OR_RETURN(int val, FormatBitStringAsHex(tokens[i]));
    if (found_delimiter) {
      output.add_action_parameters(val);
    } else {
      output.add_match_values(val);
    }
  }

  return std::make_pair(tokens[1], output);
}

pdpi::StatusOr<TableEntries> ParseAndFillEntries(const char *entries_path) {
  ASSIGN_OR_RETURN(std::string file_content, util::ReadFile(entries_path));

  // Skip empty lines or ones that only contain whitespace.
  std::vector<std::string> lines =
      absl::StrSplit(file_content, '\n', absl::SkipWhitespace());

  std::vector<std::pair<std::string, TableEntry>> output;
  for (const std::string &line : lines) {
    ASSIGN_OR_RETURN(auto entry, ParseLine(line));
    output.push_back(entry);
  }

  return output;
}

}  // namespace ir
}  // namespace p4_symbolic
<commit_msg>simplify table_entries parsing to ints for now<commit_after>// Copyright 2020 Google LLC
//
// 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.

#include "p4_symbolic/ir/table_entries.h"

#include <iostream>
#include <regex>
#include <string>

#include "absl/strings/str_format.h"
#include "absl/strings/str_split.h"
#include "p4_symbolic/util/io.h"

namespace p4_symbolic {
namespace ir {

pdpi::StatusOr<std::pair<std::string, TableEntry>> ParseLine(
    const std::string &line) {
  std::vector<std::string> tokens =
      absl::StrSplit(line, ' ', absl::SkipWhitespace());
  if (tokens.size() < 3) {
    return absl::Status(
        absl::StatusCode::kInvalidArgument,
        absl::StrFormat("Malformed table entry, found %s", line));
  }
  if (tokens[0] != "table_add") {
    return absl::Status(
        absl::StatusCode::kInvalidArgument,
        absl::StrFormat("Malformed table entry command %s, found %s", tokens[0],
                        line));
  }

  // Parse table entries.
  TableEntry output;
  output.set_action(tokens[2]);
  bool found_delimiter = false;  // true when "=>" is found.
  for (size_t i = 3; i < tokens.size(); i++) {
    if (tokens[i] == "=>") {
      found_delimiter = true;
      continue;
    }

    int val = std::atoi(tokens[i].c_str());
    if (found_delimiter) {
      output.add_action_parameters(val);
    } else {
      output.add_match_values(val);
    }
  }

  return std::make_pair(tokens[1], output);
}

pdpi::StatusOr<TableEntries> ParseAndFillEntries(const char *entries_path) {
  ASSIGN_OR_RETURN(std::string file_content, util::ReadFile(entries_path));

  // Skip empty lines or ones that only contain whitespace.
  std::vector<std::string> lines =
      absl::StrSplit(file_content, '\n', absl::SkipWhitespace());

  std::vector<std::pair<std::string, TableEntry>> output;
  for (const std::string &line : lines) {
    ASSIGN_OR_RETURN(auto entry, ParseLine(line));
    output.push_back(entry);
  }

  return output;
}

}  // namespace ir
}  // namespace p4_symbolic
<|endoftext|>