<commit_before>/**
Copyright (c) 2015, Intel Corporation. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.
    * Neither the name of the Intel Corporation nor the
      names of its contributors may be used to endorse or promote products
      derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL INTEL CORPORATION BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

#include <cstring>
#include <algorithm>

#include "COO.hpp"
#include "mm_io.h"

using namespace std;

namespace SpMP
{

COO::COO() : rowidx(NULL), colidx(NULL), values(NULL), isSymmetric(false)
{
}

COO::~COO()
{
  dealloc();
}

void COO::dealloc()
{
  FREE(rowidx);
  FREE(colidx);
  FREE(values);
}

void COO::storeMatrixMarket(const char *fileName) const
{
  FILE *fp = fopen(fileName, "w");
  assert(fp);

  MM_typecode matcode;
  mm_initialize_typecode(&matcode);
  mm_set_matrix(&matcode);
  mm_set_sparse(&matcode);
  mm_set_real(&matcode);

  int err = mm_write_mtx_crd(
    (char *)fileName, m, n, nnz, rowidx, colidx, values, matcode);
  if (err) {
    fprintf(
      stderr,
      "Fail to write matrix to %s (error code = %d)\n", fileName, err);
    exit(-1);
  }
}

template<class T>
static void qsort(int *idx, T *w, int left, int right)
{
  if (left >= right) return;

  swap(idx[left], idx[left + (right - left)/2]);
  swap(w[left], w[left + (right - left)/2]);

  int last = left;
  for (int i = left+1; i <= right; i++) {
    if (idx[i] < idx[left]) {
       ++last;
       swap(idx[last], idx[i]);
       swap(w[last], w[i]);
    }
  }

  swap(idx[left], idx[last]);
  swap(w[left], w[last]);

  qsort(idx, w, left, last-1);
  qsort(idx, w, last+1, right);
}

/* converts COO format to CSR format, not in-place,
   if SORT_IN_ROW is defined, each row is sorted in column index.
assume COO is one-based index */

template<class T>
void coo2csr(int n, int nz, const T *a, const int *i_idx, const int *j_idx,
       T *csr_a, int *col_idx, int *row_start, bool sort)
{
  int i, l;

#pragma omp parallel for
  for (i=0; i<=n; i++) row_start[i] = 0;

  /* determine row lengths */
  for (i=0; i<nz; i++) row_start[i_idx[i]]++;

  for (i=0; i<n; i++) row_start[i+1] += row_start[i];

  /* go through the structure  once more. Fill in output matrix. */
  for (l=0; l<nz; l++){
    i = row_start[i_idx[l] - 1];
    csr_a[i] = a[l];
    col_idx[i] = j_idx[l] - 1;
    row_start[i_idx[l] - 1]++;
  }

  /* shift back row_start */
  for (i=n; i>0; i--) row_start[i] = row_start[i-1];

  row_start[0] = 0;

  if (sort) {
#pragma omp parallel for
    for (i=0; i<n; i++){
      qsort (col_idx, csr_a, row_start[i], row_start[i+1] - 1);
      assert(is_sorted(col_idx + row_start[i], col_idx + row_start[i+1]));
    }
  }
}

void dcoo2csr(int n, int nz, const double *a, const int *i_idx, const int *j_idx,
       double *csr_a, int *col_idx, int *row_start, bool sort/*=true*/)
{
  coo2csr(n, nz, a, i_idx, j_idx, csr_a, col_idx, row_start, sort);
}

void dcoo2csr(const COO *Acoo, CSR *Acrs, bool createSeparateDiagData /*= true*/)
{
  Acrs->n=Acoo->n;
  Acrs->m=Acoo->m;

  dcoo2csr(
    Acrs->n, Acoo->nnz,
    Acoo->values, Acoo->rowidx, Acoo->colidx,
    Acrs->values, Acrs->colidx, Acrs->rowptr);

//  int job[8];
//  job[0]=2; // COO->CSR and column indicies are sorted
//  job[1]=0; // zero-based indexing for CSR
//  job[2]=1; // one-based indexing for COO
//  job[4]=Acoo->nnz;
//  job[5]=0;
//
//  int info;
//  mkl_dcsrcoo(&job[0], &(Acrs->n), Acrs->values, Acrs->colidx, Acrs->rowptr,
//              &(Acrs->nnz), Acoo->values, Acoo->rowidx, Acoo->colidx, &info);

  if (Acrs->diagptr) {
#pragma omp parallel for
    for (int i = 0; i < Acrs->m; ++i) {
      for (int j = Acrs->rowptr[i]; j < Acrs->rowptr[i + 1]; ++j) {
        if (Acrs->colidx[j] == i) {
          Acrs->diagptr[i] = j;

          if (createSeparateDiagData) {
            Acrs->idiag[i] = 1/Acrs->values[j];
            Acrs->diag[i] = Acrs->values[j];
          }
        }
      }
    }
  }
}

void loadMatrixMarket (const char *file, COO &coo, bool force_symmetric /*=false*/, int pad /*=1*/)
{
    FILE *fp=fopen(file, "r");
    if (NULL == fp) {
      fprintf(stderr, "Failed to open file %s\n", file);
      exit(-1);
    }
    MM_typecode matcode;
    int m;
    int n;
    int nnz;
    int x;
    int y;
    double value;
    size_t count;
    int pattern;
    int i;
    int *colidx;
    int *rowidx;
    double *values;
    int lines;

    if (mm_read_banner (fp, &matcode) != 0)
    {
        printf ("Error: could not process Matrix Market banner.\n");
        exit(1);
    }

    if ( !mm_is_valid (matcode) &&
         (mm_is_array (matcode) ||
          mm_is_dense (matcode)) )
    {
        printf ("Error: only support sparse and real matrices.\n");
        exit(1);
    }

    if (mm_read_mtx_crd_size(fp, &m, &n, &nnz) !=0)
    {
        printf ("Error: could not read matrix size.\n");
        exit(1);

    }
    int origM = m, origN = n;
    m = (m + pad - 1)/pad*pad;
    n = (n + pad - 1)/pad*pad;
    assert(m==n);

    if (force_symmetric || mm_is_symmetric (matcode) == 1)
    {
        coo.isSymmetric = true;
        count = 2L*nnz;
    }
    else
    {
        count = nnz;
    }

    coo.m = m;
    coo.n = n;
    size_t extraCount = min(m, n) - min(origM, origN);
    values = MALLOC(double, count + extraCount);
    colidx = MALLOC(int, count + extraCount);
    rowidx = MALLOC(int, count + extraCount);
    assert (values != NULL);
    assert (colidx != NULL);
    assert (rowidx != NULL);

    int *colidx_temp, *rowcnt;
    if (coo.isSymmetric) {
      colidx_temp = MALLOC(int, count);
      rowcnt = MALLOC(int, m);
      memset(rowcnt, 0, sizeof(int)*m);
      assert(colidx_temp != NULL);
      assert(rowcnt != NULL);
    }

    count = 0;
    lines = 0;
    pattern = mm_is_pattern (matcode);
    int x_o=1, y_o;
    double imag;
    while (mm_read_mtx_crd_entry (fp, &x, &y, &value, &imag, matcode) == 0)
    {
        rowidx[count] = x;
        colidx[count] = y;

        if (x > origM || y > origN)
        {
            printf ("Error: (%d %d) coordinate is out of range.\n", x, y);
            exit(1);
        }
        if (pattern == 1)
        {
            values[count] = 1;//RAND01();
        }
        else
        {
            values[count] = (double)value;
        }

        count++;
        lines++;
        if (coo.isSymmetric) rowcnt[x]++;
    }
    for (int i = min(origM, origN); i < min(m, n); ++i) {
      rowidx[count] = i + 1;
      colidx[count] = i + 1;
      values[count] = 1;
      ++count;
    }

    assert (lines == nnz);

  if (coo.isSymmetric) {
    // add transposed elements only if it doesn't exist
    size_t real_count = count;
    // preix-sum
    for (int i = 0; i < m; ++i) {
      rowcnt[i + 1] += rowcnt[i];
    }
    for (int i = 0; i < count; ++i) {
      int j = rowcnt[rowidx[i] - 1];
      colidx_temp[j] = colidx[i];
      rowcnt[rowidx[i] - 1]++;
    }
    for (int i = m; i > 0; --i) {
      rowcnt[i] = rowcnt[i - 1];
    }
    rowcnt[0] = 0;

#pragma omp parallel for
    for (int i = 0; i < m; ++i) {
      sort(colidx_temp + rowcnt[i], colidx_temp + rowcnt[i + 1]);
    }

    for (int i = 0; i < count; ++i) {
      int x = rowidx[i], y = colidx[i];
      if (x != y) {
        if (!binary_search(
            colidx_temp + rowcnt[y - 1], colidx_temp + rowcnt[y], x)) {
          rowidx[real_count] = y;
          colidx[real_count] = x;
          values[real_count] = values[i];
          ++real_count;
        }
      }
    }
    count = real_count;
  }
  nnz = count;

    //printf("count=%d trc=%d\n", count, trc+m);
    nnz = count;

    if (coo.isSymmetric) {
      FREE(rowcnt);
      FREE(colidx_temp);
    }

    coo.nnz = nnz;
    coo.dealloc();
    coo.values = values;
    coo.colidx = colidx;
    coo.rowidx = rowidx;

    fclose(fp);
}

} // namespace SpMP
<commit_msg>populate diagptr only if it's allocated<commit_after>/**
Copyright (c) 2015, Intel Corporation. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.
    * Neither the name of the Intel Corporation nor the
      names of its contributors may be used to endorse or promote products
      derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL INTEL CORPORATION BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

