<commit_before>/*
 * Copyright (c) 2007-2010 Digital Bazaar, Inc. All rights reserved.
 */
#include "monarch/mail/Mail.h"

#include "monarch/util/Base64Codec.h"
#include "monarch/util/StringTools.h"

#include <cstdio>

using namespace std;
using namespace monarch::mail;
using namespace monarch::rt;
using namespace monarch::util;

Mail::Mail()
{
   mRecipients->setType(Array);
   mMessage["headers"]["To"]->setType(Array);
   mMessage["headers"]["Subject"] = "";
   mMessage["body"]->setType(String);
}

Mail::~Mail()
{
}

void Mail::clear()
{
   mRecipients->setType(Array);
   mRecipients->clear();
   mMessage["headers"]["To"]->setType(Array);
   mMessage["headers"]["To"]->clear();
   mMessage["headers"]["Subject"] = "";
   mMessage["body"]->setType(String);
   mMessage["body"]->clear();
}

bool Mail::setAddress(Address& a, const char* address)
{
   bool rval = false;

   // FIXME: obviously this needs work to be robust

   // set address
   a["address"] = address;

   // check for domain
   const char* at = strchr(address, '@');
   if(at != NULL)
   {
      // set domain
      a["domain"] = (at + 1);

      // set smtp encoding of address
      char temp[strlen(address) + 3];
      sprintf(temp, "<%s>", address);
      a["smtpEncoding"] = temp;

      rval = true;
   }

   return rval;
}

bool Mail::addRecipient(const char* header, const char* address)
{
   bool rval = false;

   Address a;
   if((rval = setAddress(a, address)))
   {
      // add to list of recipients
      mRecipients[mRecipients->length()] = a;

      // add header if not NULL
      if(header != NULL)
      {
         mMessage["headers"][header]->setType(Array);
         mMessage["headers"][header]->append() = address;
      }
   }

   return rval;
}

bool Mail::setSender(const char* address)
{
   bool rval = false;

   if((rval = setAddress(mSender, address)))
   {
      // set "From" header
      mMessage["headers"]["From"] = address;
   }

   return rval;
}

Address& Mail::getSender()
{
   return mSender;
}

bool Mail::addTo(const char* address)
{
   return addRecipient("To", address);
}

bool Mail::addCc(const char* address)
{
   return addRecipient("CC", address);
}

bool Mail::addBcc(const char* address)
{
   return addRecipient(NULL, address);
}

AddressList& Mail::getRecipients()
{
   return mRecipients;
}

static void biCapitalize(char* name)
{
   // capitalize first letter and letters after hyphens
   // decapitalize other letters
   // NOTE: hardcoded version is faster than using toupper/tolower
   int length = 0;
   if(name != NULL && *name != '\0')
   {
      length++;
      char* ptr = name;
      // cap first
      if(*ptr >= 'a' && *ptr <= 'z')
      {
         *ptr -= 'a' - 'A';
      }
      for(ptr++; *ptr != '\0'; ptr++, length++)
      {
         // cap after '-'
         if(*(ptr - 1) == '-')
         {
            if(*ptr >= 'a' && *ptr <= 'z')
            {
               *ptr -= 'a' - 'A';
            }
         }
         // decap rest
         else if(*ptr >= 'A' && *ptr <= 'Z')
         {
            *ptr += 'a' - 'A';
         }
      }

      // special case TE header
      if(length == 2 && name[0] == 'T' && name[1] == 'e')
      {
         name[1] = 'E';
      }
   }
}

void Mail::setHeader(const char* header, const char* value)
{
   if(strcasecmp(header, "from") == 0)
   {
      setSender(value);
   }
   else if(strcasecmp(header, "to") == 0)
   {
      addTo(value);
   }
   else if(strcasecmp(header, "cc") == 0)
   {
      addCc(value);
   }
   else if(strcasecmp(header, "bcc") == 0)
   {
      addBcc(value);
   }
   else if(strcasecmp(header, "subject") == 0)
   {
      setSubject(value);
   }
   else
   {
      char tmp[strlen(header) + 1];
      strcpy(tmp, header);
      biCapitalize(tmp);
      mMessage["headers"][tmp] = value;
   }
}

void Mail::setSubject(const char* subject)
{
   mMessage["headers"]["Subject"] = subject;
}

void Mail::setBody(const char* body)
{
   mMessage["body"] = body;
}

void Mail::appendBodyLine(const char* line)
{
   string str = mMessage["body"]->getString();
   str.append(line);
   str.push_back('\r');
   str.push_back('\n');
   mMessage["body"] = str.c_str();
}

Message& Mail::getMessage()
{
   return mMessage;
}

bool Mail::shouldTransferEncodeBody()
{
   bool rval = false;

   if(mMessage["headers"]->hasMember("Content-Transfer-Encoding"))
   {
      const char* encoding =
         mMessage["headers"]["Content-Transfer-Encoding"]->getString();
      if(strcasecmp(encoding, "base64") == 0)
      {
         rval = true;
      }
   }

   return rval;
}

string Mail::getTransferEncodedBody()
{
   string rval = mMessage["body"]->getString();

   bool encoded = false;
   if(mMessage["headers"]->hasMember("Content-Transfer-Encoding"))
   {
      const char* encoding =
         mMessage["headers"]["Content-Transfer-Encoding"]->getString();
      if(strcasecmp(encoding, "base64") == 0)
      {
         // base64 encode message
         rval = Base64Codec::encode(rval.c_str(), rval.length());
         encoded = true;
      }
   }

   if(!encoded)
   {
      // use default smtp-encoding
      smtpMessageEncode(rval);
   }

   return rval;
}
#include "monarch/test/Test.h"
string Mail::toTemplate()
{
   string str;

   // add headers
   DynamicObjectIterator i = mMessage["headers"].getIterator();
   while(i->hasNext())
   {
      DynamicObject& header = i->next();

      if(header->getType() == Array)
      {
         DynamicObjectIterator ii = header.getIterator();
         while(ii->hasNext())
         {
            DynamicObject& each = ii->next();
            str.append(i->getName());
            str.append(": ");
            str.append(each->getString());
            str.append("\r\n");
         }
      }
      else
      {
         str.append(i->getName());
         str.append(": ");
         str.append(header->getString());
         str.append("\r\n");
      }
   }

   // terminate headers
   str.append("\r\n");

   // add body
   str.append(mMessage["body"]->getString());

   // escape all '{'
   StringTools::replaceAll(str, "{", "{:ldelim}");

   // escape all '}' that do not follow '{:ldelim'
   string::size_type pos = str.find('}');
   while(pos != string::npos)
   {
      if(pos < 8 || strncmp(str.c_str() + pos - 8, "{:ldelim}", 9) != 0)
      {
         str.replace(pos, 1, "{:rdelim}");
         pos += 8;
      }
      pos = str.find('}', pos + 1);
   }

   return str;
}

string& Mail::smtpMessageEncode(string& str)
{
   // insert second dot for any line that starts with a dot
   return StringTools::replaceAll(str, "\r\n.", "\r\n..");
}
<commit_msg>Removed include.<commit_after>/*
 * Copyright (c) 2007-2010 Digital Bazaar, Inc. All rights reserved.
 */
#include "monarch/mail/Mail.h"

#include "monarch/util/Base64Codec.h"
#include "monarch/util/StringTools.h"

#include <cstdio>

using namespace std;
using namespace monarch::mail;
using namespace monarch::rt;
using namespace monarch::util;

Mail::Mail()
{
   mRecipients->setType(Array);
   mMessage["headers"]["To"]->setType(Array);
   mMessage["headers"]["Subject"] = "";
   mMessage["body"]->setType(String);
}

Mail::~Mail()
{
}

void Mail::clear()
{
   mRecipients->setType(Array);
   mRecipients->clear();
   mMessage["headers"]["To"]->setType(Array);
   mMessage["headers"]["To"]->clear();
   mMessage["headers"]["Subject"] = "";
   mMessage["body"]->setType(String);
   mMessage["body"]->clear();
}

bool Mail::setAddress(Address& a, const char* address)
{
   bool rval = false;

   // FIXME: obviously this needs work to be robust

   // set address
   a["address"] = address;

   // check for domain
   const char* at = strchr(address, '@');
   if(at != NULL)
   {
      // set domain
      a["domain"] = (at + 1);

      // set smtp encoding of address
      char temp[strlen(address) + 3];
      sprintf(temp, "<%s>", address);
      a["smtpEncoding"] = temp;

      rval = true;
   }

   return rval;
}

bool Mail::addRecipient(const char* header, const char* address)
{
   bool rval = false;

   Address a;
   if((rval = setAddress(a, address)))
   {
      // add to list of recipients
      mRecipients[mRecipients->length()] = a;

      // add header if not NULL
      if(header != NULL)
      {
         mMessage["headers"][header]->setType(Array);
         mMessage["headers"][header]->append() = address;
      }
   }

   return rval;
}

bool Mail::setSender(const char* address)
{
   bool rval = false;

   if((rval = setAddress(mSender, address)))
   {
      // set "From" header
      mMessage["headers"]["From"] = address;
   }

   return rval;
}

Address& Mail::getSender()
{
   return mSender;
}

bool Mail::addTo(const char* address)
{
   return addRecipient("To", address);
}

bool Mail::addCc(const char* address)
{
   return addRecipient("CC", address);
}

bool Mail::addBcc(const char* address)
{
   return addRecipient(NULL, address);
}

AddressList& Mail::getRecipients()
{
   return mRecipients;
}

static void biCapitalize(char* name)
{
   // capitalize first letter and letters after hyphens
   // decapitalize other letters
   // NOTE: hardcoded version is faster than using toupper/tolower
   int length = 0;
   if(name != NULL && *name != '\0')
   {
      length++;
      char* ptr = name;
      // cap first
      if(*ptr >= 'a' && *ptr <= 'z')
      {
         *ptr -= 'a' - 'A';
      }
      for(ptr++; *ptr != '\0'; ptr++, length++)
      {
         // cap after '-'
         if(*(ptr - 1) == '-')
         {
            if(*ptr >= 'a' && *ptr <= 'z')
            {
               *ptr -= 'a' - 'A';
            }
         }
         // decap rest
         else if(*ptr >= 'A' && *ptr <= 'Z')
         {
            *ptr += 'a' - 'A';
         }
      }

      // special case TE header
      if(length == 2 && name[0] == 'T' && name[1] == 'e')
      {
         name[1] = 'E';
      }
   }
}

void Mail::setHeader(const char* header, const char* value)
{
   if(strcasecmp(header, "from") == 0)
   {
      setSender(value);
   }
   else if(strcasecmp(header, "to") == 0)
   {
      addTo(value);
   }
   else if(strcasecmp(header, "cc") == 0)
   {
      addCc(value);
   }
   else if(strcasecmp(header, "bcc") == 0)
   {
      addBcc(value);
   }
   else if(strcasecmp(header, "subject") == 0)
   {
      setSubject(value);
   }
   else
   {
      char tmp[strlen(header) + 1];
      strcpy(tmp, header);
      biCapitalize(tmp);
      mMessage["headers"][tmp] = value;
   }
}

void Mail::setSubject(const char* subject)
{
   mMessage["headers"]["Subject"] = subject;
}

void Mail::setBody(const char* body)
{
   mMessage["body"] = body;
}

void Mail::appendBodyLine(const char* line)
{
   string str = mMessage["body"]->getString();
   str.append(line);
   str.push_back('\r');
   str.push_back('\n');
   mMessage["body"] = str.c_str();
}

Message& Mail::getMessage()
{
   return mMessage;
}

bool Mail::shouldTransferEncodeBody()
{
   bool rval = false;

   if(mMessage["headers"]->hasMember("Content-Transfer-Encoding"))
   {
      const char* encoding =
         mMessage["headers"]["Content-Transfer-Encoding"]->getString();
      if(strcasecmp(encoding, "base64") == 0)
      {
         rval = true;
      }
   }

   return rval;
}