#include <cstring>
#include <algorithm>

#include "COO.hpp"
#include "mm_io.h"

using namespace std;

namespace SpMP
{

COO::COO() : rowidx(NULL), colidx(NULL), values(NULL), isSymmetric(false)
{
}

COO::~COO()
{
  dealloc();
}

void COO::dealloc()
{
  FREE(rowidx);
  FREE(colidx);
  FREE(values);
}

void COO::storeMatrixMarket(const char *fileName) const
{
  FILE *fp = fopen(fileName, "w");
  assert(fp);

  MM_typecode matcode;
  mm_initialize_typecode(&matcode);
  mm_set_matrix(&matcode);
  mm_set_sparse(&matcode);
  mm_set_real(&matcode);

  int err = mm_write_mtx_crd(
    (char *)fileName, m, n, nnz, rowidx, colidx, values, matcode);
  if (err) {
    fprintf(
      stderr,
      "Fail to write matrix to %s (error code = %d)\n", fileName, err);
    exit(-1);
  }
}

template<class T>
static void qsort(int *idx, T *w, int left, int right)
{
  if (left >= right) return;

  swap(idx[left], idx[left + (right - left)/2]);
  swap(w[left], w[left + (right - left)/2]);

  int last = left;
  for (int i = left+1; i <= right; i++) {
    if (idx[i] < idx[left]) {
       ++last;
       swap(idx[last], idx[i]);
       swap(w[last], w[i]);
    }
  }

  swap(idx[left], idx[last]);
  swap(w[left], w[last]);

  qsort(idx, w, left, last-1);
  qsort(idx, w, last+1, right);
}

/* converts COO format to CSR format, not in-place,
   if SORT_IN_ROW is defined, each row is sorted in column index.
assume COO is one-based index */

template<class T>
void coo2csr(int n, int nz, const T *a, const int *i_idx, const int *j_idx,
       T *csr_a, int *col_idx, int *row_start, bool sort)
{
  int i, l;

#pragma omp parallel for
  for (i=0; i<=n; i++) row_start[i] = 0;

  /* determine row lengths */
  for (i=0; i<nz; i++) row_start[i_idx[i]]++;

  for (i=0; i<n; i++) row_start[i+1] += row_start[i];

  /* go through the structure  once more. Fill in output matrix. */
  for (l=0; l<nz; l++){
    i = row_start[i_idx[l] - 1];
    csr_a[i] = a[l];
    col_idx[i] = j_idx[l] - 1;
    row_start[i_idx[l] - 1]++;
  }

  /* shift back row_start */
  for (i=n; i>0; i--) row_start[i] = row_start[i-1];

  row_start[0] = 0;

  if (sort) {
#pragma omp parallel for
    for (i=0; i<n; i++){
      qsort (col_idx, csr_a, row_start[i], row_start[i+1] - 1);
      assert(is_sorted(col_idx + row_start[i], col_idx + row_start[i+1]));
    }
  }
}

void dcoo2csr(int n, int nz, const double *a, const int *i_idx, const int *j_idx,
       double *csr_a, int *col_idx, int *row_start, bool sort/*=true*/)
{
  coo2csr(n, nz, a, i_idx, j_idx, csr_a, col_idx, row_start, sort);
}

void dcoo2csr(const COO *Acoo, CSR *Acrs, bool createSeparateDiagData /*= true*/)
{
  Acrs->n=Acoo->n;
  Acrs->m=Acoo->m;

  dcoo2csr(
    Acrs->n, Acoo->nnz,
    Acoo->values, Acoo->rowidx, Acoo->colidx,
    Acrs->values, Acrs->colidx, Acrs->rowptr);

  if (Acrs->diagptr) {
    if (!Acrs->idiag || !Acrs->diag) {
      createSeparateDiagData = false;
    }
#pragma omp parallel for
    for (int i = 0; i < Acrs->m; ++i) {
      for (int j = Acrs->rowptr[i]; j < Acrs->rowptr[i + 1]; ++j) {
        if (Acrs->colidx[j] == i) {
          Acrs->diagptr[i] = j;

          if (createSeparateDiagData) {
            Acrs->idiag[i] = 1/Acrs->values[j];
            Acrs->diag[i] = Acrs->values[j];
          }
        }
      }
    }
  }
}

void loadMatrixMarket (const char *file, COO &coo, bool force_symmetric /*=false*/, int pad /*=1*/)
{
    FILE *fp=fopen(file, "r");
    if (NULL == fp) {
      fprintf(stderr, "Failed to open file %s\n", file);
      exit(-1);
    }
    MM_typecode matcode;
    int m;
    int n;
    int nnz;
    int x;
    int y;
    double value;
    size_t count;
    int pattern;
    int i;
    int *colidx;
    int *rowidx;
    double *values;
    int lines;

    if (mm_read_banner (fp, &matcode) != 0)
    {
        printf ("Error: could not process Matrix Market banner.\n");
        exit(1);
    }

    if ( !mm_is_valid (matcode) &&
         (mm_is_array (matcode) ||
          mm_is_dense (matcode)) )
    {
        printf ("Error: only support sparse and real matrices.\n");
        exit(1);
    }

    if (mm_read_mtx_crd_size(fp, &m, &n, &nnz) !=0)
    {
        printf ("Error: could not read matrix size.\n");
        exit(1);

    }
    int origM = m, origN = n;
    m = (m + pad - 1)/pad*pad;
    n = (n + pad - 1)/pad*pad;
    assert(m==n);

    if (force_symmetric || mm_is_symmetric (matcode) == 1)
    {
        coo.isSymmetric = true;
        count = 2L*nnz;
    }
    else
    {
        count = nnz;
    }

    coo.m = m;
    coo.n = n;
    size_t extraCount = min(m, n) - min(origM, origN);
    values = MALLOC(double, count + extraCount);
    colidx = MALLOC(int, count + extraCount);
    rowidx = MALLOC(int, count + extraCount);
    assert (values != NULL);
    assert (colidx != NULL);
    assert (rowidx != NULL);

    int *colidx_temp, *rowcnt;
    if (coo.isSymmetric) {
      colidx_temp = MALLOC(int, count);
      rowcnt = MALLOC(int, m);
      memset(rowcnt, 0, sizeof(int)*m);
      assert(colidx_temp != NULL);
      assert(rowcnt != NULL);
    }

    count = 0;
    lines = 0;
    pattern = mm_is_pattern (matcode);
    int x_o=1, y_o;
    double imag;
    while (mm_read_mtx_crd_entry (fp, &x, &y, &value, &imag, matcode) == 0)
    {
        rowidx[count] = x;
        colidx[count] = y;

        if (x > origM || y > origN)
        {
            printf ("Error: (%d %d) coordinate is out of range.\n", x, y);
            exit(1);
        }
        if (pattern == 1)
        {
            values[count] = 1;//RAND01();
        }
        else
        {
            values[count] = (double)value;
        }

        count++;
        lines++;
        if (coo.isSymmetric) rowcnt[x]++;
    }
    for (int i = min(origM, origN); i < min(m, n); ++i) {
      rowidx[count] = i + 1;
      colidx[count] = i + 1;
      values[count] = 1;
      ++count;
    }

    assert (lines == nnz);

  if (coo.isSymmetric) {
    // add transposed elements only if it doesn't exist
    size_t real_count = count;
    // preix-sum
    for (int i = 0; i < m; ++i) {
      rowcnt[i + 1] += rowcnt[i];
    }
    for (int i = 0; i < count; ++i) {
      int j = rowcnt[rowidx[i] - 1];
      colidx_temp[j] = colidx[i];
      rowcnt[rowidx[i] - 1]++;
    }
    for (int i = m; i > 0; --i) {
      rowcnt[i] = rowcnt[i - 1];
    }
    rowcnt[0] = 0;

#pragma omp parallel for
    for (int i = 0; i < m; ++i) {
      sort(colidx_temp + rowcnt[i], colidx_temp + rowcnt[i + 1]);
    }

    for (int i = 0; i < count; ++i) {
      int x = rowidx[i], y = colidx[i];
      if (x != y) {
        if (!binary_search(
            colidx_temp + rowcnt[y - 1], colidx_temp + rowcnt[y], x)) {
          rowidx[real_count] = y;
          colidx[real_count] = x;
          values[real_count] = values[i];
          ++real_count;
        }
      }
    }
    count = real_count;
  }
  nnz = count;

    //printf("count=%d trc=%d\n", count, trc+m);
    nnz = count;

    if (coo.isSymmetric) {
      FREE(rowcnt);
      FREE(colidx_temp);
    }

    coo.nnz = nnz;
    coo.dealloc();
    coo.values = values;
    coo.colidx = colidx;
    coo.rowidx = rowidx;

    fclose(fp);
}

} // namespace SpMP
<|endoftext|>


<commit_before>// Copyright (c) 2018, 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/raw_object_fields.h"

namespace dart {

#if defined(DART_PRECOMPILER)

#define RAW_CLASSES_AND_FIELDS(F)                                              \
  F(Class, name_)                                                              \
  F(Class, user_name_)                                                         \
  F(Class, functions_)                                                         \
  F(Class, functions_hash_table_)                                              \
  F(Class, fields_)                                                            \
  F(Class, offset_in_words_to_field_)                                          \
  F(Class, interfaces_)                                                        \
  F(Class, script_)                                                            \
  F(Class, library_)                                                           \
  F(Class, type_parameters_)                                                   \
  F(Class, super_type_)                                                        \
  F(Class, mixin_)                                                             \
  F(Class, signature_function_)                                                \
  F(Class, constants_)                                                         \
  F(Class, canonical_type_)                                                    \
  F(Class, invocation_dispatcher_cache_)                                       \
  F(Class, allocation_stub_)                                                   \
  F(Class, direct_implementors_)                                               \
  F(Class, direct_subclasses_)                                                 \
  F(Class, dependent_code_)                                                    \
  F(PatchClass, patched_class_)                                                \
  F(PatchClass, origin_class_)                                                 \
  F(PatchClass, script_)                                                       \
  F(PatchClass, library_kernel_data_)                                          \
  F(Function, name_)                                                           \
  F(Function, owner_)                                                          \
  F(Function, result_type_)                                                    \
  F(Function, parameter_types_)                                                \
  F(Function, parameter_names_)                                                \
  F(Function, type_parameters_)                                                \
  F(Function, data_)                                                           \
  F(Function, ic_data_array_)                                                  \
  F(Function, code_)                                                           \
  F(ClosureData, context_scope_)                                               \
  F(ClosureData, parent_function_)                                             \
  F(ClosureData, signature_type_)                                              \
  F(ClosureData, closure_)                                                     \
  F(SignatureData, parent_function_)                                           \
  F(SignatureData, signature_type_)                                            \
  F(RedirectionData, type_)                                                    \
  F(RedirectionData, identifier_)                                              \
  F(RedirectionData, target_)                                                  \
  F(Field, name_)                                                              \
  F(Field, owner_)                                                             \
  F(Field, type_)                                                              \
  F(Field, guarded_list_length_)                                               \
  F(Field, dependent_code_)                                                    \
  F(Field, type_test_cache_)                                                   \
  F(Script, url_)                                                              \
  F(Script, resolved_url_)                                                     \
  F(Script, compile_time_constants_)                                           \
  F(Script, line_starts_)                                                      \
  F(Script, debug_positions_)                                                  \
  F(Script, yield_positions_)                                                  \
  F(Script, kernel_program_info_)                                              \
  F(Script, source_)                                                           \
  F(Library, name_)                                                            \
  F(Library, url_)                                                             \
  F(Library, private_key_)                                                     \
  F(Library, dictionary_)                                                      \
  F(Library, metadata_)                                                        \
  F(Library, toplevel_class_)                                                  \
  F(Library, patch_classes_)                                                   \
  F(Library, imports_)                                                         \
  F(Library, exports_)                                                         \
  F(Library, load_error_)                                                      \
  F(Library, kernel_data_)                                                     \
  F(Library, resolved_names_)                                                  \
  F(Library, exported_names_)                                                  \
  F(Library, loaded_scripts_)                                                  \
  F(Namespace, library_)                                                       \
  F(Namespace, show_names_)                                                    \
  F(Namespace, hide_names_)                                                    \
  F(Namespace, metadata_field_)                                                \
  F(KernelProgramInfo, string_offsets_)                                        \
  F(KernelProgramInfo, string_data_)                                           \
  F(KernelProgramInfo, canonical_names_)                                       \
  F(KernelProgramInfo, metadata_payloads_)                                     \
  F(KernelProgramInfo, metadata_mappings_)                                     \
  F(KernelProgramInfo, scripts_)                                               \
  F(KernelProgramInfo, constants_)                                             \
  F(KernelProgramInfo, bytecode_component_)                                    \
  F(KernelProgramInfo, potential_natives_)                                     \
  F(KernelProgramInfo, potential_pragma_functions_)                            \
  F(KernelProgramInfo, constants_table_)                                       \
  F(KernelProgramInfo, libraries_cache_)                                       \
  F(KernelProgramInfo, classes_cache_)                                         \
  F(Code, object_pool_)                                                        \
  F(Code, instructions_)                                                       \
  F(Code, owner_)                                                              \
  F(Code, exception_handlers_)                                                 \
  F(Code, pc_descriptors_)                                                     \
  F(Code, stackmaps_)                                                          \
  F(Code, inlined_id_to_function_)                                             \
  F(Code, code_source_map_)                                                    \
  F(Bytecode, object_pool_)                                                    \
  F(Bytecode, instructions_)                                                   \
  F(Bytecode, function_)                                                       \
  F(Bytecode, exception_handlers_)                                             \
  F(Bytecode, pc_descriptors_)                                                 \
  F(ExceptionHandlers, handled_types_data_)                                    \
  F(Context, parent_)                                                          \
  F(SingleTargetCache, target_)                                                \
  F(UnlinkedCall, target_name_)                                                \
  F(UnlinkedCall, args_descriptor_)                                            \
  F(ICData, ic_data_)                                                          \
  F(ICData, target_name_)                                                      \
  F(ICData, args_descriptor_)                                                  \
  F(ICData, owner_)                                                            \
  F(MegamorphicCache, buckets_)                                                \
  F(MegamorphicCache, mask_)                                                   \
  F(MegamorphicCache, target_name_)                                            \
  F(MegamorphicCache, args_descriptor_)                                        \
  F(SubtypeTestCache, cache_)                                                  \
  F(ApiError, message_)                                                        \
  F(LanguageError, previous_error_)                                            \
  F(LanguageError, script_)                                                    \
  F(LanguageError, message_)                                                   \
  F(LanguageError, formatted_message_)                                         \
  F(UnhandledException, exception_)                                            \
  F(UnhandledException, stacktrace_)                                           \
  F(UnwindError, message_)                                                     \
  F(LibraryPrefix, name_)                                                      \
  F(LibraryPrefix, importer_)                                                  \
  F(LibraryPrefix, imports_)                                                   \
  F(LibraryPrefix, dependent_code_)                                            \
  F(TypeArguments, instantiations_)                                            \
  F(TypeArguments, length_)                                                    \
  F(TypeArguments, hash_)                                                      \
  F(Type, type_class_id_)                                                      \
  F(Type, arguments_)                                                          \
  F(Type, hash_)                                                               \
  F(TypeRef, type_)                                                            \
  F(TypeParameter, name_)                                                      \
  F(TypeParameter, hash_)                                                      \
  F(TypeParameter, bound_)                                                     \
  F(TypeParameter, parameterized_function_)                                    \
  F(MixinAppType, super_type_)                                                 \
  F(MixinAppType, mixin_types_)                                                \
  F(Closure, instantiator_type_arguments_)                                     \
  F(Closure, function_type_arguments_)                                         \
  F(Closure, delayed_type_arguments_)                                          \
  F(Closure, function_)                                                        \
  F(Closure, context_)                                                         \
  F(Closure, hash_)                                                            \
  F(String, length_)                                                           \
  F(String, hash_)                                                             \
  F(Array, type_arguments_)                                                    \
  F(Array, length_)                                                            \
  F(GrowableObjectArray, type_arguments_)                                      \
  F(GrowableObjectArray, length_)                                              \
  F(GrowableObjectArray, data_)                                                \
  F(LinkedHashMap, type_arguments_)                                            \
  F(LinkedHashMap, index_)                                                     \
  F(LinkedHashMap, hash_mask_)                                                 \
  F(LinkedHashMap, data_)                                                      \
  F(LinkedHashMap, used_data_)                                                 \
  F(LinkedHashMap, deleted_keys_)                                              \
  F(TypedData, length_)                                                        \
  F(ExternalTypedData, length_)                                                \
  F(ReceivePort, send_port_)                                                   \
  F(ReceivePort, handler_)                                                     \
  F(StackTrace, async_link_)                                                   \
  F(StackTrace, code_array_)                                                   \
  F(StackTrace, pc_offset_array_)                                              \
  F(RegExp, num_bracket_expressions_)                                          \
  F(RegExp, pattern_)                                                          \
  F(RegExp, external_one_byte_function_)                                       \
  F(RegExp, external_two_byte_function_)                                       \
  F(RegExp, external_one_byte_sticky_function_)                                \
  F(RegExp, external_two_byte_sticky_function_)                                \
  F(WeakProperty, key_)                                                        \
  F(WeakProperty, value_)                                                      \
  F(MirrorReference, referent_)                                                \
  F(UserTag, label_)

OffsetsTable::OffsetsTable(Zone* zone) : cached_offsets_(zone) {
  for (intptr_t i = 0; offsets_table[i].class_id != -1; ++i) {
    OffsetsTableEntry entry = offsets_table[i];
    cached_offsets_.Insert({{entry.class_id, entry.offset}, entry.field_name});
  }
}

const char* OffsetsTable::FieldNameForOffset(intptr_t class_id,
                                             intptr_t offset) {
  return cached_offsets_.LookupValue({class_id, offset});
}

#define DEFINE_OFFSETS_TABLE_ENTRY(class_name, field_name)                     \
  {class_name::kClassId, #field_name, OFFSET_OF(Raw##class_name, field_name)},

// clang-format off
OffsetsTable::OffsetsTableEntry OffsetsTable::offsets_table[] = {
    RAW_CLASSES_AND_FIELDS(DEFINE_OFFSETS_TABLE_ENTRY)
    {-1, nullptr, -1}
};
// clang-format on

#undef DEFINE_OFFSETS_TABLE_ENTRY

#endif

}  // namespace dart
<commit_msg>[vm] Fix bots after commit 5f36c5f9.<commit_after>// Copyright (c) 2018, 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/raw_object_fields.h"

namespace dart {

#if defined(DART_PRECOMPILER)

#define RAW_CLASSES_AND_FIELDS(F)                                              \
  F(Class, name_)                                                              \
  F(Class, user_name_)                                                         \
  F(Class, functions_)                                                         \
  F(Class, functions_hash_table_)                                              \
  F(Class, fields_)                                                            \
  F(Class, offset_in_words_to_field_)                                          \
  F(Class, interfaces_)                                                        \
  F(Class, script_)                                                            \
  F(Class, library_)                                                           \
  F(Class, type_parameters_)                                                   \
  F(Class, super_type_)                                                        \
  F(Class, mixin_)                                                             \
  F(Class, signature_function_)                                                \
  F(Class, constants_)                                                         \
  F(Class, canonical_type_)                                                    \
  F(Class, invocation_dispatcher_cache_)                                       \
  F(Class, allocation_stub_)                                                   \
  F(Class, direct_implementors_)                                               \
  F(Class, direct_subclasses_)                                                 \
  F(Class, dependent_code_)                                                    \
  F(PatchClass, patched_class_)                                                \
  F(PatchClass, origin_class_)                                                 \
  F(PatchClass, script_)                                                       \
  F(PatchClass, library_kernel_data_)                                          \
  F(Function, name_)                                                           \
  F(Function, owner_)                                                          \
  F(Function, result_type_)                                                    \
  F(Function, parameter_types_)                                                \
  F(Function, parameter_names_)                                                \
  F(Function, type_parameters_)                                                \
  F(Function, data_)                                                           \
  F(Function, ic_data_array_)                                                  \
  F(Function, code_)                                                           \
  F(ClosureData, context_scope_)                                               \
  F(ClosureData, parent_function_)                                             \
  F(ClosureData, signature_type_)                                              \
  F(ClosureData, closure_)                                                     \
  F(SignatureData, parent_function_)                                           \
  F(SignatureData, signature_type_)                                            \
  F(RedirectionData, type_)                                                    \
  F(RedirectionData, identifier_)                                              \
  F(RedirectionData, target_)                                                  \
  F(Field, name_)                                                              \
  F(Field, owner_)                                                             \
  F(Field, type_)                                                              \
  F(Field, guarded_list_length_)                                               \
  F(Field, dependent_code_)                                                    \
  F(Field, type_test_cache_)                                                   \
  F(Script, url_)                                                              \
  F(Script, resolved_url_)                                                     \
  F(Script, compile_time_constants_)                                           \
  F(Script, line_starts_)                                                      \
  F(Script, debug_positions_)                                                  \
  F(Script, yield_positions_)                                                  \
  F(Script, kernel_program_info_)                                              \
  F(Script, source_)                                                           \
  F(Library, name_)                                                            \
  F(Library, url_)                                                             \
  F(Library, private_key_)                                                     \
  F(Library, dictionary_)                                                      \
  F(Library, metadata_)                                                        \
  F(Library, toplevel_class_)                                                  \
  F(Library, patch_classes_)                                                   \
  F(Library, imports_)                                                         \
  F(Library, exports_)                                                         \
  F(Library, load_error_)                                                      \
  F(Library, kernel_data_)                                                     \
  F(Library, resolved_names_)                                                  \
  F(Library, exported_names_)                                                  \
  F(Library, loaded_scripts_)                                                  \
  F(Namespace, library_)                                                       \
  F(Namespace, show_names_)                                                    \
  F(Namespace, hide_names_)                                                    \
  F(Namespace, metadata_field_)                                                \
  F(KernelProgramInfo, string_offsets_)                                        \
  F(KernelProgramInfo, string_data_)                                           \
  F(KernelProgramInfo, canonical_names_)                                       \
  F(KernelProgramInfo, metadata_payloads_)                                     \
  F(KernelProgramInfo, metadata_mappings_)                                     \
  F(KernelProgramInfo, scripts_)                                               \
  F(KernelProgramInfo, constants_)                                             \
  F(KernelProgramInfo, bytecode_component_)                                    \
  F(KernelProgramInfo, potential_natives_)                                     \
  F(KernelProgramInfo, potential_pragma_functions_)                            \
  F(KernelProgramInfo, constants_table_)                                       \
  F(KernelProgramInfo, libraries_cache_)                                       \
  F(KernelProgramInfo, classes_cache_)                                         \
  F(Code, object_pool_)                                                        \
  F(Code, instructions_)                                                       \
  F(Code, owner_)                                                              \
  F(Code, exception_handlers_)                                                 \
  F(Code, pc_descriptors_)                                                     \
  F(Code, stackmaps_)                                                          \
  F(Code, inlined_id_to_function_)                                             \
  F(Code, code_source_map_)                                                    \
  F(Bytecode, object_pool_)                                                    \
  F(Bytecode, instructions_)                                                   \
  F(Bytecode, function_)                                                       \
  F(Bytecode, exception_handlers_)                                             \
  F(Bytecode, pc_descriptors_)                                                 \
  F(ExceptionHandlers, handled_types_data_)                                    \
  F(Context, parent_)                                                          \
  F(SingleTargetCache, target_)                                                \
  F(UnlinkedCall, target_name_)                                                \
  F(UnlinkedCall, args_descriptor_)                                            \
  F(ICData, ic_data_)                                                          \
  F(ICData, target_name_)                                                      \
  F(ICData, args_descriptor_)                                                  \
  F(ICData, owner_)                                                            \
  F(MegamorphicCache, buckets_)                                                \
  F(MegamorphicCache, mask_)                                                   \
  F(MegamorphicCache, target_name_)                                            \
  F(MegamorphicCache, args_descriptor_)                                        \
  F(SubtypeTestCache, cache_)                                                  \
  F(ApiError, message_)                                                        \
  F(LanguageError, previous_error_)                                            \
  F(LanguageError, script_)                                                    \
  F(LanguageError, message_)                                                   \
  F(LanguageError, formatted_message_)                                         \
  F(UnhandledException, exception_)                                            \
  F(UnhandledException, stacktrace_)                                           \
  F(UnwindError, message_)                                                     \
  F(LibraryPrefix, name_)                                                      \
  F(LibraryPrefix, importer_)                                                  \
  F(LibraryPrefix, imports_)                                                   \
  F(LibraryPrefix, dependent_code_)                                            \
  F(TypeArguments, instantiations_)                                            \
  F(TypeArguments, length_)                                                    \
  F(TypeArguments, hash_)                                                      \
  F(Type, type_class_id_)                                                      \
  F(Type, arguments_)                                                          \
  F(Type, hash_)                                                               \
  F(Type, signature_)                                                          \
  F(TypeRef, type_)                                                            \
  F(TypeParameter, name_)                                                      \
  F(TypeParameter, hash_)                                                      \
  F(TypeParameter, bound_)                                                     \
  F(TypeParameter, parameterized_function_)                                    \
  F(MixinAppType, super_type_)                                                 \
  F(MixinAppType, mixin_types_)                                                \
  F(Closure, instantiator_type_arguments_)                                     \
  F(Closure, function_type_arguments_)                                         \
  F(Closure, delayed_type_arguments_)                                          \
  F(Closure, function_)                                                        \
  F(Closure, context_)                                                         \
  F(Closure, hash_)                                                            \
  F(String, length_)                                                           \
  F(String, hash_)                                                             \
  F(Array, type_arguments_)                                                    \
  F(Array, length_)                                                            \
  F(GrowableObjectArray, type_arguments_)                                      \
  F(GrowableObjectArray, length_)                                              \
  F(GrowableObjectArray, data_)                                                \
  F(LinkedHashMap, type_arguments_)                                            \
  F(LinkedHashMap, index_)                                                     \
  F(LinkedHashMap, hash_mask_)                                                 \
  F(LinkedHashMap, data_)                                                      \
  F(LinkedHashMap, used_data_)                                                 \
  F(LinkedHashMap, deleted_keys_)                                              \
  F(TypedData, length_)                                                        \
  F(ExternalTypedData, length_)                                                \
  F(ReceivePort, send_port_)                                                   \
  F(ReceivePort, handler_)                                                     \
  F(StackTrace, async_link_)                                                   \
  F(StackTrace, code_array_)                                                   \
  F(StackTrace, pc_offset_array_)                                              \
  F(RegExp, num_bracket_expressions_)                                          \
  F(RegExp, pattern_)                                                          \
  F(RegExp, external_one_byte_function_)                                       \
  F(RegExp, external_two_byte_function_)                                       \
  F(RegExp, external_one_byte_sticky_function_)                                \
  F(RegExp, external_two_byte_sticky_function_)                                \
  F(WeakProperty, key_)                                                        \
  F(WeakProperty, value_)                                                      \
  F(MirrorReference, referent_)                                                \
  F(UserTag, label_)

OffsetsTable::OffsetsTable(Zone* zone) : cached_offsets_(zone) {
  for (intptr_t i = 0; offsets_table[i].class_id != -1; ++i) {
    OffsetsTableEntry entry = offsets_table[i];
    cached_offsets_.Insert({{entry.class_id, entry.offset}, entry.field_name});
  }
}

const char* OffsetsTable::FieldNameForOffset(intptr_t class_id,
                                             intptr_t offset) {
  return cached_offsets_.LookupValue({class_id, offset});
}

#define DEFINE_OFFSETS_TABLE_ENTRY(class_name, field_name)                     \
  {class_name::kClassId, #field_name, OFFSET_OF(Raw##class_name, field_name)},

// clang-format off
OffsetsTable::OffsetsTableEntry OffsetsTable::offsets_table[] = {
    RAW_CLASSES_AND_FIELDS(DEFINE_OFFSETS_TABLE_ENTRY)
    {-1, nullptr, -1}
};
// clang-format on

#undef DEFINE_OFFSETS_TABLE_ENTRY

#endif

}  // namespace dart
<|endoftext|>


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

#include "chrome/browser/ui/input_window_dialog.h"

#include <gtk/gtk.h>

#include "app/gtk_signal.h"
#include "base/message_loop.h"
#include "base/scoped_ptr.h"
#include "base/string_piece.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/gtk/gtk_util.h"

class InputWindowDialogGtk : public InputWindowDialog {
 public:
  // Creates a dialog. Takes ownership of |delegate|.
  InputWindowDialogGtk(GtkWindow* parent,
                       const std::string& window_title,
                       const std::string& label,
                       const std::string& contents,
                       Delegate* delegate);
  virtual ~InputWindowDialogGtk();