string Mail::getTransferEncodedBody()
{
   string rval = mMessage["body"]->getString();

   bool encoded = false;
   if(mMessage["headers"]->hasMember("Content-Transfer-Encoding"))
   {
      const char* encoding =
         mMessage["headers"]["Content-Transfer-Encoding"]->getString();
      if(strcasecmp(encoding, "base64") == 0)
      {
         // base64 encode message
         rval = Base64Codec::encode(rval.c_str(), rval.length());
         encoded = true;
      }
   }

   if(!encoded)
   {
      // use default smtp-encoding
      smtpMessageEncode(rval);
   }

   return rval;
}

string Mail::toTemplate()
{
   string str;

   // add headers
   DynamicObjectIterator i = mMessage["headers"].getIterator();
   while(i->hasNext())
   {
      DynamicObject& header = i->next();

      if(header->getType() == Array)
      {
         DynamicObjectIterator ii = header.getIterator();
         while(ii->hasNext())
         {
            DynamicObject& each = ii->next();
            str.append(i->getName());
            str.append(": ");
            str.append(each->getString());
            str.append("\r\n");
         }
      }
      else
      {
         str.append(i->getName());
         str.append(": ");
         str.append(header->getString());
         str.append("\r\n");
      }
   }

   // terminate headers
   str.append("\r\n");

   // add body
   str.append(mMessage["body"]->getString());

   // escape all '{'
   StringTools::replaceAll(str, "{", "{:ldelim}");

   // escape all '}' that do not follow '{:ldelim'
   string::size_type pos = str.find('}');
   while(pos != string::npos)
   {
      if(pos < 8 || strncmp(str.c_str() + pos - 8, "{:ldelim}", 9) != 0)
      {
         str.replace(pos, 1, "{:rdelim}");
         pos += 8;
      }
      pos = str.find('}', pos + 1);
   }

   return str;
}

string& Mail::smtpMessageEncode(string& str)
{
   // insert second dot for any line that starts with a dot
   return StringTools::replaceAll(str, "\r\n.", "\r\n..");
}
<|endoftext|>


<commit_before>/* Copyright (c) 2017, CNRS-LAAS
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.

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 THE COPYRIGHT HOLDER OR CONTRIBUTORS 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. */

#ifndef PLANNING_CPP_DEBUG_H
#define PLANNING_CPP_DEBUG_H

#include <stdio.h>
#include <signal.h>
#include <stdio.h>
#include <signal.h>
#include <execinfo.h>
#include <wait.h>
#include <zconf.h>
#include <cstdlib>
#include <cassert>

 namespace SAOP {

     void print_trace();

     double drand(double min, double max);

     size_t rand(size_t min, size_t non_inclusive_max);

     double positive_modulo(double left, double right);

}

/** Macro that test equality of to floating point number, disregarding rounding errors. */
#define ALMOST_EQUAL(x, y) (fabs((double) (x) - (double) (y)) < 0.000001)

/** Macro that test whether x >= y with tolerance to rounding errors. */
#define ALMOST_GREATER_EQUAL(x, y) ((double) (x) >= ((double) (y) - 0.000001))

/** Macro that test whether x >= y with tolerance to rounding errors. */
#define ALMOST_LESSER_EQUAL(x, y) ((double) (x) <= ((double) (y) + 0.000001))

// http://cnicholson.net/2009/02/stupid-c-tricks-adventures-in-assert/
#ifdef DEBUG
#define ASSERT(test)                  \
do { if(!(test)) {                         \
  fprintf(stderr, "Failed assert\n"); \
  print_trace();                      \
}                                     \
assert(test); } while(0)
#else
#define ASSERT(test) \
        do { (void)sizeof(test); } while(0)
#endif

#endif //PLANNING_CPP_DEBUG_H
<commit_msg>Do not depend on zlib to include unistd.h<commit_after>/* Copyright (c) 2017, CNRS-LAAS
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.

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 THE COPYRIGHT HOLDER OR CONTRIBUTORS 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. */

#ifndef PLANNING_CPP_DEBUG_H
#define PLANNING_CPP_DEBUG_H

#include <stdio.h>
#include <signal.h>
#include <stdio.h>
#include <signal.h>
#include <execinfo.h>
#include <wait.h>
#include <unistd.h>
#include <cstdlib>
#include <cassert>

 namespace SAOP {

     void print_trace();

     double drand(double min, double max);

     size_t rand(size_t min, size_t non_inclusive_max);

     double positive_modulo(double left, double right);

}

/** Macro that test equality of to floating point number, disregarding rounding errors. */
#define ALMOST_EQUAL(x, y) (fabs((double) (x) - (double) (y)) < 0.000001)

/** Macro that test whether x >= y with tolerance to rounding errors. */
#define ALMOST_GREATER_EQUAL(x, y) ((double) (x) >= ((double) (y) - 0.000001))

/** Macro that test whether x >= y with tolerance to rounding errors. */
#define ALMOST_LESSER_EQUAL(x, y) ((double) (x) <= ((double) (y) + 0.000001))

// http://cnicholson.net/2009/02/stupid-c-tricks-adventures-in-assert/
#ifdef DEBUG
#define ASSERT(test)                  \
do { if(!(test)) {                         \
  fprintf(stderr, "Failed assert\n"); \
  print_trace();                      \
}                                     \
assert(test); } while(0)
#else
#define ASSERT(test) \
        do { (void)sizeof(test); } while(0)
#endif

#endif //PLANNING_CPP_DEBUG_H
<|endoftext|>


<commit_before><commit_msg>Add ucppkg1<commit_after><|endoftext|>


<commit_before>/**
 * This file is part of the CernVM File System.
 *
 * libcvmfs provides an API for the CernVM-FS client.  This is an
 * alternative to FUSE for reading a remote CernVM-FS repository.
 */

#define _FILE_OFFSET_BITS 64
#define __STDC_FORMAT_MACROS

#include "cvmfs_config.h"
#include "libcvmfs.h"

#include <errno.h>
#include <inttypes.h>
#include <stddef.h>
#include <sys/stat.h>

#include <cassert>
#include <cstdlib>
#include <string>

#include "libcvmfs_int.h"
#include "logging.h"
#include "smalloc.h"
#include "statistics.h"
#include "util/posix.h"
#include "xattr.h"

using namespace std;  // NOLINT

/**
 * Create the cvmfs_attr struct which contains the same information
 * as a stat, but also has pointers to the hash, symlink, and name.
 */
struct cvmfs_attr* cvmfs_attr_create()
{
  struct cvmfs_attr *attr;
  attr = reinterpret_cast<cvmfs_attr *>(calloc(1, sizeof(*attr)));
  return attr;
}

/**
 * Destroy the cvmfs_attr struct and frees the checksum, symlink,
 * name, and xattrs.
 */
void cvmfs_attr_destroy(struct cvmfs_attr *attr)
{
  if (attr) {
    free(attr->cvm_checksum);
    free(attr->cvm_symlink);
    free(attr->cvm_name);
    /* xattrs is a shallow pointer and not deleted */
    delete reinterpret_cast<XattrList *>(attr->cvm_xattrs);
  }
  free(attr);
}

struct cvmfs_nc_attr *cvmfs_nc_attr_init()
{
  struct cvmfs_nc_attr *attr;
  attr = reinterpret_cast<cvmfs_nc_attr *>(calloc(1, sizeof(*attr)));
  return attr;
}