  virtual void Show();
  virtual void Close();

 private:
  CHROMEG_CALLBACK_0(InputWindowDialogGtk, void, OnEntryChanged, GtkEditable*);
  CHROMEGTK_CALLBACK_1(InputWindowDialogGtk, void, OnResponse, int);
  CHROMEGTK_CALLBACK_1(InputWindowDialogGtk, gboolean,
                       OnWindowDeleteEvent, GdkEvent*);
  CHROMEGTK_CALLBACK_0(InputWindowDialogGtk, void, OnWindowDestroy);

  // The underlying gtk dialog window.
  GtkWidget* dialog_;

  // The GtkEntry in this form.
  GtkWidget* input_;

  // Our delegate. Consumes the window's output.
  scoped_ptr<InputWindowDialog::Delegate> delegate_;
};

InputWindowDialogGtk::InputWindowDialogGtk(GtkWindow* parent,
                                           const std::string& window_title,
                                           const std::string& label,
                                           const std::string& contents,
                                           Delegate* delegate)
    : dialog_(gtk_dialog_new_with_buttons(
                  window_title.c_str(),
                  parent,
                  GTK_DIALOG_MODAL,
                  GTK_STOCK_CANCEL, GTK_RESPONSE_REJECT,
                  GTK_STOCK_OK, GTK_RESPONSE_ACCEPT,
                  NULL)),
      delegate_(delegate) {
  gtk_dialog_set_default_response(GTK_DIALOG(dialog_), GTK_RESPONSE_ACCEPT);
  gtk_dialog_set_has_separator(GTK_DIALOG(dialog_), FALSE);

  GtkWidget* content_area = GTK_DIALOG(dialog_)->vbox;
  gtk_box_set_spacing(GTK_BOX(content_area), 18);

  GtkWidget* hbox = gtk_hbox_new(FALSE, 6);
  GtkWidget* label_widget = gtk_label_new(label.c_str());
  gtk_box_pack_start(GTK_BOX(hbox), label_widget, FALSE, FALSE, 0);

  input_ = gtk_entry_new();
  gtk_entry_set_text(GTK_ENTRY(input_), contents.c_str());
  g_signal_connect(input_, "changed",
                   G_CALLBACK(OnEntryChangedThunk), this);
  g_object_set(G_OBJECT(input_), "activates-default", TRUE, NULL);
  gtk_box_pack_start(GTK_BOX(hbox), input_, TRUE, TRUE, 0);

  gtk_widget_show_all(hbox);

  gtk_box_pack_start(GTK_BOX(content_area), hbox, FALSE, FALSE, 0);

  g_signal_connect(dialog_, "response",
                   G_CALLBACK(OnResponseThunk), this);
  g_signal_connect(dialog_, "delete-event",
                   G_CALLBACK(OnWindowDeleteEventThunk), this);
  g_signal_connect(dialog_, "destroy",
                   G_CALLBACK(OnWindowDestroyThunk), this);
}

InputWindowDialogGtk::~InputWindowDialogGtk() {
}

void InputWindowDialogGtk::Show() {
  gtk_util::ShowDialog(dialog_);
}

void InputWindowDialogGtk::Close() {
  // Under the model that we've inherited from Windows, dialogs can receive
  // more than one Close() call inside the current message loop event.
  if (dialog_) {
    gtk_widget_destroy(GTK_WIDGET(dialog_));
    dialog_ = NULL;
  }
}

void InputWindowDialogGtk::OnEntryChanged(GtkEditable* entry) {
  std::wstring value(UTF8ToWide(gtk_entry_get_text(GTK_ENTRY(entry))));
  gtk_dialog_set_response_sensitive(GTK_DIALOG(dialog_),
                                    GTK_RESPONSE_ACCEPT,
                                    delegate_->IsValid(value));
}

void InputWindowDialogGtk::OnResponse(GtkWidget* dialog, int response_id) {
  if (response_id == GTK_RESPONSE_ACCEPT) {
    std::wstring value(UTF8ToWide(gtk_entry_get_text(GTK_ENTRY(input_))));
    delegate_->InputAccepted(value);
  } else {
    delegate_->InputCanceled();
  }
  Close();
}

gboolean InputWindowDialogGtk::OnWindowDeleteEvent(GtkWidget* widget,
                                                   GdkEvent* event) {
  Close();

  // Return true to prevent the gtk dialog from being destroyed. Close will
  // destroy it for us and the default gtk_dialog_delete_event_handler() will
  // force the destruction without us being able to stop it.
  return TRUE;
}

void InputWindowDialogGtk::OnWindowDestroy(GtkWidget* widget) {
  MessageLoop::current()->DeleteSoon(FROM_HERE, this);
}

InputWindowDialog* InputWindowDialog::Create(gfx::NativeWindow parent,
                                             const std::wstring& window_title,
                                             const std::wstring& label,
                                             const std::wstring& contents,
                                             Delegate* delegate) {
  return new InputWindowDialogGtk(parent,
                                  WideToUTF8(window_title),
                                  WideToUTF8(label),
                                  WideToUTF8(contents),
                                  delegate);
}
<commit_msg>gtk: Do not make folder editor dialog resizable.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/ui/input_window_dialog.h"

#include <gtk/gtk.h>

#include "app/gtk_signal.h"
#include "base/message_loop.h"
#include "base/scoped_ptr.h"
#include "base/string_piece.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/gtk/gtk_util.h"

class InputWindowDialogGtk : public InputWindowDialog {
 public:
  // Creates a dialog. Takes ownership of |delegate|.
  InputWindowDialogGtk(GtkWindow* parent,
                       const std::string& window_title,
                       const std::string& label,
                       const std::string& contents,
                       Delegate* delegate);
  virtual ~InputWindowDialogGtk();

  virtual void Show();
  virtual void Close();

 private:
  CHROMEG_CALLBACK_0(InputWindowDialogGtk, void, OnEntryChanged, GtkEditable*);
  CHROMEGTK_CALLBACK_1(InputWindowDialogGtk, void, OnResponse, int);
  CHROMEGTK_CALLBACK_1(InputWindowDialogGtk, gboolean,
                       OnWindowDeleteEvent, GdkEvent*);
  CHROMEGTK_CALLBACK_0(InputWindowDialogGtk, void, OnWindowDestroy);

  // The underlying gtk dialog window.
  GtkWidget* dialog_;

  // The GtkEntry in this form.
  GtkWidget* input_;

  // Our delegate. Consumes the window's output.
  scoped_ptr<InputWindowDialog::Delegate> delegate_;
};

InputWindowDialogGtk::InputWindowDialogGtk(GtkWindow* parent,
                                           const std::string& window_title,
                                           const std::string& label,
                                           const std::string& contents,
                                           Delegate* delegate)
    : dialog_(gtk_dialog_new_with_buttons(
                  window_title.c_str(),
                  parent,
                  GTK_DIALOG_MODAL,
                  GTK_STOCK_CANCEL, GTK_RESPONSE_REJECT,
                  GTK_STOCK_OK, GTK_RESPONSE_ACCEPT,
                  NULL)),
      delegate_(delegate) {
  gtk_dialog_set_default_response(GTK_DIALOG(dialog_), GTK_RESPONSE_ACCEPT);
  gtk_dialog_set_has_separator(GTK_DIALOG(dialog_), FALSE);
  gtk_window_set_resizable(GTK_WINDOW(dialog_), FALSE);

  GtkWidget* content_area = GTK_DIALOG(dialog_)->vbox;
  gtk_box_set_spacing(GTK_BOX(content_area), 18);

  GtkWidget* hbox = gtk_hbox_new(FALSE, 6);
  GtkWidget* label_widget = gtk_label_new(label.c_str());
  gtk_box_pack_start(GTK_BOX(hbox), label_widget, FALSE, FALSE, 0);

  input_ = gtk_entry_new();
  gtk_entry_set_text(GTK_ENTRY(input_), contents.c_str());
  g_signal_connect(input_, "changed",
                   G_CALLBACK(OnEntryChangedThunk), this);
  g_object_set(G_OBJECT(input_), "activates-default", TRUE, NULL);
  gtk_box_pack_start(GTK_BOX(hbox), input_, TRUE, TRUE, 0);

  gtk_widget_show_all(hbox);

  gtk_box_pack_start(GTK_BOX(content_area), hbox, FALSE, FALSE, 0);

  g_signal_connect(dialog_, "response",
                   G_CALLBACK(OnResponseThunk), this);
  g_signal_connect(dialog_, "delete-event",
                   G_CALLBACK(OnWindowDeleteEventThunk), this);
  g_signal_connect(dialog_, "destroy",
                   G_CALLBACK(OnWindowDestroyThunk), this);
}

InputWindowDialogGtk::~InputWindowDialogGtk() {
}

void InputWindowDialogGtk::Show() {
  gtk_util::ShowDialog(dialog_);
}

void InputWindowDialogGtk::Close() {
  // Under the model that we've inherited from Windows, dialogs can receive
  // more than one Close() call inside the current message loop event.
  if (dialog_) {
    gtk_widget_destroy(GTK_WIDGET(dialog_));
    dialog_ = NULL;
  }
}

void InputWindowDialogGtk::OnEntryChanged(GtkEditable* entry) {
  std::wstring value(UTF8ToWide(gtk_entry_get_text(GTK_ENTRY(entry))));
  gtk_dialog_set_response_sensitive(GTK_DIALOG(dialog_),
                                    GTK_RESPONSE_ACCEPT,
                                    delegate_->IsValid(value));
}

void InputWindowDialogGtk::OnResponse(GtkWidget* dialog, int response_id) {
  if (response_id == GTK_RESPONSE_ACCEPT) {
    std::wstring value(UTF8ToWide(gtk_entry_get_text(GTK_ENTRY(input_))));
    delegate_->InputAccepted(value);
  } else {
    delegate_->InputCanceled();
  }
  Close();
}

gboolean InputWindowDialogGtk::OnWindowDeleteEvent(GtkWidget* widget,
                                                   GdkEvent* event) {
  Close();

  // Return true to prevent the gtk dialog from being destroyed. Close will
  // destroy it for us and the default gtk_dialog_delete_event_handler() will
  // force the destruction without us being able to stop it.
  return TRUE;
}

void InputWindowDialogGtk::OnWindowDestroy(GtkWidget* widget) {
  MessageLoop::current()->DeleteSoon(FROM_HERE, this);
}

InputWindowDialog* InputWindowDialog::Create(gfx::NativeWindow parent,
                                             const std::wstring& window_title,
                                             const std::wstring& label,
                                             const std::wstring& contents,
                                             Delegate* delegate) {
  return new InputWindowDialogGtk(parent,
                                  WideToUTF8(window_title),
                                  WideToUTF8(label),
                                  WideToUTF8(contents),
                                  delegate);
}
<|endoftext|>


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

#include "chrome/renderer/extensions/event_bindings.h"

#include "base/basictypes.h"
#include "base/singleton.h"
#include "chrome/common/render_messages.h"
#include "chrome/common/url_constants.h"
#include "chrome/renderer/extensions/bindings_utils.h"
#include "chrome/renderer/extensions/event_bindings.h"
#include "chrome/renderer/js_only_v8_extensions.h"
#include "chrome/renderer/render_thread.h"
#include "chrome/renderer/render_view.h"
#include "grit/renderer_resources.h"
#include "webkit/api/public/WebDataSource.h"
#include "webkit/api/public/WebURLRequest.h"
#include "webkit/glue/webframe.h"

using bindings_utils::CallFunctionInContext;
using bindings_utils::ContextInfo;
using bindings_utils::ContextList;
using bindings_utils::GetContexts;
using bindings_utils::GetStringResource;
using bindings_utils::ExtensionBase;
using bindings_utils::GetPendingRequestMap;
using bindings_utils::PendingRequestMap;

namespace {

// Keep a local cache of RenderThread so that we can mock it out for unit tests.
static RenderThreadBase* render_thread = NULL;
static bool in_unit_tests = false;

// Set to true if these bindings are registered.  Will be false when extensions
// are disabled.
static bool bindings_registered = false;

struct ExtensionData {
  std::map<std::string, int> listener_count;
};
int EventIncrementListenerCount(const std::string& event_name) {
  ExtensionData *data = Singleton<ExtensionData>::get();
  return ++(data->listener_count[event_name]);
}
int EventDecrementListenerCount(const std::string& event_name) {
  ExtensionData *data = Singleton<ExtensionData>::get();
  return --(data->listener_count[event_name]);
}

class ExtensionImpl : public ExtensionBase {
 public:
  ExtensionImpl()
      : ExtensionBase(EventBindings::kName,
                      GetStringResource<IDR_EVENT_BINDINGS_JS>(),
                      0, NULL) {
  }
  ~ExtensionImpl() {}