void cvmfs_nc_attr_free(struct cvmfs_nc_attr *nc_attr)
{
  if (nc_attr) {
    free(nc_attr->mountpoint);
    free(nc_attr->hash);
  }
  free(nc_attr);

/**
 * Expand symlinks in all levels of a path.  Also, expand ".." and ".".  This
 * also has the side-effect of ensuring that cvmfs_getattr() is called on all
 * parent paths, which is needed to ensure proper loading of nested catalogs
 * before the child is accessed.
 */
static int expand_path(
  const int depth,
  LibContext *ctx,
  char const *path,
  string *expanded_path)
{
  string p_path = GetParentPath(path);
  string fname = GetFileName(path);
  int rc;

  if (fname == "..") {
    rc = expand_path(depth, ctx, p_path.c_str(), expanded_path);
    if (rc != 0) {
      return -1;
    }
    if (*expanded_path == "/") {
      // attempt to access parent path of the root of the repository
      LogCvmfs(kLogCvmfs, kLogDebug,
               "libcvmfs cannot resolve symlinks to paths outside of the repo: "
               "%s", path);
      errno = ENOENT;
      return -1;
    }
    *expanded_path = GetParentPath(*expanded_path);
    if (*expanded_path == "") {
      *expanded_path = "/";
    }
    return 0;
  }

  string buf;
  if (p_path != "") {
    rc = expand_path(depth, ctx, p_path.c_str(), &buf);
    if (rc != 0) {
      return -1;
    }

    if (fname == ".") {
      *expanded_path = buf;
      return 0;
    }
  }

  if (buf.length() == 0 || buf[buf.length()-1] != '/') {
    buf += "/";
  }
  buf += fname;

  struct stat st;
  rc = ctx->GetAttr(buf.c_str(), &st);
  if (rc != 0) {
    errno = -rc;
    return -1;
  }

  if (!S_ISLNK(st.st_mode)) {
    *expanded_path = buf;
    return 0;
  }

  if (depth > 1000) {
    // avoid unbounded recursion due to symlinks
    LogCvmfs(kLogCvmfs, kLogDebug,
             "libcvmfs hit its symlink recursion limit: %s", path);
    errno = ELOOP;
    return -1;
  }

  // expand symbolic link

  char *ln_buf = reinterpret_cast<char *>(alloca(st.st_size+2));
  if (!ln_buf) {
    errno = ENOMEM;
    return -1;
  }
  rc = ctx->Readlink(buf.c_str(), ln_buf, st.st_size + 2);
  if (rc != 0) {
    errno = -rc;
    return -1;
  }
  if (ln_buf[0] == '/') {
    // symlink is absolute path, strip /cvmfs/$repo
    unsigned len = ctx->mount_point()->fqrn().length();
    if (strncmp(ln_buf, ctx->mount_point()->fqrn().c_str(), len) == 0 &&
        (ln_buf[len] == '/' || ln_buf[len] == '\0'))
    {
      buf = ln_buf+len;
      if (ln_buf[len] == '\0') {
        buf += "/";
      }
    } else {
      LogCvmfs(kLogCvmfs, kLogDebug,
               "libcvmfs can't resolve symlinks to paths outside of the repo: "
               "%s --> %s (mountpoint=%s)",
               path, ln_buf, ctx->mount_point()->fqrn().c_str());
      errno = ENOENT;
      return -1;
    }
  } else {
    // symlink is relative path
    buf = GetParentPath(buf);
    buf += "/";
    buf += ln_buf;
  }

  // In case the symlink references other symlinks or contains ".."
  // or "."  we must now call expand_path on the result.

  return expand_path(depth + 1, ctx, buf.c_str(), expanded_path);
}

/**
 * Like expand_path(), but do not expand the final element of the path.
 */
static int expand_ppath(LibContext *ctx,
                        const char *path,
                        string *expanded_path)
{
  string p_path = GetParentPath(path);
  string fname = GetFileName(path);

  if (p_path == "") {
    *expanded_path = path;
    return 0;
  }

  int rc = expand_path(0, ctx, p_path.c_str(), expanded_path);
  if (rc != 0) {
    return rc;
  }

  (*expanded_path) += "/";
  (*expanded_path) += fname;

  return 0;
}

int cvmfs_open(LibContext *ctx, const char *path) {
  string lpath;
  int rc;
  rc = expand_path(0, ctx, path, &lpath);
  if (rc < 0) {
    return -1;
  }
  path = lpath.c_str();

  rc = ctx->Open(path);
  if (rc < 0) {
    errno = -rc;
    return -1;
  }
  return rc;
}

ssize_t cvmfs_pread(
  LibContext *ctx,
  int fd,
  void *buf,
  size_t size,
  off_t off)
{
  ssize_t nbytes = ctx->Pread(fd, buf, size, off);
  if (nbytes < 0) {
    errno = -nbytes;
    return -1;
  }
  return nbytes;
}

int cvmfs_close(LibContext *ctx, int fd)
{
  int rc = ctx->Close(fd);
  if (rc < 0) {
    errno = -rc;
    return -1;
  }
  return 0;
}

int cvmfs_readlink(
  LibContext *ctx,
  const char *path,
  char *buf,
  size_t size
) {
  string lpath;
  int rc;
  rc = expand_ppath(ctx, path, &lpath);
  if (rc < 0) {
    return -1;
  }
  path = lpath.c_str();

  rc = ctx->Readlink(path, buf, size);
  if (rc < 0) {
    errno = -rc;
    return -1;
  }
  return 0;
}

int cvmfs_stat(LibContext *ctx, const char *path, struct stat *st) {
  string lpath;
  int rc;
  rc = expand_path(0, ctx, path, &lpath);
  if (rc < 0) {
    return -1;
  }
  path = lpath.c_str();

  rc = ctx->GetAttr(path, st);
  if (rc < 0) {
    errno = -rc;
    return -1;
  }
  return 0;
}

int cvmfs_lstat(LibContext *ctx, const char *path, struct stat *st) {
  string lpath;
  int rc;
  rc = expand_ppath(ctx, path, &lpath);
  if (rc < 0) {
    return -1;
  }
  path = lpath.c_str();

  rc = ctx->GetAttr(path, st);
  if (rc < 0) {
    errno = -rc;
    return -1;
  }
  return 0;
}

int cvmfs_stat_attr(
  LibContext *ctx,
  const char *path,
  struct cvmfs_attr *attr
) {
  string lpath;
  int rc;
  rc = expand_path(0, ctx, path, &lpath);
  if (rc < 0) {
    return -1;
  }
  path = lpath.c_str();

  rc = ctx->GetExtAttr(path, attr);
  if (rc < 0) {
    errno = -rc;
    return -1;
  }
  return 0;
}

int cvmfs_listdir(
  LibContext *ctx,
  const char *path,
  char ***buf,
  size_t *buflen
) {
  string lpath;
  int rc;
  rc = expand_path(0, ctx, path, &lpath);
  if (rc < 0) {
    return -1;
  }
  path = lpath.c_str();

  rc = ctx->ListDirectory(path, buf, buflen);
  if (rc < 0) {
    errno = -rc;
    return -1;
  }
  return 0;
}

int cvmfs_stat_nc(
  LibContext *ctx,
  const char *path,
  struct cvmfs_nc_attr *nc_attr
) {
  string lpath;
  int rc;
  rc = expand_path(0, ctx, path, &lpath);
  if (rc < 0) {
    return -1;
  }
  path = lpath.c_str();

  rc = ctx->GetNestedCatalogAttr(path, nc_attr);
  if (rc < 0) {
    errno = -rc;
    return -1;
  }
  return 0;
}

int cvmfs_list_nc(
  LibContext *ctx,
  const char *path,
  char ***buf,
  size_t *buflen
) {
  string lpath;
  int rc;
  rc = expand_path(0, ctx, path, &lpath);
  if (rc < 0) {
    return -1;
  }
  path = lpath.c_str();

  rc = ctx->ListNestedCatalogs(path, buf, buflen);
  if (rc < 0) {
    errno = -rc;
    return -1;
  }
  return 0;
}

void cvmfs_list_free(char **buf)
{
  // Quick return if base pointer is NULL
  if (!buf) return;
  size_t pos = 0;
  // Iterate over each non-null entry and free
  // This assumes no null entries, which don't currently exist
  while (buf[pos]) {
    free(buf[pos]);
    pos++;
  }
  free(buf);
}

cvmfs_errors cvmfs_attach_repo_v2(
  const char *fqrn,
  SimpleOptionsParser *opts,
  LibContext **ctx)
{
  assert(ctx != NULL);
  opts->SwitchTemplateManager(new DefaultOptionsTemplateManager(fqrn));
  *ctx = LibContext::Create(fqrn, opts);
  assert(*ctx != NULL);
  loader::Failures result = (*ctx)->mount_point()->boot_status();
  if (result != loader::kFailOk) {
    LogCvmfs(kLogCvmfs, kLogStderr, "Attaching %s failed: %s (%d)",
             fqrn, (*ctx)->mount_point()->boot_error().c_str(), result);
    delete *ctx;
    *ctx = NULL;
  }
  return static_cast<cvmfs_errors>(result);
}

void cvmfs_adopt_options(cvmfs_context *ctx, SimpleOptionsParser *opts) {
  ctx->set_options_mgr(opts);
}

void cvmfs_detach_repo(LibContext *ctx) {
  delete ctx;
}

cvmfs_errors cvmfs_init_v2(SimpleOptionsParser *opts) {
  int result = LibGlobals::Initialize(opts);
  if (result != loader::kFailOk) {
    LogCvmfs(kLogCvmfs, kLogStderr, "Initialization failed: %s (%d)",
             LibGlobals::GetInstance()->file_system()->boot_error().c_str(),
             result);
    LibGlobals::CleanupInstance();
  }
  return static_cast<cvmfs_errors>(result);
}

void cvmfs_fini() {
  LibGlobals::CleanupInstance();
}

static void (*ext_log_fn)(const char *msg) = NULL;

static void libcvmfs_log_fn(
  const LogSource /*source*/,
  const int /*mask*/,
  const char *msg
) {
  if (ext_log_fn) {
    (*ext_log_fn)(msg);
  }
}

void cvmfs_set_log_fn(void (*log_fn)(const char *msg))
{
  ext_log_fn = log_fn;
  if (log_fn == NULL) {
    SetAltLogFunc(NULL);
  } else {
    SetAltLogFunc(libcvmfs_log_fn);
  }
}

char *cvmfs_statistics_format(cvmfs_context *ctx) {
  assert(ctx != NULL);
  std::string stats = ctx->mount_point()->statistics()
    ->PrintList(perf::Statistics::kPrintHeader);
  return strdup(stats.c_str());
}

int cvmfs_remount(LibContext *ctx) {
  // not implemented
  return -1;
}
<commit_msg>remove incorrect comment<commit_after>/**
 * This file is part of the CernVM File System.
 *
 * libcvmfs provides an API for the CernVM-FS client.  This is an
 * alternative to FUSE for reading a remote CernVM-FS repository.
 */

#define _FILE_OFFSET_BITS 64
#define __STDC_FORMAT_MACROS

#include "cvmfs_config.h"
#include "libcvmfs.h"

#include <errno.h>
#include <inttypes.h>
#include <stddef.h>
#include <sys/stat.h>

#include <cassert>
#include <cstdlib>
#include <string>

#include "libcvmfs_int.h"
#include "logging.h"
#include "smalloc.h"
#include "statistics.h"
#include "util/posix.h"
#include "xattr.h"

using namespace std;  // NOLINT

/**
 * Create the cvmfs_attr struct which contains the same information
 * as a stat, but also has pointers to the hash, symlink, and name.
 */
struct cvmfs_attr* cvmfs_attr_create()
{
  struct cvmfs_attr *attr;
  attr = reinterpret_cast<cvmfs_attr *>(calloc(1, sizeof(*attr)));
  return attr;
}

/**
 * Destroy the cvmfs_attr struct and frees the checksum, symlink,
 * name, and xattrs.
 */
void cvmfs_attr_destroy(struct cvmfs_attr *attr)
{
  if (attr) {
    free(attr->cvm_checksum);
    free(attr->cvm_symlink);
    free(attr->cvm_name);
    delete reinterpret_cast<XattrList *>(attr->cvm_xattrs);
  }
  free(attr);
}

struct cvmfs_nc_attr *cvmfs_nc_attr_init()
{
  struct cvmfs_nc_attr *attr;
  attr = reinterpret_cast<cvmfs_nc_attr *>(calloc(1, sizeof(*attr)));
  return attr;
}

void cvmfs_nc_attr_free(struct cvmfs_nc_attr *nc_attr)
{
  if (nc_attr) {
    free(nc_attr->mountpoint);
    free(nc_attr->hash);
  }
  free(nc_attr);

/**
 * Expand symlinks in all levels of a path.  Also, expand ".." and ".".  This
 * also has the side-effect of ensuring that cvmfs_getattr() is called on all
 * parent paths, which is needed to ensure proper loading of nested catalogs
 * before the child is accessed.
 */
static int expand_path(
  const int depth,
  LibContext *ctx,
  char const *path,
  string *expanded_path)
{
  string p_path = GetParentPath(path);
  string fname = GetFileName(path);
  int rc;

  if (fname == "..") {
    rc = expand_path(depth, ctx, p_path.c_str(), expanded_path);
    if (rc != 0) {
      return -1;
    }
    if (*expanded_path == "/") {
      // attempt to access parent path of the root of the repository
      LogCvmfs(kLogCvmfs, kLogDebug,
               "libcvmfs cannot resolve symlinks to paths outside of the repo: "
               "%s", path);
      errno = ENOENT;
      return -1;
    }
    *expanded_path = GetParentPath(*expanded_path);
    if (*expanded_path == "") {
      *expanded_path = "/";
    }
    return 0;
  }

  string buf;
  if (p_path != "") {
    rc = expand_path(depth, ctx, p_path.c_str(), &buf);
    if (rc != 0) {
      return -1;
    }

    if (fname == ".") {
      *expanded_path = buf;
      return 0;
    }
  }

  if (buf.length() == 0 || buf[buf.length()-1] != '/') {
    buf += "/";
  }
  buf += fname;

  struct stat st;
  rc = ctx->GetAttr(buf.c_str(), &st);
  if (rc != 0) {
    errno = -rc;
    return -1;
  }

  if (!S_ISLNK(st.st_mode)) {
    *expanded_path = buf;
    return 0;
  }

  if (depth > 1000) {
    // avoid unbounded recursion due to symlinks
    LogCvmfs(kLogCvmfs, kLogDebug,
             "libcvmfs hit its symlink recursion limit: %s", path);
    errno = ELOOP;
    return -1;
  }

  // expand symbolic link

  char *ln_buf = reinterpret_cast<char *>(alloca(st.st_size+2));
  if (!ln_buf) {
    errno = ENOMEM;
    return -1;
  }
  rc = ctx->Readlink(buf.c_str(), ln_buf, st.st_size + 2);
  if (rc != 0) {
    errno = -rc;
    return -1;
  }
  if (ln_buf[0] == '/') {
    // symlink is absolute path, strip /cvmfs/$repo
    unsigned len = ctx->mount_point()->fqrn().length();
    if (strncmp(ln_buf, ctx->mount_point()->fqrn().c_str(), len) == 0 &&
        (ln_buf[len] == '/' || ln_buf[len] == '\0'))
    {
      buf = ln_buf+len;
      if (ln_buf[len] == '\0') {
        buf += "/";
      }
    } else {
      LogCvmfs(kLogCvmfs, kLogDebug,
               "libcvmfs can't resolve symlinks to paths outside of the repo: "
               "%s --> %s (mountpoint=%s)",
               path, ln_buf, ctx->mount_point()->fqrn().c_str());
      errno = ENOENT;
      return -1;
    }
  } else {
    // symlink is relative path
    buf = GetParentPath(buf);
    buf += "/";
    buf += ln_buf;
  }

  // In case the symlink references other symlinks or contains ".."
  // or "."  we must now call expand_path on the result.

  return expand_path(depth + 1, ctx, buf.c_str(), expanded_path);
}

/**
 * Like expand_path(), but do not expand the final element of the path.
 */
static int expand_ppath(LibContext *ctx,
                        const char *path,
                        string *expanded_path)
{
  string p_path = GetParentPath(path);
  string fname = GetFileName(path);

  if (p_path == "") {
    *expanded_path = path;
    return 0;
  }

  int rc = expand_path(0, ctx, p_path.c_str(), expanded_path);
  if (rc != 0) {
    return rc;
  }

  (*expanded_path) += "/";
  (*expanded_path) += fname;

  return 0;
}

int cvmfs_open(LibContext *ctx, const char *path) {
  string lpath;
  int rc;
  rc = expand_path(0, ctx, path, &lpath);
  if (rc < 0) {
    return -1;
  }
  path = lpath.c_str();

  rc = ctx->Open(path);
  if (rc < 0) {
    errno = -rc;
    return -1;
  }
  return rc;
}

ssize_t cvmfs_pread(
  LibContext *ctx,
  int fd,
  void *buf,
  size_t size,
  off_t off)
{
  ssize_t nbytes = ctx->Pread(fd, buf, size, off);
  if (nbytes < 0) {
    errno = -nbytes;
    return -1;
  }
  return nbytes;
}

int cvmfs_close(LibContext *ctx, int fd)
{
  int rc = ctx->Close(fd);
  if (rc < 0) {
    errno = -rc;
    return -1;
  }
  return 0;
}

int cvmfs_readlink(
  LibContext *ctx,
  const char *path,
  char *buf,
  size_t size
) {
  string lpath;
  int rc;
  rc = expand_ppath(ctx, path, &lpath);
  if (rc < 0) {
    return -1;
  }
  path = lpath.c_str();

  rc = ctx->Readlink(path, buf, size);
  if (rc < 0) {
    errno = -rc;
    return -1;
  }
  return 0;
}

int cvmfs_stat(LibContext *ctx, const char *path, struct stat *st) {
  string lpath;
  int rc;
  rc = expand_path(0, ctx, path, &lpath);
  if (rc < 0) {
    return -1;
  }
  path = lpath.c_str();

  rc = ctx->GetAttr(path, st);
  if (rc < 0) {
    errno = -rc;
    return -1;
  }
  return 0;
}

int cvmfs_lstat(LibContext *ctx, const char *path, struct stat *st) {
  string lpath;
  int rc;
  rc = expand_ppath(ctx, path, &lpath);
  if (rc < 0) {
    return -1;
  }
  path = lpath.c_str();

  rc = ctx->GetAttr(path, st);
  if (rc < 0) {
    errno = -rc;
    return -1;
  }
  return 0;
}

int cvmfs_stat_attr(
  LibContext *ctx,
  const char *path,
  struct cvmfs_attr *attr
) {
  string lpath;
  int rc;
  rc = expand_path(0, ctx, path, &lpath);
  if (rc < 0) {
    return -1;
  }
  path = lpath.c_str();

  rc = ctx->GetExtAttr(path, attr);
  if (rc < 0) {
    errno = -rc;
    return -1;
  }
  return 0;
}

int cvmfs_listdir(
  LibContext *ctx,
  const char *path,
  char ***buf,
  size_t *buflen
) {
  string lpath;
  int rc;
  rc = expand_path(0, ctx, path, &lpath);
  if (rc < 0) {
    return -1;
  }
  path = lpath.c_str();

  rc = ctx->ListDirectory(path, buf, buflen);
  if (rc < 0) {
    errno = -rc;
    return -1;
  }
  return 0;
}

int cvmfs_stat_nc(
  LibContext *ctx,
  const char *path,
  struct cvmfs_nc_attr *nc_attr
) {
  string lpath;
  int rc;
  rc = expand_path(0, ctx, path, &lpath);
  if (rc < 0) {
    return -1;
  }
  path = lpath.c_str();

  rc = ctx->GetNestedCatalogAttr(path, nc_attr);
  if (rc < 0) {
    errno = -rc;
    return -1;
  }
  return 0;
}

int cvmfs_list_nc(
  LibContext *ctx,
  const char *path,
  char ***buf,
  size_t *buflen
) {
  string lpath;
  int rc;
  rc = expand_path(0, ctx, path, &lpath);
  if (rc < 0) {
    return -1;
  }
  path = lpath.c_str();

  rc = ctx->ListNestedCatalogs(path, buf, buflen);
  if (rc < 0) {
    errno = -rc;
    return -1;
  }
  return 0;
}

void cvmfs_list_free(char **buf)
{
  // Quick return if base pointer is NULL
  if (!buf) return;
  size_t pos = 0;
  // Iterate over each non-null entry and free
  // This assumes no null entries, which don't currently exist
  while (buf[pos]) {
    free(buf[pos]);
    pos++;
  }
  free(buf);
}

cvmfs_errors cvmfs_attach_repo_v2(
  const char *fqrn,
  SimpleOptionsParser *opts,
  LibContext **ctx)
{
  assert(ctx != NULL);
  opts->SwitchTemplateManager(new DefaultOptionsTemplateManager(fqrn));
  *ctx = LibContext::Create(fqrn, opts);
  assert(*ctx != NULL);
  loader::Failures result = (*ctx)->mount_point()->boot_status();
  if (result != loader::kFailOk) {
    LogCvmfs(kLogCvmfs, kLogStderr, "Attaching %s failed: %s (%d)",
             fqrn, (*ctx)->mount_point()->boot_error().c_str(), result);
    delete *ctx;
    *ctx = NULL;
  }
  return static_cast<cvmfs_errors>(result);
}

void cvmfs_adopt_options(cvmfs_context *ctx, SimpleOptionsParser *opts) {
  ctx->set_options_mgr(opts);
}

void cvmfs_detach_repo(LibContext *ctx) {
  delete ctx;
}

cvmfs_errors cvmfs_init_v2(SimpleOptionsParser *opts) {
  int result = LibGlobals::Initialize(opts);
  if (result != loader::kFailOk) {
    LogCvmfs(kLogCvmfs, kLogStderr, "Initialization failed: %s (%d)",
             LibGlobals::GetInstance()->file_system()->boot_error().c_str(),
             result);
    LibGlobals::CleanupInstance();
  }
  return static_cast<cvmfs_errors>(result);
}

void cvmfs_fini() {
  LibGlobals::CleanupInstance();
}

static void (*ext_log_fn)(const char *msg) = NULL;

static void libcvmfs_log_fn(
  const LogSource /*source*/,
  const int /*mask*/,
  const char *msg
) {
  if (ext_log_fn) {
    (*ext_log_fn)(msg);
  }
}

void cvmfs_set_log_fn(void (*log_fn)(const char *msg))
{
  ext_log_fn = log_fn;
  if (log_fn == NULL) {
    SetAltLogFunc(NULL);
  } else {
    SetAltLogFunc(libcvmfs_log_fn);
  }
}

char *cvmfs_statistics_format(cvmfs_context *ctx) {
  assert(ctx != NULL);
  std::string stats = ctx->mount_point()->statistics()
    ->PrintList(perf::Statistics::kPrintHeader);
  return strdup(stats.c_str());
}

int cvmfs_remount(LibContext *ctx) {
  // not implemented
  return -1;
}
<|endoftext|>


<commit_before>#ifndef K3_RUNTIME_BASESTRING_H
#define K3_RUNTIME_BASESTRING_H

#include <cstring>
#include <memory>

char* strdup(const char*);

namespace K3 {
  class base_string {
   public:
    // Constructors/Destructors/Assignment.

    base_string(): buffer(nullptr) {}

    base_string(const base_string& other): buffer(strdup(other.buffer)) {}

    base_string(base_string&& other): base_string() {
      swap(*this, other);
    }

    base_string(const char* b): buffer(strdup(b)) {}
    base_string(const std::string& s) : buffer(strdup(s.c_str())) {}

    base_string(const char* from, std::size_t count) {
      buffer = new char[count + 1];
      strncpy(buffer, from, count);
      buffer[count] = 0;
    }

    ~base_string() {
      delete [] buffer;
    }

    base_string& operator =(base_string other) {
      swap(*this, other);
      return *this;
    }

    base_string& operator =(base_string&& other) {
      swap(*this, other);
      return *this;
    }

    friend void swap(base_string& first, base_string& second) {
      using std::swap;
      swap(first.buffer, second.buffer);
    }

    // Conversions
    operator std::string() const {
      return std::string(buffer);
    }

    // Accessors
    std::size_t length() {
      return strlen(buffer);
    }

    char* c_str() {
      return buffer;
    }

    // Comparisons
    bool operator ==(const base_string& other) {
      return strcmp(buffer, other.buffer) == 0;
    }

    bool operator !=(const base_string& other) {
      return strcmp(buffer, other.buffer) != 0;
    }

    bool operator <=(const base_string& other) {
      return strcmp(buffer, other.buffer) <= 0;
    }

    bool operator <(const base_string& other) {
      return strcmp(buffer, other.buffer) < 0;
    }

    bool operator >=(const base_string& other) {
      return strcmp(buffer, other.buffer) >= 0;
    }

    bool operator >(const base_string& other) {
      return strcmp(buffer, other.buffer) > 0;
    }

    // Operations
    base_string substr(std::size_t from, std::size_t to) {
      auto n = strlen(buffer);

      if (from > n) {
        from = n;
      }

      if (to > n) {
        to = n;
      }

      return base_string(buffer + from, to - from);
    }

   private:
    char* buffer;
  };
}

#endif
<commit_msg>Mark substr as const.<commit_after>#ifndef K3_RUNTIME_BASESTRING_H
#define K3_RUNTIME_BASESTRING_H

#include <cstring>
#include <memory>

char* strdup(const char*);

namespace K3 {
  class base_string {
   public:
    // Constructors/Destructors/Assignment.

    base_string(): buffer(nullptr) {}

    base_string(const base_string& other): buffer(strdup(other.buffer)) {}

    base_string(base_string&& other): base_string() {
      swap(*this, other);
    }

    base_string(const char* b): buffer(strdup(b)) {}
    base_string(const std::string& s) : buffer(strdup(s.c_str())) {}

    base_string(const char* from, std::size_t count) {
      buffer = new char[count + 1];
      strncpy(buffer, from, count);
      buffer[count] = 0;
    }

    ~base_string() {
      delete [] buffer;
    }

    base_string& operator =(base_string other) {
      swap(*this, other);
      return *this;
    }

    base_string& operator =(base_string&& other) {
      swap(*this, other);
      return *this;
    }

    friend void swap(base_string& first, base_string& second) {
      using std::swap;
      swap(first.buffer, second.buffer);
    }

    // Conversions
    operator std::string() const {
      return std::string(buffer);
    }

    // Accessors
    std::size_t length() {
      return strlen(buffer);
    }

    char* c_str() {
      return buffer;
    }

    // Comparisons
    bool operator ==(const base_string& other) {
      return strcmp(buffer, other.buffer) == 0;
    }

    bool operator !=(const base_string& other) {
      return strcmp(buffer, other.buffer) != 0;
    }

    bool operator <=(const base_string& other) {
      return strcmp(buffer, other.buffer) <= 0;
    }

    bool operator <(const base_string& other) {
      return strcmp(buffer, other.buffer) < 0;
    }

    bool operator >=(const base_string& other) {
      return strcmp(buffer, other.buffer) >= 0;
    }

    bool operator >(const base_string& other) {
      return strcmp(buffer, other.buffer) > 0;
    }

    // Operations
    base_string substr(std::size_t from, std::size_t to) const {
      auto n = strlen(buffer);

      if (from > n) {
        from = n;
      }

      if (to > n) {
        to = n;
      }

      return base_string(buffer + from, to - from);
    }

   private:
    char* buffer;
  };
}

#endif
<|endoftext|>


<commit_before>//
// Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.
//

#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_

#include "utils/macros.hpp"

#ifndef AMD_PLATFORM_NAME
# define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME

#ifndef AMD_PLATFORM_BUILD_NUMBER
# define AMD_PLATFORM_BUILD_NUMBER 2225
#endif // AMD_PLATFORM_BUILD_NUMBER

#ifndef AMD_PLATFORM_REVISION_NUMBER
# define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER

#ifndef AMD_PLATFORM_RELEASE_INFO
# define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO

#define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \
    "." XSTR(AMD_PLATFORM_REVISION_NUMBER)

#ifndef AMD_PLATFORM_INFO
# define AMD_PLATFORM_INFO "AMD-APP" AMD_PLATFORM_RELEASE_INFO \
    DEBUG_ONLY("." IF(IS_OPTIMIZED,"opt","dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO

#endif // VERSIONS_HPP_
<commit_msg>P4 to Git Change 1318652 by johtaylo@johtaylo-jtincrementor-increment on 2016/09/26 03:00:04<commit_after>//
// Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.
//

#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_

#include "utils/macros.hpp"

#ifndef AMD_PLATFORM_NAME
# define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME

#ifndef AMD_PLATFORM_BUILD_NUMBER
# define AMD_PLATFORM_BUILD_NUMBER 2226
#endif // AMD_PLATFORM_BUILD_NUMBER

#ifndef AMD_PLATFORM_REVISION_NUMBER
# define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER

#ifndef AMD_PLATFORM_RELEASE_INFO
# define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO

#define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \
    "." XSTR(AMD_PLATFORM_REVISION_NUMBER)

#ifndef AMD_PLATFORM_INFO
# define AMD_PLATFORM_INFO "AMD-APP" AMD_PLATFORM_RELEASE_INFO \
    DEBUG_ONLY("." IF(IS_OPTIMIZED,"opt","dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO

#endif // VERSIONS_HPP_
<|endoftext|>


<commit_before>//
// Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.
//

#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_

#include "utils/macros.hpp"

#ifndef AMD_PLATFORM_NAME
# define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME

#ifndef AMD_PLATFORM_BUILD_NUMBER
# define AMD_PLATFORM_BUILD_NUMBER 1715
#endif // AMD_PLATFORM_BUILD_NUMBER

#ifndef AMD_PLATFORM_REVISION_NUMBER
# define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER

#ifndef AMD_PLATFORM_RELEASE_INFO
# define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO

#define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \
    "." XSTR(AMD_PLATFORM_REVISION_NUMBER)

#ifndef AMD_PLATFORM_INFO
# define AMD_PLATFORM_INFO "AMD-APP" AMD_PLATFORM_RELEASE_INFO \
    DEBUG_ONLY("." IF(IS_OPTIMIZED,"opt","dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO

#endif // VERSIONS_HPP_
<commit_msg>P4 to Git Change 1113116 by johtaylo@johtaylo-JTBUILDER03-increment on 2015/01/20 03:00:14<commit_after>//
// Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.
//

#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_

#include "utils/macros.hpp"

#ifndef AMD_PLATFORM_NAME
# define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME

#ifndef AMD_PLATFORM_BUILD_NUMBER
# define AMD_PLATFORM_BUILD_NUMBER 1716
#endif // AMD_PLATFORM_BUILD_NUMBER

#ifndef AMD_PLATFORM_REVISION_NUMBER
# define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER

#ifndef AMD_PLATFORM_RELEASE_INFO
# define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO

#define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \
    "." XSTR(AMD_PLATFORM_REVISION_NUMBER)

#ifndef AMD_PLATFORM_INFO
# define AMD_PLATFORM_INFO "AMD-APP" AMD_PLATFORM_RELEASE_INFO \
    DEBUG_ONLY("." IF(IS_OPTIMIZED,"opt","dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO

#endif // VERSIONS_HPP_
<|endoftext|>


<commit_before>//
// Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.
//

#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_

#include "utils/macros.hpp"

#ifndef AMD_PLATFORM_NAME
# define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME

#ifndef AMD_PLATFORM_BUILD_NUMBER
# define AMD_PLATFORM_BUILD_NUMBER 1594
#endif // AMD_PLATFORM_BUILD_NUMBER

#ifndef AMD_PLATFORM_REVISION_NUMBER
# define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER

#ifndef AMD_PLATFORM_RELEASE_INFO
# define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO

#define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \
    "." XSTR(AMD_PLATFORM_REVISION_NUMBER)

#ifndef AMD_PLATFORM_INFO
# define AMD_PLATFORM_INFO "AMD-APP" AMD_PLATFORM_RELEASE_INFO \
    DEBUG_ONLY("." IF(IS_OPTIMIZED,"opt","dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO

#endif // VERSIONS_HPP_
<commit_msg>P4 to Git Change 1058200 by johtaylo@johtaylo-JTBUILDER03-increment on 2014/07/23 03:00:12<commit_after>//
// Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.
//

#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_

#include "utils/macros.hpp"

#ifndef AMD_PLATFORM_NAME
# define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME

#ifndef AMD_PLATFORM_BUILD_NUMBER
# define AMD_PLATFORM_BUILD_NUMBER 1595
#endif // AMD_PLATFORM_BUILD_NUMBER

#ifndef AMD_PLATFORM_REVISION_NUMBER
# define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER

#ifndef AMD_PLATFORM_RELEASE_INFO
# define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO

#define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \
    "." XSTR(AMD_PLATFORM_REVISION_NUMBER)

#ifndef AMD_PLATFORM_INFO
# define AMD_PLATFORM_INFO "AMD-APP" AMD_PLATFORM_RELEASE_INFO \
    DEBUG_ONLY("." IF(IS_OPTIMIZED,"opt","dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO

#endif // VERSIONS_HPP_
<|endoftext|>


<commit_before>//
// Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.
//

#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_

#include "utils/macros.hpp"

#ifndef AMD_PLATFORM_NAME
# define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME

#ifndef AMD_PLATFORM_BUILD_NUMBER
# define AMD_PLATFORM_BUILD_NUMBER 2204
#endif // AMD_PLATFORM_BUILD_NUMBER

#ifndef AMD_PLATFORM_REVISION_NUMBER
# define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER

#ifndef AMD_PLATFORM_RELEASE_INFO
# define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO

#define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \
    "." XSTR(AMD_PLATFORM_REVISION_NUMBER)

#ifndef AMD_PLATFORM_INFO
# define AMD_PLATFORM_INFO "AMD-APP" AMD_PLATFORM_RELEASE_INFO \
    DEBUG_ONLY("." IF(IS_OPTIMIZED,"opt","dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO

#endif // VERSIONS_HPP_
<commit_msg>P4 to Git Change 1305891 by johtaylo@johtaylo-JTBUILDER03-increment on 2016/08/23 03:00:09<commit_after>//
// Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.
//

#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_

#include "utils/macros.hpp"

#ifndef AMD_PLATFORM_NAME
# define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME

#ifndef AMD_PLATFORM_BUILD_NUMBER
# define AMD_PLATFORM_BUILD_NUMBER 2205
#endif // AMD_PLATFORM_BUILD_NUMBER

#ifndef AMD_PLATFORM_REVISION_NUMBER
# define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER

#ifndef AMD_PLATFORM_RELEASE_INFO
# define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO

#define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \
    "." XSTR(AMD_PLATFORM_REVISION_NUMBER)

#ifndef AMD_PLATFORM_INFO
# define AMD_PLATFORM_INFO "AMD-APP" AMD_PLATFORM_RELEASE_INFO \
    DEBUG_ONLY("." IF(IS_OPTIMIZED,"opt","dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO

#endif // VERSIONS_HPP_
<|endoftext|>


<commit_before>//
// Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.
//

#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_

#include "utils/macros.hpp"

#ifndef AMD_PLATFORM_NAME
# define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME

#ifndef AMD_PLATFORM_BUILD_NUMBER
# define AMD_PLATFORM_BUILD_NUMBER 1931
#endif // AMD_PLATFORM_BUILD_NUMBER

#ifndef AMD_PLATFORM_REVISION_NUMBER
# define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER

#ifndef AMD_PLATFORM_RELEASE_INFO
# define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO

#define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \
    "." XSTR(AMD_PLATFORM_REVISION_NUMBER)

#ifndef AMD_PLATFORM_INFO
# define AMD_PLATFORM_INFO "AMD-APP" AMD_PLATFORM_RELEASE_INFO \
    DEBUG_ONLY("." IF(IS_OPTIMIZED,"opt","dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO

#endif // VERSIONS_HPP_
<commit_msg>P4 to Git Change 1206344 by johtaylo@johtaylo-JTBUILDER03-increment on 2015/11/02 03:00:11<commit_after>//
// Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.
//

#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_

#include "utils/macros.hpp"

#ifndef AMD_PLATFORM_NAME
# define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME

#ifndef AMD_PLATFORM_BUILD_NUMBER
# define AMD_PLATFORM_BUILD_NUMBER 1932
#endif // AMD_PLATFORM_BUILD_NUMBER

#ifndef AMD_PLATFORM_REVISION_NUMBER
# define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER

#ifndef AMD_PLATFORM_RELEASE_INFO
# define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO

#define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \
    "." XSTR(AMD_PLATFORM_REVISION_NUMBER)

#ifndef AMD_PLATFORM_INFO
# define AMD_PLATFORM_INFO "AMD-APP" AMD_PLATFORM_RELEASE_INFO \
    DEBUG_ONLY("." IF(IS_OPTIMIZED,"opt","dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO

#endif // VERSIONS_HPP_
<|endoftext|>


<commit_before>//
// Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.
//

#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_

#include "utils/macros.hpp"

#ifndef AMD_PLATFORM_NAME
#define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif  // AMD_PLATFORM_NAME

#ifndef AMD_PLATFORM_BUILD_NUMBER
#define AMD_PLATFORM_BUILD_NUMBER 3032
#endif  // AMD_PLATFORM_BUILD_NUMBER

#ifndef AMD_PLATFORM_REVISION_NUMBER
#define AMD_PLATFORM_REVISION_NUMBER 0
#endif  // AMD_PLATFORM_REVISION_NUMBER

#ifndef AMD_PLATFORM_RELEASE_INFO
#define AMD_PLATFORM_RELEASE_INFO
#endif  // AMD_PLATFORM_RELEASE_INFO

#define AMD_BUILD_STRING                                                                           \
  XSTR(AMD_PLATFORM_BUILD_NUMBER)                                                                  \
  "." XSTR(AMD_PLATFORM_REVISION_NUMBER)

#ifndef AMD_PLATFORM_INFO
#define AMD_PLATFORM_INFO                                                                          \
  "AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY(                                                  \
      "." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")"
#endif  // ATI_PLATFORM_INFO

#endif  // VERSIONS_HPP_
<commit_msg>P4 to Git Change 2026403 by chui@ocl-promo-incrementor on 2019/11/07 03:00:05<commit_after>//
// Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.
//

#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_

#include "utils/macros.hpp"

#ifndef AMD_PLATFORM_NAME
#define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif  // AMD_PLATFORM_NAME

#ifndef AMD_PLATFORM_BUILD_NUMBER
#define AMD_PLATFORM_BUILD_NUMBER 3033
#endif  // AMD_PLATFORM_BUILD_NUMBER

#ifndef AMD_PLATFORM_REVISION_NUMBER
#define AMD_PLATFORM_REVISION_NUMBER 0
#endif  // AMD_PLATFORM_REVISION_NUMBER

#ifndef AMD_PLATFORM_RELEASE_INFO
#define AMD_PLATFORM_RELEASE_INFO
#endif  // AMD_PLATFORM_RELEASE_INFO

#define AMD_BUILD_STRING                                                                           \
  XSTR(AMD_PLATFORM_BUILD_NUMBER)                                                                  \
  "." XSTR(AMD_PLATFORM_REVISION_NUMBER)

#ifndef AMD_PLATFORM_INFO
#define AMD_PLATFORM_INFO                                                                          \
  "AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY(                                                  \
      "." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")"
#endif  // ATI_PLATFORM_INFO

#endif  // VERSIONS_HPP_
<|endoftext|>


<commit_before>//
// Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.
//

#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_

#include "utils/macros.hpp"

#ifndef AMD_PLATFORM_NAME
#define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif  // AMD_PLATFORM_NAME

#ifndef AMD_PLATFORM_BUILD_NUMBER
#define AMD_PLATFORM_BUILD_NUMBER 2565
#endif  // AMD_PLATFORM_BUILD_NUMBER

#ifndef AMD_PLATFORM_REVISION_NUMBER
#define AMD_PLATFORM_REVISION_NUMBER 0
#endif  // AMD_PLATFORM_REVISION_NUMBER

#ifndef AMD_PLATFORM_RELEASE_INFO
#define AMD_PLATFORM_RELEASE_INFO
#endif  // AMD_PLATFORM_RELEASE_INFO

#define AMD_BUILD_STRING                                                                           \
  XSTR(AMD_PLATFORM_BUILD_NUMBER)                                                                  \
  "." XSTR(AMD_PLATFORM_REVISION_NUMBER)

#ifndef AMD_PLATFORM_INFO
#define AMD_PLATFORM_INFO                                                                          \
  "AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY(                                                  \
      "." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")"
#endif  // ATI_PLATFORM_INFO

#endif  // VERSIONS_HPP_
<commit_msg>P4 to Git Change 1499779 by johtaylo@johtaylo-jtincrementor2-increment on 2018/01/04 03:00:04<commit_after>//
// Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.
//

#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_

#include "utils/macros.hpp"

#ifndef AMD_PLATFORM_NAME
#define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif  // AMD_PLATFORM_NAME

#ifndef AMD_PLATFORM_BUILD_NUMBER
#define AMD_PLATFORM_BUILD_NUMBER 2566
#endif  // AMD_PLATFORM_BUILD_NUMBER

#ifndef AMD_PLATFORM_REVISION_NUMBER
#define AMD_PLATFORM_REVISION_NUMBER 0
#endif  // AMD_PLATFORM_REVISION_NUMBER

#ifndef AMD_PLATFORM_RELEASE_INFO
#define AMD_PLATFORM_RELEASE_INFO
#endif  // AMD_PLATFORM_RELEASE_INFO

#define AMD_BUILD_STRING                                                                           \
  XSTR(AMD_PLATFORM_BUILD_NUMBER)                                                                  \
  "." XSTR(AMD_PLATFORM_REVISION_NUMBER)

#ifndef AMD_PLATFORM_INFO
#define AMD_PLATFORM_INFO                                                                          \
  "AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY(                                                  \
      "." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")"
#endif  // ATI_PLATFORM_INFO

#endif  // VERSIONS_HPP_
<|endoftext|>


<commit_before>// Copyright (c) 2011, 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 "vm/disassembler.h"

#include "vm/assembler.h"
#include "vm/globals.h"
#include "vm/os.h"
#include "vm/log.h"
#include "vm/json_stream.h"

namespace dart {

void DisassembleToStdout::ConsumeInstruction(char* hex_buffer,
                                             intptr_t hex_size,
                                             char* human_buffer,
                                             intptr_t human_size,
                                             uword pc) {
  static const int kHexColumnWidth = 23;
  uint8_t* pc_ptr = reinterpret_cast<uint8_t*>(pc);
  ISL_Print("%p    %s", pc_ptr, hex_buffer);
  int hex_length = strlen(hex_buffer);
  if (hex_length < kHexColumnWidth) {
    for (int i = kHexColumnWidth - hex_length; i > 0; i--) {
      ISL_Print(" ");
    }
  }
  ISL_Print("%s", human_buffer);
  ISL_Print("\n");
}

void DisassembleToStdout::Print(const char* format, ...) {
  va_list args;
  va_start(args, format);
  OS::VFPrint(stdout, format, args);
  va_end(args);
}

void DisassembleToJSONStream::ConsumeInstruction(char* hex_buffer,
                                                 intptr_t hex_size,
                                                 char* human_buffer,
                                                 intptr_t human_size,
                                                 uword pc) {
  uint8_t* pc_ptr = reinterpret_cast<uint8_t*>(pc);
  // Instructions are represented as three consecutive values in a JSON array.
  // All three are strings. The first is the address of the instruction,
  // the second is the hex string of the code, and the final is a human
  // readable string.
  jsarr_.AddValueF("%p", pc_ptr);
  jsarr_.AddValue(hex_buffer);
  jsarr_.AddValue(human_buffer);
}

void DisassembleToJSONStream::Print(const char* format, ...) {
  va_list args;
  va_start(args, format);
  intptr_t len = OS::VSNPrint(NULL, 0, format, args);
  va_end(args);
  char* p = reinterpret_cast<char*>(malloc(len+1));
  va_start(args, format);
  intptr_t len2 = OS::VSNPrint(p, len, format, args);
  va_end(args);
  ASSERT(len == len2);
  for (intptr_t i = 0; i < len; i++) {
    if (p[i] == '\n' || p[i] == '\r') {
      p[i] = ' ';
    }
  }
  // Instructions are represented as three consecutive values in a JSON array.
  // All three are strings. Comments only use the third slot. See above comment
  // for more information.
  jsarr_.AddValue("");
  jsarr_.AddValue("");
  jsarr_.AddValue(p);
  free(p);
}

class FindAddrVisitor : public FindObjectVisitor {
 public:
  explicit FindAddrVisitor(uword addr)
      : FindObjectVisitor(Isolate::Current()), addr_(addr) { }
  virtual ~FindAddrVisitor() { }

  virtual uword filter_addr() const { return addr_; }

  // Check if object matches find condition.
  virtual bool FindObject(RawObject* obj) const {
    return obj == reinterpret_cast<RawObject*>(addr_);
  }

 private:
  const uword addr_;

  DISALLOW_COPY_AND_ASSIGN(FindAddrVisitor);
};

bool Disassembler::CanFindOldObject(uword addr) {
  FindAddrVisitor visitor(addr);
  NoGCScope no_gc;
  return Isolate::Current()->heap()->FindOldObject(&visitor) != Object::null();
}

void Disassembler::Disassemble(uword start,
                               uword end,
                               DisassemblyFormatter* formatter,
                               const Code& code) {
  const Code::Comments& comments =
      code.IsNull() ? Code::Comments::New(0) : code.comments();
  ASSERT(formatter != NULL);
  char hex_buffer[kHexadecimalBufferSize];  // Instruction in hexadecimal form.
  char human_buffer[kUserReadableBufferSize];  // Human-readable instruction.
  uword pc = start;
  intptr_t comment_finger = 0;
  GrowableArray<Function*> inlined_functions;
  while (pc < end) {
    const intptr_t offset = pc - start;
    const intptr_t old_comment_finger = comment_finger;
    while (comment_finger < comments.Length() &&
           comments.PCOffsetAt(comment_finger) <= offset) {
      formatter->Print(
          "        ;; %s\n",
          String::Handle(comments.CommentAt(comment_finger)).ToCString());
      comment_finger++;
    }
    if (old_comment_finger != comment_finger) {
      // Comment emitted, emit inlining information.
      code.GetInlinedFunctionsAt(offset, &inlined_functions);
      // Skip top scope function printing.
      for (intptr_t i = 1; i < inlined_functions.length(); i++) {
        if (i == 1) {
          formatter->Print("        ;; Inlined ");
        }
        formatter->Print("-> %s ", inlined_functions[i]->ToQualifiedCString());
      }
      if (inlined_functions.length() > 1) {
        formatter->Print("\n");
      }
    }
    int instruction_length;
    DecodeInstruction(hex_buffer,
                      sizeof(hex_buffer),
                      human_buffer,
                      sizeof(human_buffer),
                      &instruction_length, pc);
    formatter->ConsumeInstruction(hex_buffer,
                                  sizeof(hex_buffer),
                                  human_buffer,
                                  sizeof(human_buffer),
                                  pc);
    pc += instruction_length;
  }
}

}  // namespace dart
<commit_msg>Fix disassembly comments<commit_after>// Copyright (c) 2011, 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 "vm/disassembler.h"

#include "vm/assembler.h"
#include "vm/globals.h"
#include "vm/os.h"
#include "vm/log.h"
#include "vm/json_stream.h"

namespace dart {

void DisassembleToStdout::ConsumeInstruction(char* hex_buffer,
                                             intptr_t hex_size,
                                             char* human_buffer,
                                             intptr_t human_size,
                                             uword pc) {
  static const int kHexColumnWidth = 23;
  uint8_t* pc_ptr = reinterpret_cast<uint8_t*>(pc);
  ISL_Print("%p    %s", pc_ptr, hex_buffer);
  int hex_length = strlen(hex_buffer);
  if (hex_length < kHexColumnWidth) {
    for (int i = kHexColumnWidth - hex_length; i > 0; i--) {
      ISL_Print(" ");
    }
  }
  ISL_Print("%s", human_buffer);
  ISL_Print("\n");
}

void DisassembleToStdout::Print(const char* format, ...) {
  va_list args;

  va_start(args, format);
  intptr_t len = OS::VSNPrint(NULL, 0, format, args);
  va_end(args);

  char* p = reinterpret_cast<char*>(malloc(len+1));
  va_start(args, format);
  OS::VSNPrint(p, len, format, args);
  va_end(args);

  ISL_Print("%s", p);
  free(p);
}

void DisassembleToJSONStream::ConsumeInstruction(char* hex_buffer,
                                                 intptr_t hex_size,
                                                 char* human_buffer,
                                                 intptr_t human_size,
                                                 uword pc) {
  uint8_t* pc_ptr = reinterpret_cast<uint8_t*>(pc);
  // Instructions are represented as three consecutive values in a JSON array.
  // All three are strings. The first is the address of the instruction,
  // the second is the hex string of the code, and the final is a human
  // readable string.
  jsarr_.AddValueF("%p", pc_ptr);
  jsarr_.AddValue(hex_buffer);
  jsarr_.AddValue(human_buffer);
}

void DisassembleToJSONStream::Print(const char* format, ...) {
  va_list args;
  va_start(args, format);
  intptr_t len = OS::VSNPrint(NULL, 0, format, args);
  va_end(args);
  char* p = reinterpret_cast<char*>(malloc(len+1));
  va_start(args, format);
  intptr_t len2 = OS::VSNPrint(p, len, format, args);
  va_end(args);
  ASSERT(len == len2);
  for (intptr_t i = 0; i < len; i++) {
    if (p[i] == '\n' || p[i] == '\r') {
      p[i] = ' ';
    }
  }
  // Instructions are represented as three consecutive values in a JSON array.
  // All three are strings. Comments only use the third slot. See above comment
  // for more information.
  jsarr_.AddValue("");
  jsarr_.AddValue("");
  jsarr_.AddValue(p);
  free(p);
}

class FindAddrVisitor : public FindObjectVisitor {
 public:
  explicit FindAddrVisitor(uword addr)
      : FindObjectVisitor(Isolate::Current()), addr_(addr) { }
  virtual ~FindAddrVisitor() { }

  virtual uword filter_addr() const { return addr_; }

  // Check if object matches find condition.
  virtual bool FindObject(RawObject* obj) const {
    return obj == reinterpret_cast<RawObject*>(addr_);
  }

 private:
  const uword addr_;

  DISALLOW_COPY_AND_ASSIGN(FindAddrVisitor);
};

bool Disassembler::CanFindOldObject(uword addr) {
  FindAddrVisitor visitor(addr);
  NoGCScope no_gc;
  return Isolate::Current()->heap()->FindOldObject(&visitor) != Object::null();
}

void Disassembler::Disassemble(uword start,
                               uword end,
                               DisassemblyFormatter* formatter,
                               const Code& code) {
  const Code::Comments& comments =
      code.IsNull() ? Code::Comments::New(0) : code.comments();
  ASSERT(formatter != NULL);
  char hex_buffer[kHexadecimalBufferSize];  // Instruction in hexadecimal form.
  char human_buffer[kUserReadableBufferSize];  // Human-readable instruction.
  uword pc = start;
  intptr_t comment_finger = 0;
  GrowableArray<Function*> inlined_functions;
  while (pc < end) {
    const intptr_t offset = pc - start;
    const intptr_t old_comment_finger = comment_finger;
    while (comment_finger < comments.Length() &&
           comments.PCOffsetAt(comment_finger) <= offset) {
      formatter->Print(
          "        ;; %s\n",
          String::Handle(comments.CommentAt(comment_finger)).ToCString());
      comment_finger++;
    }
    if (old_comment_finger != comment_finger) {
      // Comment emitted, emit inlining information.
      code.GetInlinedFunctionsAt(offset, &inlined_functions);
      // Skip top scope function printing.
      for (intptr_t i = 1; i < inlined_functions.length(); i++) {
        if (i == 1) {
          formatter->Print("        ;; Inlined ");
        }
        formatter->Print("-> %s ", inlined_functions[i]->ToQualifiedCString());
      }
      if (inlined_functions.length() > 1) {
        formatter->Print("\n");
      }
    }
    int instruction_length;
    DecodeInstruction(hex_buffer,
                      sizeof(hex_buffer),
                      human_buffer,
                      sizeof(human_buffer),
                      &instruction_length, pc);
    formatter->ConsumeInstruction(hex_buffer,
                                  sizeof(hex_buffer),
                                  human_buffer,
                                  sizeof(human_buffer),
                                  pc);
    pc += instruction_length;
  }
}

}  // namespace dart
<|endoftext|>


<commit_before><commit_msg>Testcase for YIELDMAT<commit_after><|endoftext|>


<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** 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.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/

#include "itemlibrary.h"

#include "itemlibrarymodel.h"
#include "customdraganddrop.h"

#include "ui_itemlibrary.h"
#include <metainfo.h>
#include <itemlibraryinfo.h>
#include <formeditorscene.h>

#include <QtCore/QDebug>
#include <QtGui/QContextMenuEvent>
#include <QtGui/QMenu>
#include <QtGui/QAction>
#include <QtGui/QGraphicsView>
#include <QtGui/QGraphicsScene>
#include <QtGui/QGraphicsItem>
#include <QtGui/QPixmap>
#include <QSortFilterProxyModel>
#include <QLabel>
#include <QMainWindow>
#include <QMenuBar>
#include <QFile>
#include <QDirModel>
#include <QFileIconProvider>

namespace QmlDesigner {

class MyFileIconProvider : public QFileIconProvider
{
public:
    MyFileIconProvider() : QFileIconProvider()
    {}
    virtual QIcon icon ( const QFileInfo & info ) const
    {
        QPixmap pixmap(info.absoluteFilePath());
        if (pixmap.isNull())
            return QFileIconProvider::icon(info);
        else return pixmap; //pixmap.scaled(128, 128, Qt::KeepAspectRatio);
    }
};

class GrabHelper {
    Q_DISABLE_COPY(GrabHelper)
public:
    GrabHelper();
    QPixmap grabItem(QGraphicsItem *item);

private:
    QGraphicsScene m_scene;
    QGraphicsView m_view;
};

GrabHelper::GrabHelper()
{
    m_view.setScene(&m_scene);
    m_view.setFrameShape(QFrame::NoFrame);
    m_view.setAlignment(Qt::AlignLeft|Qt::AlignTop);
    m_view.setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    m_view.setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
}

QPixmap GrabHelper::grabItem(QGraphicsItem *item)
{
    if (item->scene()) {
        qWarning("%s: WARNING: Attempt to grab item that is part of another scene!", Q_FUNC_INFO);
        return QPixmap();
    }
    // Temporarily add the item, resize the view widget and grab it.
    m_scene.addItem(item);
    item->setPos(0.0, 0.0);
    const QSize size = item->boundingRect().size().toSize();
    QPixmap rc;
    if (!size.isEmpty()) { // We have seen horses barf...
        m_view.resize(size);
        rc = QPixmap::grabWidget(&m_view);
    }
    m_scene.removeItem(item);
    return rc;
}

// ---------- ItemLibraryPrivate
class ItemLibraryPrivate {
public:
    ItemLibraryPrivate(QObject *object);
    ~ItemLibraryPrivate();

    Ui::ItemLibrary m_ui;
    Internal::ItemLibraryModel *m_itemLibraryModel;
    QDirModel *m_resourcesDirModel;
    QSortFilterProxyModel *m_filterProxy;
    GrabHelper *m_grabHelper;
    QString m_resourcePath;
};

ItemLibraryPrivate::ItemLibraryPrivate(QObject *object) :
    m_itemLibraryModel(0),
    m_grabHelper(0)
{
    m_resourcePath = QDir::currentPath();
    Q_UNUSED(object);
}

ItemLibraryPrivate::~ItemLibraryPrivate()
{
    delete m_grabHelper;
}

ItemLibrary::ItemLibrary(QWidget *parent) :
    QFrame(parent),
    m_d(new ItemLibraryPrivate(this))
{
    m_d->m_ui.setupUi(this);
    m_d->m_itemLibraryModel = new Internal::ItemLibraryModel(this);
    m_d->m_resourcesDirModel = new QDirModel(this);
    m_d->m_filterProxy = new QSortFilterProxyModel(this);
    m_d->m_filterProxy->setSourceModel(m_d->m_itemLibraryModel);
    m_d->m_ui.ItemLibraryTreeView->setModel(m_d->m_filterProxy);
    m_d->m_filterProxy->setDynamicSortFilter(true);
    m_d->m_ui.ItemLibraryTreeView->setRealModel(m_d->m_itemLibraryModel);
    m_d->m_ui.ItemLibraryTreeView->setIconSize(QSize(64, 64));
    m_d->m_ui.ItemLibraryTreeView->setSortingEnabled(true);
    m_d->m_ui.ItemLibraryTreeView->setHeaderHidden(true);
    m_d->m_ui.ItemLibraryTreeView->setIndentation(10);
    m_d->m_ui.ItemLibraryTreeView->setAnimated(true);
    m_d->m_ui.ItemLibraryTreeView->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
    m_d->m_ui.ItemLibraryTreeView->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    m_d->m_ui.ItemLibraryTreeView->setAttribute(Qt::WA_MacShowFocusRect, false);
    m_d->m_filterProxy->setFilterCaseSensitivity(Qt::CaseInsensitive);
    m_d->m_filterProxy->setFilterRole(Qt::UserRole);
    m_d->m_filterProxy->setSortRole(Qt::DisplayRole);
    connect(m_d->m_ui.lineEdit, SIGNAL(textChanged(QString)), m_d->m_filterProxy, SLOT(setFilterRegExp(QString)));
    connect(m_d->m_ui.lineEdit, SIGNAL(textChanged(QString)), this, SLOT(setNameFilter(QString)));
    connect(m_d->m_ui.lineEdit, SIGNAL(textChanged(QString)), this, SLOT(expandAll()));
    connect(m_d->m_ui.buttonItems, SIGNAL(toggled (bool)), this, SLOT(itemLibraryButton()));
    connect(m_d->m_ui.buttonResources, SIGNAL(toggled (bool)), this, SLOT(resourcesButton()));
    connect(m_d->m_ui.ItemLibraryTreeView, SIGNAL(itemActivated(const QString&)), this, SIGNAL(itemActivated(const QString&)));
    m_d->m_ui.lineEdit->setDragEnabled(false);
    setNameFilter("");

    MyFileIconProvider *fileIconProvider = new MyFileIconProvider();
    m_d->m_resourcesDirModel->setIconProvider(fileIconProvider);

    setWindowTitle(tr("Library", "Title of library view"));

    {
        QFile file(":/qmldesigner/stylesheet.css");
        file.open(QFile::ReadOnly);
        QString styleSheet = QLatin1String(file.readAll());
        setStyleSheet(styleSheet);

        QFile fileTool(":/qmldesigner/toolbutton.css");
        fileTool.open(QFile::ReadOnly);
        styleSheet = QLatin1String(fileTool.readAll());
        m_d->m_ui.buttonItems->setStyleSheet(styleSheet);
        m_d->m_ui.buttonResources->setStyleSheet(styleSheet);
    }

    {
        QFile file(":/qmldesigner/scrollbar.css");
        file.open(QFile::ReadOnly);
        QString styleSheet = QLatin1String(file.readAll());
        m_d->m_ui.ItemLibraryTreeView->setStyleSheet(styleSheet);
    }

    m_d->m_ui.buttonItems->setChecked(true);
}

ItemLibrary::~ItemLibrary()
{
    delete m_d;
}

void ItemLibrary::setNameFilter(const QString &nameFilter)
{
    QStringList nameFilterList;
    nameFilterList.append(nameFilter + "*.gif");
    nameFilterList.append(nameFilter + "*.png");
    nameFilterList.append(nameFilter + "*.jpg");
    nameFilterList.append(nameFilter + "*.");
    m_d->m_resourcesDirModel->setFilter(QDir::AllDirs | QDir::Files | QDir::NoDotAndDotDot);
    m_d->m_resourcesDirModel->setNameFilters(nameFilterList);
    m_d->m_ui.ItemLibraryTreeView->setRootIndex(m_d->m_resourcesDirModel->index(m_d->m_resourcePath));
}

void ItemLibrary::itemLibraryButton()
{
    if (m_d->m_ui.buttonItems->isChecked()) {
        m_d->m_filterProxy->setSourceModel(m_d->m_itemLibraryModel);
        m_d->m_ui.ItemLibraryTreeView->setModel(m_d->m_filterProxy);
        m_d->m_ui.ItemLibraryTreeView->setIconSize(QSize(64, 64));
        m_d->m_ui.buttonResources->setChecked(false);
        m_d->m_ui.ItemLibraryTreeView->setRealModel(m_d->m_itemLibraryModel);
        expandAll();
    }
}

void ItemLibrary::resourcesButton()
{
    if (m_d->m_ui.buttonResources->isChecked()) {
        m_d->m_ui.ItemLibraryTreeView->setModel(m_d->m_resourcesDirModel);
        m_d->m_ui.ItemLibraryTreeView->setIconSize(QSize(32, 32));
        m_d->m_ui.buttonItems->setChecked(false);
        m_d->m_ui.ItemLibraryTreeView->setRootIndex(m_d->m_resourcesDirModel->index(m_d->m_resourcePath));
        m_d->m_ui.ItemLibraryTreeView->setColumnHidden(1, true);
        m_d->m_ui.ItemLibraryTreeView->setColumnHidden(2, true);
        m_d->m_ui.ItemLibraryTreeView->setColumnHidden(3, true);
        expandAll();
    }
}

void ItemLibrary::addItemLibraryInfo(const ItemLibraryInfo &itemLibraryInfo)
{
    m_d->m_itemLibraryModel->addItemLibraryInfo(itemLibraryInfo);
}

void ItemLibrary::setResourcePath(const QString &resourcePath)
{
    m_d->m_resourcePath = resourcePath;
}

void ItemLibrary::setMetaInfo(const MetaInfo &metaInfo)
{
    m_d->m_itemLibraryModel->clear();

    foreach (const QString &type, metaInfo.itemLibraryItems()) {
        NodeMetaInfo nodeInfo = metaInfo.nodeMetaInfo(type);

        QList<ItemLibraryInfo> itemLibraryRepresentationList = metaInfo.itemLibraryRepresentations(nodeInfo);

        if (!metaInfo.hasNodeMetaInfo(type))
            qWarning() << "ItemLibrary: type not declared: " << type;
        if (!itemLibraryRepresentationList.isEmpty() && metaInfo.hasNodeMetaInfo(type)) {
            foreach (ItemLibraryInfo itemLibraryRepresentation, itemLibraryRepresentationList) {
                QImage image(64, 64, QImage::Format_RGB32); // = m_d->m_queryView->paintObject(nodeInfo, itemLibraryRepresentation.properties()); TODO
                if (!image.isNull()) {
                    QPainter p(&image);
                    QPen pen(Qt::gray);
                    pen.setWidth(2);
                    p.setPen(pen);
                    p.drawRect(1, 1, image.width() - 2, image.height() - 2);
                }
                QIcon icon = itemLibraryRepresentation.icon();
                if (itemLibraryRepresentation.icon().isNull())
                    itemLibraryRepresentation.setIcon(QIcon(":/ItemLibrary/images/default-icon.png"));

                if (itemLibraryRepresentation.category().isEmpty())
                    itemLibraryRepresentation.setCategory(nodeInfo.category());
                if (!image.isNull()) {
                    itemLibraryRepresentation.setDragIcon(QPixmap::fromImage(image));
                    addItemLibraryInfo(itemLibraryRepresentation);
                }
            }
        } else {
            QImage image; // = m_d->m_queryView->paintObject(nodeInfo); TODO we have to render image
            QIcon icon = nodeInfo.icon();
            if (icon.isNull())
                icon = QIcon(":/ItemLibrary/images/default-icon.png");

            ItemLibraryInfo itemLibraryInfo;
            itemLibraryInfo.setName(type);
            itemLibraryInfo.setTypeName(nodeInfo.typeName());
            itemLibraryInfo.setCategory(nodeInfo.category());
            itemLibraryInfo.setIcon(icon);
            itemLibraryInfo.setMajorVersion(nodeInfo.majorVersion());
            itemLibraryInfo.setMinorVersion(nodeInfo.minorVersion());
            itemLibraryInfo.setDragIcon(QPixmap::fromImage(image));
            addItemLibraryInfo(itemLibraryInfo);
        }
    }
    expandAll();
}

void ItemLibrary::expandAll()
{
    m_d->m_ui.ItemLibraryTreeView->expandToDepth(1);
}

void ItemLibrary::contextMenuEvent (QContextMenuEvent *event)
{
    event->accept();
    QMenu menu;
    menu.addAction(tr("About plugins..."));
    menu.exec(event->globalPos());
}

}
<commit_msg>Fix runtime warning<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** 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.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/

#include "itemlibrary.h"

#include "itemlibrarymodel.h"
#include "customdraganddrop.h"

#include "ui_itemlibrary.h"
#include <metainfo.h>
#include <itemlibraryinfo.h>
#include <formeditorscene.h>

#include <QtCore/QDebug>
#include <QtGui/QContextMenuEvent>
#include <QtGui/QMenu>
#include <QtGui/QAction>
#include <QtGui/QGraphicsView>
#include <QtGui/QGraphicsScene>
#include <QtGui/QGraphicsItem>
#include <QtGui/QPixmap>
#include <QSortFilterProxyModel>
#include <QLabel>
#include <QMainWindow>
#include <QMenuBar>
#include <QFile>
#include <QDirModel>
#include <QFileIconProvider>

namespace QmlDesigner {

class MyFileIconProvider : public QFileIconProvider
{
public:
    MyFileIconProvider() : QFileIconProvider()
    {}
    virtual QIcon icon ( const QFileInfo & info ) const
    {
        QPixmap pixmap(info.absoluteFilePath());
        if (pixmap.isNull())
            return QFileIconProvider::icon(info);
        else return pixmap; //pixmap.scaled(128, 128, Qt::KeepAspectRatio);
    }
};

class GrabHelper {
    Q_DISABLE_COPY(GrabHelper)
public:
    GrabHelper();
    QPixmap grabItem(QGraphicsItem *item);

private:
    QGraphicsScene m_scene;
    QGraphicsView m_view;
};

GrabHelper::GrabHelper()
{
    m_view.setScene(&m_scene);
    m_view.setFrameShape(QFrame::NoFrame);
    m_view.setAlignment(Qt::AlignLeft|Qt::AlignTop);
    m_view.setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    m_view.setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
}

QPixmap GrabHelper::grabItem(QGraphicsItem *item)
{
    if (item->scene()) {
        qWarning("%s: WARNING: Attempt to grab item that is part of another scene!", Q_FUNC_INFO);
        return QPixmap();
    }
    // Temporarily add the item, resize the view widget and grab it.
    m_scene.addItem(item);
    item->setPos(0.0, 0.0);
    const QSize size = item->boundingRect().size().toSize();
    QPixmap rc;
    if (!size.isEmpty()) { // We have seen horses barf...
        m_view.resize(size);
        rc = QPixmap::grabWidget(&m_view);
    }
    m_scene.removeItem(item);
    return rc;
}

// ---------- ItemLibraryPrivate
class ItemLibraryPrivate {
public:
    ItemLibraryPrivate(QObject *object);
    ~ItemLibraryPrivate();

    Ui::ItemLibrary m_ui;
    Internal::ItemLibraryModel *m_itemLibraryModel;
    QDirModel *m_resourcesDirModel;
    QSortFilterProxyModel *m_filterProxy;
    GrabHelper *m_grabHelper;
    QString m_resourcePath;
};

ItemLibraryPrivate::ItemLibraryPrivate(QObject *object) :
    m_itemLibraryModel(0),
    m_grabHelper(0)
{
    m_resourcePath = QDir::currentPath();
    Q_UNUSED(object);
}

ItemLibraryPrivate::~ItemLibraryPrivate()
{
    delete m_grabHelper;
}

ItemLibrary::ItemLibrary(QWidget *parent) :
    QFrame(parent),
    m_d(new ItemLibraryPrivate(this))
{
    m_d->m_ui.setupUi(this);
    m_d->m_itemLibraryModel = new Internal::ItemLibraryModel(this);
    m_d->m_resourcesDirModel = new QDirModel(this);
    m_d->m_filterProxy = new QSortFilterProxyModel(this);
    m_d->m_filterProxy->setSourceModel(m_d->m_itemLibraryModel);
    m_d->m_ui.ItemLibraryTreeView->setModel(m_d->m_filterProxy);
    m_d->m_filterProxy->setDynamicSortFilter(true);
    m_d->m_ui.ItemLibraryTreeView->setRealModel(m_d->m_itemLibraryModel);
    m_d->m_ui.ItemLibraryTreeView->setIconSize(QSize(64, 64));
    m_d->m_ui.ItemLibraryTreeView->setSortingEnabled(true);
    m_d->m_ui.ItemLibraryTreeView->setHeaderHidden(true);
    m_d->m_ui.ItemLibraryTreeView->setIndentation(10);
    m_d->m_ui.ItemLibraryTreeView->setAnimated(true);
    m_d->m_ui.ItemLibraryTreeView->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
    m_d->m_ui.ItemLibraryTreeView->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    m_d->m_ui.ItemLibraryTreeView->setAttribute(Qt::WA_MacShowFocusRect, false);
    m_d->m_filterProxy->setFilterCaseSensitivity(Qt::CaseInsensitive);
    m_d->m_filterProxy->setFilterRole(Qt::UserRole);
    m_d->m_filterProxy->setSortRole(Qt::DisplayRole);
    connect(m_d->m_ui.lineEdit, SIGNAL(textChanged(QString)), m_d->m_filterProxy, SLOT(setFilterRegExp(QString)));
    connect(m_d->m_ui.lineEdit, SIGNAL(textChanged(QString)), this, SLOT(setNameFilter(QString)));
    connect(m_d->m_ui.lineEdit, SIGNAL(textChanged(QString)), this, SLOT(expandAll()));
    connect(m_d->m_ui.buttonItems, SIGNAL(toggled (bool)), this, SLOT(itemLibraryButton()));
    connect(m_d->m_ui.buttonResources, SIGNAL(toggled (bool)), this, SLOT(resourcesButton()));
    connect(m_d->m_ui.ItemLibraryTreeView, SIGNAL(itemActivated(const QString&)), this, SIGNAL(itemActivated(const QString&)));
    m_d->m_ui.lineEdit->setDragEnabled(false);
    setNameFilter("");

    MyFileIconProvider *fileIconProvider = new MyFileIconProvider();
    m_d->m_resourcesDirModel->setIconProvider(fileIconProvider);

    setWindowTitle(tr("Library", "Title of library view"));

    {
        QFile file(":/qmldesigner/stylesheet.css");
        file.open(QFile::ReadOnly);
        QString styleSheet = QLatin1String(file.readAll());
        setStyleSheet(styleSheet);

        QFile fileTool(":/qmldesigner/toolbutton.css");
        fileTool.open(QFile::ReadOnly);
        styleSheet = QLatin1String(fileTool.readAll());
        m_d->m_ui.buttonItems->setStyleSheet(styleSheet);
        m_d->m_ui.buttonResources->setStyleSheet(styleSheet);
    }

    {
        QFile file(":/qmldesigner/scrollbar.css");
        file.open(QFile::ReadOnly);
        QString styleSheet = QLatin1String(file.readAll());
        m_d->m_ui.ItemLibraryTreeView->setStyleSheet(styleSheet);
    }

    m_d->m_ui.buttonItems->setChecked(true);
}

ItemLibrary::~ItemLibrary()
{
    delete m_d;
}

void ItemLibrary::setNameFilter(const QString &nameFilter)
{
    QStringList nameFilterList;
    nameFilterList.append(nameFilter + "*.gif");
    nameFilterList.append(nameFilter + "*.png");
    nameFilterList.append(nameFilter + "*.jpg");
    nameFilterList.append(nameFilter + "*.");
    m_d->m_resourcesDirModel->setFilter(QDir::AllDirs | QDir::Files | QDir::NoDotAndDotDot);
    m_d->m_resourcesDirModel->setNameFilters(nameFilterList);
    if (m_d->m_ui.ItemLibraryTreeView->model() == m_d->m_resourcesDirModel)
        m_d->m_ui.ItemLibraryTreeView->setRootIndex(m_d->m_resourcesDirModel->index(m_d->m_resourcePath));
}

void ItemLibrary::itemLibraryButton()
{
    if (m_d->m_ui.buttonItems->isChecked()) {
        m_d->m_filterProxy->setSourceModel(m_d->m_itemLibraryModel);
        m_d->m_ui.ItemLibraryTreeView->setModel(m_d->m_filterProxy);
        m_d->m_ui.ItemLibraryTreeView->setIconSize(QSize(64, 64));
        m_d->m_ui.buttonResources->setChecked(false);
        m_d->m_ui.ItemLibraryTreeView->setRealModel(m_d->m_itemLibraryModel);
        expandAll();
    }
}

void ItemLibrary::resourcesButton()
{
    if (m_d->m_ui.buttonResources->isChecked()) {
        m_d->m_ui.ItemLibraryTreeView->setModel(m_d->m_resourcesDirModel);
        m_d->m_ui.ItemLibraryTreeView->setIconSize(QSize(32, 32));
        m_d->m_ui.buttonItems->setChecked(false);
        m_d->m_ui.ItemLibraryTreeView->setRootIndex(m_d->m_resourcesDirModel->index(m_d->m_resourcePath));
        m_d->m_ui.ItemLibraryTreeView->setColumnHidden(1, true);
        m_d->m_ui.ItemLibraryTreeView->setColumnHidden(2, true);
        m_d->m_ui.ItemLibraryTreeView->setColumnHidden(3, true);
        expandAll();
    }
}

void ItemLibrary::addItemLibraryInfo(const ItemLibraryInfo &itemLibraryInfo)
{
    m_d->m_itemLibraryModel->addItemLibraryInfo(itemLibraryInfo);
}

void ItemLibrary::setResourcePath(const QString &resourcePath)
{
    m_d->m_resourcePath = resourcePath;
}

void ItemLibrary::setMetaInfo(const MetaInfo &metaInfo)
{
    m_d->m_itemLibraryModel->clear();

    foreach (const QString &type, metaInfo.itemLibraryItems()) {
        NodeMetaInfo nodeInfo = metaInfo.nodeMetaInfo(type);

        QList<ItemLibraryInfo> itemLibraryRepresentationList = metaInfo.itemLibraryRepresentations(nodeInfo);

        if (!metaInfo.hasNodeMetaInfo(type))
            qWarning() << "ItemLibrary: type not declared: " << type;
        if (!itemLibraryRepresentationList.isEmpty() && metaInfo.hasNodeMetaInfo(type)) {
            foreach (ItemLibraryInfo itemLibraryRepresentation, itemLibraryRepresentationList) {
                QImage image(64, 64, QImage::Format_RGB32); // = m_d->m_queryView->paintObject(nodeInfo, itemLibraryRepresentation.properties()); TODO
                if (!image.isNull()) {
                    QPainter p(&image);
                    QPen pen(Qt::gray);
                    pen.setWidth(2);
                    p.setPen(pen);
                    p.drawRect(1, 1, image.width() - 2, image.height() - 2);
                }
                QIcon icon = itemLibraryRepresentation.icon();
                if (itemLibraryRepresentation.icon().isNull())
                    itemLibraryRepresentation.setIcon(QIcon(":/ItemLibrary/images/default-icon.png"));

                if (itemLibraryRepresentation.category().isEmpty())
                    itemLibraryRepresentation.setCategory(nodeInfo.category());
                if (!image.isNull()) {
                    itemLibraryRepresentation.setDragIcon(QPixmap::fromImage(image));
                    addItemLibraryInfo(itemLibraryRepresentation);
                }
            }
        } else {
            QImage image; // = m_d->m_queryView->paintObject(nodeInfo); TODO we have to render image
            QIcon icon = nodeInfo.icon();
            if (icon.isNull())
                icon = QIcon(":/ItemLibrary/images/default-icon.png");

            ItemLibraryInfo itemLibraryInfo;
            itemLibraryInfo.setName(type);
            itemLibraryInfo.setTypeName(nodeInfo.typeName());
            itemLibraryInfo.setCategory(nodeInfo.category());
            itemLibraryInfo.setIcon(icon);
            itemLibraryInfo.setMajorVersion(nodeInfo.majorVersion());
            itemLibraryInfo.setMinorVersion(nodeInfo.minorVersion());
            itemLibraryInfo.setDragIcon(QPixmap::fromImage(image));
            addItemLibraryInfo(itemLibraryInfo);
        }
    }
    expandAll();
}

void ItemLibrary::expandAll()
{
    m_d->m_ui.ItemLibraryTreeView->expandToDepth(1);
}

void ItemLibrary::contextMenuEvent (QContextMenuEvent *event)
{
    event->accept();
    QMenu menu;
    menu.addAction(tr("About plugins..."));
    menu.exec(event->globalPos());
}

}
<|endoftext|>