  virtual v8::Handle<v8::FunctionTemplate> GetNativeFunction(
      v8::Handle<v8::String> name) {
    if (name->Equals(v8::String::New("AttachEvent"))) {
      return v8::FunctionTemplate::New(AttachEvent);
    } else if (name->Equals(v8::String::New("DetachEvent"))) {
      return v8::FunctionTemplate::New(DetachEvent);
    }
    return ExtensionBase::GetNativeFunction(name);
  }

  // Attach an event name to an object.
  static v8::Handle<v8::Value> AttachEvent(const v8::Arguments& args) {
    DCHECK(args.Length() == 1);
    // TODO(erikkay) should enforce that event name is a string in the bindings
    DCHECK(args[0]->IsString() || args[0]->IsUndefined());

    if (args[0]->IsString()) {
      std::string event_name(*v8::String::AsciiValue(args[0]));
      if (EventIncrementListenerCount(event_name) == 1) {
        EventBindings::GetRenderThread()->Send(
            new ViewHostMsg_ExtensionAddListener(event_name));
      }
    }

    return v8::Undefined();
  }

  static v8::Handle<v8::Value> DetachEvent(const v8::Arguments& args) {
    DCHECK(args.Length() == 1);
    // TODO(erikkay) should enforce that event name is a string in the bindings
    DCHECK(args[0]->IsString() || args[0]->IsUndefined());

    if (args[0]->IsString()) {
      std::string event_name(*v8::String::AsciiValue(args[0]));
      if (EventDecrementListenerCount(event_name) == 0) {
        EventBindings::GetRenderThread()->Send(
          new ViewHostMsg_ExtensionRemoveListener(event_name));
      }
    }

    return v8::Undefined();
  }
};

}  // namespace

const char* EventBindings::kName = "chrome/EventBindings";

v8::Extension* EventBindings::Get() {
  bindings_registered = true;
  return new ExtensionImpl();
}

// static
void EventBindings::SetRenderThread(RenderThreadBase* thread) {
  render_thread = thread;
  in_unit_tests = true;
}

// static
RenderThreadBase* EventBindings::GetRenderThread() {
  return render_thread ? render_thread : RenderThread::current();
}

static void HandleContextDestroyed(ContextList::iterator context_iter,
                                   bool callUnload) {
  // Notify the bindings that they're going away.
  if (callUnload) {
    CallFunctionInContext((*context_iter)->context, "dispatchOnUnload", 0,
                          NULL);
  }

  // Remove all pending requests for this context.
  PendingRequestMap& pending_requests = GetPendingRequestMap();
  for (PendingRequestMap::iterator it = pending_requests.begin();
       it != pending_requests.end(); ) {
    PendingRequestMap::iterator current = it++;
    if (current->second->context == (*context_iter)->context) {
      current->second->context.Dispose();
      current->second->context.Clear();
      pending_requests.erase(current);
    }
  }

  // Unload any content script contexts for this frame.
  for (ContextList::iterator it = GetContexts().begin();
       it != GetContexts().end(); ) {
    ContextList::iterator current = it++;
    if ((*current)->parent_context == (*context_iter)->context)
      HandleContextDestroyed(current, callUnload);
  }

  // Remove it from our registered contexts.
  (*context_iter)->context.ClearWeak();
  (*context_iter)->context.Dispose();
  (*context_iter)->context.Clear();

  if (!(*context_iter)->parent_context.IsEmpty()) {
    (*context_iter)->parent_context.Dispose();
    (*context_iter)->parent_context.Clear();
  }

  GetContexts().erase(context_iter);
}

static void ContextWeakReferenceCallback(v8::Persistent<v8::Value> context,
                                         void*) {
  for (ContextList::iterator it = GetContexts().begin();
       it != GetContexts().end(); ++it) {
    if ((*it)->context == context) {
      HandleContextDestroyed(it, false);
      return;
    }
  }

  NOTREACHED();
}

void EventBindings::HandleContextCreated(WebFrame* frame, bool content_script) {
  if (!bindings_registered)
    return;

  v8::HandleScope handle_scope;
  ContextList& contexts = GetContexts();
  v8::Local<v8::Context> frame_context = frame->GetScriptContext();
  v8::Local<v8::Context> context = v8::Context::GetCurrent();
  DCHECK(!context.IsEmpty());
  DCHECK(bindings_utils::FindContext(context) == contexts.end());

  // Figure out the URL for the toplevel frame.  If the top frame is loading,
  // use its provisional URL, since we get this notification before commit.
  WebFrame* main_frame = frame->GetView()->GetMainFrame();
  WebKit::WebDataSource* ds = main_frame->GetProvisionalDataSource();
  if (!ds)
    ds = main_frame->GetDataSource();
  GURL url = ds->request().url();
  std::string extension_id;
  if (url.SchemeIs(chrome::kExtensionScheme)) {
    extension_id = url.host();
  } else if (!content_script) {
    // This context is a regular non-extension web page.  Ignore it.  We only
    // care about content scripts and extension frames.
    // (Unless we're in unit tests, in which case we don't care what the URL
    // is).
    DCHECK(frame_context == context);
    if (!in_unit_tests)
      return;
  }

  v8::Persistent<v8::Context> persistent_context =
      v8::Persistent<v8::Context>::New(context);
  v8::Persistent<v8::Context> parent_context;

  if (content_script) {
    DCHECK(frame_context != context);

    parent_context = v8::Persistent<v8::Context>::New(frame_context);
    // Content script contexts can get GCed before their frame goes away, so
    // set up a GC callback.
    persistent_context.MakeWeak(NULL, &ContextWeakReferenceCallback);
  }

  RenderView* render_view = NULL;
  if (frame->GetView() && frame->GetView()->GetDelegate())
    render_view = static_cast<RenderView*>(frame->GetView()->GetDelegate());

  contexts.push_back(linked_ptr<ContextInfo>(
      new ContextInfo(persistent_context, extension_id, parent_context,
                      render_view)));

  v8::Handle<v8::Value> argv[1];
  argv[0] = v8::String::New(extension_id.c_str());
  CallFunctionInContext(context, "dispatchOnLoad", arraysize(argv), argv);
}

// static
void EventBindings::HandleContextDestroyed(WebFrame* frame) {
  if (!bindings_registered)
    return;

  v8::HandleScope handle_scope;
  v8::Local<v8::Context> context = frame->GetScriptContext();
  DCHECK(!context.IsEmpty());

  ContextList::iterator context_iter = bindings_utils::FindContext(context);
  if (context_iter != GetContexts().end())
    ::HandleContextDestroyed(context_iter, true);
}

// static
void EventBindings::CallFunction(const std::string& function_name,
                                 int argc, v8::Handle<v8::Value>* argv,
                                 RenderView* render_view) {
  for (ContextList::iterator it = GetContexts().begin();
       it != GetContexts().end(); ++it) {
    if (render_view && render_view != (*it)->render_view)
      continue;
    CallFunctionInContext((*it)->context, function_name, argc, argv);
  }
}
<commit_msg>Don't dispatch the extensions bindings unload event during GC.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/renderer/extensions/event_bindings.h"

#include "base/basictypes.h"
#include "base/singleton.h"
#include "chrome/common/render_messages.h"
#include "chrome/common/url_constants.h"
#include "chrome/renderer/extensions/bindings_utils.h"
#include "chrome/renderer/extensions/event_bindings.h"
#include "chrome/renderer/js_only_v8_extensions.h"
#include "chrome/renderer/render_thread.h"
#include "chrome/renderer/render_view.h"
#include "grit/renderer_resources.h"
#include "webkit/api/public/WebDataSource.h"
#include "webkit/api/public/WebURLRequest.h"
#include "webkit/glue/webframe.h"

using bindings_utils::CallFunctionInContext;
using bindings_utils::ContextInfo;
using bindings_utils::ContextList;
using bindings_utils::GetContexts;
using bindings_utils::GetStringResource;
using bindings_utils::ExtensionBase;
using bindings_utils::GetPendingRequestMap;
using bindings_utils::PendingRequestMap;

namespace {

// Keep a local cache of RenderThread so that we can mock it out for unit tests.
static RenderThreadBase* render_thread = NULL;
static bool in_unit_tests = false;

// Set to true if these bindings are registered.  Will be false when extensions
// are disabled.
static bool bindings_registered = false;

struct ExtensionData {
  std::map<std::string, int> listener_count;
};
int EventIncrementListenerCount(const std::string& event_name) {
  ExtensionData *data = Singleton<ExtensionData>::get();
  return ++(data->listener_count[event_name]);
}
int EventDecrementListenerCount(const std::string& event_name) {
  ExtensionData *data = Singleton<ExtensionData>::get();
  return --(data->listener_count[event_name]);
}

class ExtensionImpl : public ExtensionBase {
 public:
  ExtensionImpl()
      : ExtensionBase(EventBindings::kName,
                      GetStringResource<IDR_EVENT_BINDINGS_JS>(),
                      0, NULL) {
  }
  ~ExtensionImpl() {}

  virtual v8::Handle<v8::FunctionTemplate> GetNativeFunction(
      v8::Handle<v8::String> name) {
    if (name->Equals(v8::String::New("AttachEvent"))) {
      return v8::FunctionTemplate::New(AttachEvent);
    } else if (name->Equals(v8::String::New("DetachEvent"))) {
      return v8::FunctionTemplate::New(DetachEvent);
    }
    return ExtensionBase::GetNativeFunction(name);
  }

  // Attach an event name to an object.
  static v8::Handle<v8::Value> AttachEvent(const v8::Arguments& args) {
    DCHECK(args.Length() == 1);
    // TODO(erikkay) should enforce that event name is a string in the bindings
    DCHECK(args[0]->IsString() || args[0]->IsUndefined());

    if (args[0]->IsString()) {
      std::string event_name(*v8::String::AsciiValue(args[0]));
      if (EventIncrementListenerCount(event_name) == 1) {
        EventBindings::GetRenderThread()->Send(
            new ViewHostMsg_ExtensionAddListener(event_name));
      }
    }

    return v8::Undefined();
  }

  static v8::Handle<v8::Value> DetachEvent(const v8::Arguments& args) {
    DCHECK(args.Length() == 1);
    // TODO(erikkay) should enforce that event name is a string in the bindings
    DCHECK(args[0]->IsString() || args[0]->IsUndefined());

    if (args[0]->IsString()) {
      std::string event_name(*v8::String::AsciiValue(args[0]));
      if (EventDecrementListenerCount(event_name) == 0) {
        EventBindings::GetRenderThread()->Send(
          new ViewHostMsg_ExtensionRemoveListener(event_name));
      }
    }

    return v8::Undefined();
  }
};

}  // namespace

const char* EventBindings::kName = "chrome/EventBindings";

v8::Extension* EventBindings::Get() {
  bindings_registered = true;
  return new ExtensionImpl();
}

// static
void EventBindings::SetRenderThread(RenderThreadBase* thread) {
  render_thread = thread;
  in_unit_tests = true;
}

// static
RenderThreadBase* EventBindings::GetRenderThread() {
  return render_thread ? render_thread : RenderThread::current();
}

static void DeferredUnload(v8::Persistent<v8::Context> context) {
  v8::HandleScope handle_scope;
  CallFunctionInContext(context, "dispatchOnUnload", 0, NULL);
  context.Dispose();
  context.Clear();
}

static void HandleContextDestroyed(ContextList::iterator context_iter,
                                   bool in_gc) {
  // Notify the bindings that they're going away.
  if (in_gc) {
    // We shouldn't call back into javascript during a garbage collect.  Do it
    // later.  We'll hang onto the context until this DeferredUnload is called.
    MessageLoop::current()->PostTask(FROM_HERE, NewRunnableFunction(
        DeferredUnload, (*context_iter)->context));
  } else {
    CallFunctionInContext((*context_iter)->context, "dispatchOnUnload",
                          0, NULL);
  }

  // Remove all pending requests for this context.
  PendingRequestMap& pending_requests = GetPendingRequestMap();
  for (PendingRequestMap::iterator it = pending_requests.begin();
       it != pending_requests.end(); ) {
    PendingRequestMap::iterator current = it++;
    if (current->second->context == (*context_iter)->context) {
      current->second->context.Dispose();
      current->second->context.Clear();
      pending_requests.erase(current);
    }
  }

  // Unload any content script contexts for this frame.
  for (ContextList::iterator it = GetContexts().begin();
       it != GetContexts().end(); ) {
    ContextList::iterator current = it++;
    if ((*current)->parent_context == (*context_iter)->context)
      HandleContextDestroyed(current, in_gc);
  }

  if (!(*context_iter)->parent_context.IsEmpty()) {
    (*context_iter)->parent_context.Dispose();
    (*context_iter)->parent_context.Clear();
  }

  // Remove it from our registered contexts.
  (*context_iter)->context.ClearWeak();
  if (!in_gc) {
    (*context_iter)->context.Dispose();
    (*context_iter)->context.Clear();
  }

  GetContexts().erase(context_iter);
}

static void ContextWeakReferenceCallback(v8::Persistent<v8::Value> context,
                                         void*) {
  for (ContextList::iterator it = GetContexts().begin();
       it != GetContexts().end(); ++it) {
    if ((*it)->context == context) {
      HandleContextDestroyed(it, true);
      return;
    }
  }

  NOTREACHED();
}

void EventBindings::HandleContextCreated(WebFrame* frame, bool content_script) {
  if (!bindings_registered)
    return;

  v8::HandleScope handle_scope;
  ContextList& contexts = GetContexts();
  v8::Local<v8::Context> frame_context = frame->GetScriptContext();
  v8::Local<v8::Context> context = v8::Context::GetCurrent();
  DCHECK(!context.IsEmpty());
  DCHECK(bindings_utils::FindContext(context) == contexts.end());

  // Figure out the URL for the toplevel frame.  If the top frame is loading,
  // use its provisional URL, since we get this notification before commit.
  WebFrame* main_frame = frame->GetView()->GetMainFrame();
  WebKit::WebDataSource* ds = main_frame->GetProvisionalDataSource();
  if (!ds)
    ds = main_frame->GetDataSource();
  GURL url = ds->request().url();
  std::string extension_id;
  if (url.SchemeIs(chrome::kExtensionScheme)) {
    extension_id = url.host();
  } else if (!content_script) {
    // This context is a regular non-extension web page.  Ignore it.  We only
    // care about content scripts and extension frames.
    // (Unless we're in unit tests, in which case we don't care what the URL
    // is).
    DCHECK(frame_context == context);
    if (!in_unit_tests)
      return;
  }

  v8::Persistent<v8::Context> persistent_context =
      v8::Persistent<v8::Context>::New(context);
  v8::Persistent<v8::Context> parent_context;

  if (content_script) {
    DCHECK(frame_context != context);

    parent_context = v8::Persistent<v8::Context>::New(frame_context);
    // Content script contexts can get GCed before their frame goes away, so
    // set up a GC callback.
    persistent_context.MakeWeak(NULL, &ContextWeakReferenceCallback);
  }

  RenderView* render_view = NULL;
  if (frame->GetView() && frame->GetView()->GetDelegate())
    render_view = static_cast<RenderView*>(frame->GetView()->GetDelegate());

  contexts.push_back(linked_ptr<ContextInfo>(
      new ContextInfo(persistent_context, extension_id, parent_context,
                      render_view)));

  v8::Handle<v8::Value> argv[1];
  argv[0] = v8::String::New(extension_id.c_str());
  CallFunctionInContext(context, "dispatchOnLoad", arraysize(argv), argv);
}

// static
void EventBindings::HandleContextDestroyed(WebFrame* frame) {
  if (!bindings_registered)
    return;

  v8::HandleScope handle_scope;
  v8::Local<v8::Context> context = frame->GetScriptContext();
  DCHECK(!context.IsEmpty());

  ContextList::iterator context_iter = bindings_utils::FindContext(context);
  if (context_iter != GetContexts().end())
    ::HandleContextDestroyed(context_iter, false);
}

// static
void EventBindings::CallFunction(const std::string& function_name,
                                 int argc, v8::Handle<v8::Value>* argv,
                                 RenderView* render_view) {
  for (ContextList::iterator it = GetContexts().begin();
       it != GetContexts().end(); ++it) {
    if (render_view && render_view != (*it)->render_view)
      continue;
    CallFunctionInContext((*it)->context, function_name, argc, argv);
  }
}
<|endoftext|>