/*
 *  Copyright 2011 The LibYuv Project Authors. All rights reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS. All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */

#include "libyuv/scale.h"

#include <assert.h>
#include <string.h>

#include "libyuv/cpu_id.h"
#include "libyuv/planar_functions.h"  // For CopyARGB
#include "libyuv/row.h"
#include "libyuv/scale_row.h"

#ifdef __cplusplus
namespace libyuv {
extern "C" {
#endif

static __inline int Abs(int v) {
  return v >= 0 ? v : -v;
}

// ScaleARGB ARGB, 1/2
// This is an optimized version for scaling down a ARGB to 1/2 of
// its original size.
static void ScaleARGBDown2(int src_width, int src_height,
                           int dst_width, int dst_height,
                           int src_stride, int dst_stride,
                           const uint8* src_argb, uint8* dst_argb,
                           int x, int dx, int y, int dy,
                           enum FilterMode filtering) {
  int j;
  int row_stride = src_stride * (dy >> 16);
  void (*ScaleARGBRowDown2)(const uint8* src_argb, ptrdiff_t src_stride,
                            uint8* dst_argb, int dst_width) =
    filtering == kFilterNone ? ScaleARGBRowDown2_C :
        (filtering == kFilterLinear ? ScaleARGBRowDown2Linear_C :
        ScaleARGBRowDown2Box_C);
  assert(dx == 65536 * 2);  // Test scale factor of 2.
  assert((dy & 0x1ffff) == 0);  // Test vertical scale is multiple of 2.
  // Advance to odd row, even column.
  if (filtering == kFilterBilinear) {
    src_argb += (y >> 16) * src_stride + (x >> 16) * 4;
  } else {
    src_argb += (y >> 16) * src_stride + ((x >> 16) - 1) * 4;
  }

#if defined(HAS_SCALEARGBROWDOWN2_SSE2)
  if (TestCpuFlag(kCpuHasSSE2)) {
    ScaleARGBRowDown2 = filtering == kFilterNone ? ScaleARGBRowDown2_Any_SSE2 :
        (filtering == kFilterLinear ? ScaleARGBRowDown2Linear_Any_SSE2 :
        ScaleARGBRowDown2Box_Any_SSE2);
    if (IS_ALIGNED(dst_width, 4)) {
      ScaleARGBRowDown2 = filtering == kFilterNone ? ScaleARGBRowDown2_SSE2 :
          (filtering == kFilterLinear ? ScaleARGBRowDown2Linear_SSE2 :
          ScaleARGBRowDown2Box_SSE2);
    }
  }
#endif
#if defined(HAS_SCALEARGBROWDOWN2_NEON)
  if (TestCpuFlag(kCpuHasNEON)) {
    ScaleARGBRowDown2 = filtering == kFilterNone ? ScaleARGBRowDown2_Any_NEON :
        (filtering == kFilterLinear ? ScaleARGBRowDown2Linear_Any_NEON :
        ScaleARGBRowDown2Box_Any_NEON);
    if (IS_ALIGNED(dst_width, 8)) {
      ScaleARGBRowDown2 = filtering == kFilterNone ? ScaleARGBRowDown2_NEON :
          (filtering == kFilterLinear ? ScaleARGBRowDown2Linear_NEON :
          ScaleARGBRowDown2Box_NEON);
    }
  }
#endif

  if (filtering == kFilterLinear) {
    src_stride = 0;
  }
  for (j = 0; j < dst_height; ++j) {
    ScaleARGBRowDown2(src_argb, src_stride, dst_argb, dst_width);
    src_argb += row_stride;
    dst_argb += dst_stride;
  }
}

// ScaleARGB ARGB, 1/4
// This is an optimized version for scaling down a ARGB to 1/4 of
// its original size.
static void ScaleARGBDown4Box(int src_width, int src_height,
                              int dst_width, int dst_height,
                              int src_stride, int dst_stride,
                              const uint8* src_argb, uint8* dst_argb,
                              int x, int dx, int y, int dy) {
  int j;
  // Allocate 2 rows of ARGB.
  const int kRowSize = (dst_width * 2 * 4 + 31) & ~31;
  align_buffer_64(row, kRowSize * 2);
  int row_stride = src_stride * (dy >> 16);
  void (*ScaleARGBRowDown2)(const uint8* src_argb, ptrdiff_t src_stride,
    uint8* dst_argb, int dst_width) = ScaleARGBRowDown2Box_C;
  // Advance to odd row, even column.
  src_argb += (y >> 16) * src_stride + (x >> 16) * 4;
  assert(dx == 65536 * 4);  // Test scale factor of 4.
  assert((dy & 0x3ffff) == 0);  // Test vertical scale is multiple of 4.
#if defined(HAS_SCALEARGBROWDOWN2_SSE2)
  if (TestCpuFlag(kCpuHasSSE2)) {
    ScaleARGBRowDown2 = ScaleARGBRowDown2Box_Any_SSE2;
    if (IS_ALIGNED(dst_width, 4)) {
      ScaleARGBRowDown2 = ScaleARGBRowDown2Box_SSE2;
    }
  }
#endif
#if defined(HAS_SCALEARGBROWDOWN2_NEON)
  if (TestCpuFlag(kCpuHasNEON)) {
    ScaleARGBRowDown2 = ScaleARGBRowDown2Box_Any_NEON;
    if (IS_ALIGNED(dst_width, 8)) {
      ScaleARGBRowDown2 = ScaleARGBRowDown2Box_NEON;
    }
  }
#endif

  for (j = 0; j < dst_height; ++j) {
    ScaleARGBRowDown2(src_argb, src_stride, row, dst_width * 2);
    ScaleARGBRowDown2(src_argb + src_stride * 2, src_stride,
                      row + kRowSize, dst_width * 2);
    ScaleARGBRowDown2(row, kRowSize, dst_argb, dst_width);
    src_argb += row_stride;
    dst_argb += dst_stride;
  }
  free_aligned_buffer_64(row);
}

// ScaleARGB ARGB Even
// This is an optimized version for scaling down a ARGB to even
// multiple of its original size.
static void ScaleARGBDownEven(int src_width, int src_height,
                              int dst_width, int dst_height,
                              int src_stride, int dst_stride,
                              const uint8* src_argb, uint8* dst_argb,
                              int x, int dx, int y, int dy,
                              enum FilterMode filtering) {
  int j;
  int col_step = dx >> 16;
  int row_stride = (dy >> 16) * src_stride;
  void (*ScaleARGBRowDownEven)(const uint8* src_argb, ptrdiff_t src_stride,
                               int src_step, uint8* dst_argb, int dst_width) =
      filtering ? ScaleARGBRowDownEvenBox_C : ScaleARGBRowDownEven_C;
  assert(IS_ALIGNED(src_width, 2));
  assert(IS_ALIGNED(src_height, 2));
  src_argb += (y >> 16) * src_stride + (x >> 16) * 4;
#if defined(HAS_SCALEARGBROWDOWNEVEN_SSE2)
  if (TestCpuFlag(kCpuHasSSE2)) {
    ScaleARGBRowDownEven = filtering ? ScaleARGBRowDownEvenBox_Any_SSE2 :
        ScaleARGBRowDownEven_Any_SSE2;
    if (IS_ALIGNED(dst_width, 4)) {
      ScaleARGBRowDownEven = filtering ? ScaleARGBRowDownEvenBox_SSE2 :
          ScaleARGBRowDownEven_SSE2;
    }
  }
#endif
#if defined(HAS_SCALEARGBROWDOWNEVEN_NEON)
  if (TestCpuFlag(kCpuHasNEON)) {
    ScaleARGBRowDownEven = filtering ? ScaleARGBRowDownEvenBox_Any_NEON :
        ScaleARGBRowDownEven_Any_NEON;
    if (IS_ALIGNED(dst_width, 4)) {
      ScaleARGBRowDownEven = filtering ? ScaleARGBRowDownEvenBox_NEON :
          ScaleARGBRowDownEven_NEON;
    }
  }
#endif

  if (filtering == kFilterLinear) {
    src_stride = 0;
  }
  for (j = 0; j < dst_height; ++j) {
    ScaleARGBRowDownEven(src_argb, src_stride, col_step, dst_argb, dst_width);
    src_argb += row_stride;
    dst_argb += dst_stride;
  }
}

// Scale ARGB down with bilinear interpolation.
static void ScaleARGBBilinearDown(int src_width, int src_height,
                                  int dst_width, int dst_height,
                                  int src_stride, int dst_stride,
                                  const uint8* src_argb, uint8* dst_argb,
                                  int x, int dx, int y, int dy,
                                  enum FilterMode filtering) {
  int j;
  void (*InterpolateRow)(uint8* dst_argb, const uint8* src_argb,
      ptrdiff_t src_stride, int dst_width, int source_y_fraction) =
      InterpolateRow_C;
  void (*ScaleARGBFilterCols)(uint8* dst_argb, const uint8* src_argb,
      int dst_width, int x, int dx) =
      (src_width >= 32768) ? ScaleARGBFilterCols64_C : ScaleARGBFilterCols_C;
  int64 xlast = x + (int64)(dst_width - 1) * dx;
  int64 xl = (dx >= 0) ? x : xlast;
  int64 xr = (dx >= 0) ? xlast : x;
  int clip_src_width;
  xl = (xl >> 16) & ~3;  // Left edge aligned.
  xr = (xr >> 16) + 1;  // Right most pixel used.  Bilinear uses 2 pixels.
  xr = (xr + 1 + 3) & ~3;  // 1 beyond 4 pixel aligned right most pixel.
  if (xr > src_width) {
    xr = src_width;
  }
  clip_src_width = (int)(xr - xl) * 4;  // Width aligned to 4.
  src_argb += xl * 4;
  x -= (int)(xl << 16);
#if defined(HAS_INTERPOLATEROW_SSSE3)
  if (TestCpuFlag(kCpuHasSSSE3)) {
    InterpolateRow = InterpolateRow_Any_SSSE3;
    if (IS_ALIGNED(clip_src_width, 16)) {
      InterpolateRow = InterpolateRow_SSSE3;
    }
  }
#endif
#if defined(HAS_INTERPOLATEROW_AVX2)
  if (TestCpuFlag(kCpuHasAVX2)) {
    InterpolateRow = InterpolateRow_Any_AVX2;
    if (IS_ALIGNED(clip_src_width, 32)) {
      InterpolateRow = InterpolateRow_AVX2;
    }
  }
#endif
#if defined(HAS_INTERPOLATEROW_NEON)
  if (TestCpuFlag(kCpuHasNEON)) {
    InterpolateRow = InterpolateRow_Any_NEON;
    if (IS_ALIGNED(clip_src_width, 16)) {
      InterpolateRow = InterpolateRow_NEON;
    }
  }
#endif
#if defined(HAS_INTERPOLATEROW_DSPR2)
  if (TestCpuFlag(kCpuHasDSPR2) &&
      IS_ALIGNED(src_argb, 4) && IS_ALIGNED(src_stride, 4)) {
    InterpolateRow = InterpolateRow_Any_DSPR2;
    if (IS_ALIGNED(clip_src_width, 4)) {
      InterpolateRow = InterpolateRow_DSPR2;
    }
  }
#endif
#if defined(HAS_SCALEARGBFILTERCOLS_SSSE3)
  if (TestCpuFlag(kCpuHasSSSE3) && src_width < 32768) {
    ScaleARGBFilterCols = ScaleARGBFilterCols_SSSE3;
  }
#endif
#if defined(HAS_SCALEARGBFILTERCOLS_NEON)
  if (TestCpuFlag(kCpuHasNEON)) {
    ScaleARGBFilterCols = ScaleARGBFilterCols_Any_NEON;
    if (IS_ALIGNED(dst_width, 4)) {
      ScaleARGBFilterCols = ScaleARGBFilterCols_NEON;
    }
  }
#endif
  // TODO(fbarchard): Consider not allocating row buffer for kFilterLinear.
  // Allocate a row of ARGB.
  {
    align_buffer_64(row, clip_src_width * 4);

    const int max_y = (src_height - 1) << 16;
    if (y > max_y) {
      y = max_y;
    }
    for (j = 0; j < dst_height; ++j) {
      int yi = y >> 16;
      const uint8* src = src_argb + yi * src_stride;
      if (filtering == kFilterLinear) {
        ScaleARGBFilterCols(dst_argb, src, dst_width, x, dx);
      } else {
        int yf = (y >> 8) & 255;
        InterpolateRow(row, src, src_stride, clip_src_width, yf);
        ScaleARGBFilterCols(dst_argb, row, dst_width, x, dx);
      }
      dst_argb += dst_stride;
      y += dy;
      if (y > max_y) {
        y = max_y;
      }
    }
    free_aligned_buffer_64(row);
  }
}

// Scale ARGB up with bilinear interpolation.
static void ScaleARGBBilinearUp(int src_width, int src_height,
                                int dst_width, int dst_height,
                                int src_stride, int dst_stride,
                                const uint8* src_argb, uint8* dst_argb,
                                int x, int dx, int y, int dy,
                                enum FilterMode filtering) {
  int j;
  void (*InterpolateRow)(uint8* dst_argb, const uint8* src_argb,
      ptrdiff_t src_stride, int dst_width, int source_y_fraction) =
      InterpolateRow_C;
  void (*ScaleARGBFilterCols)(uint8* dst_argb, const uint8* src_argb,
      int dst_width, int x, int dx) =
      filtering ? ScaleARGBFilterCols_C : ScaleARGBCols_C;
  const int max_y = (src_height - 1) << 16;
#if defined(HAS_INTERPOLATEROW_SSSE3)
  if (TestCpuFlag(kCpuHasSSSE3)) {
    InterpolateRow = InterpolateRow_Any_SSSE3;
    if (IS_ALIGNED(dst_width, 4)) {
      InterpolateRow = InterpolateRow_SSSE3;
    }
  }
#endif
#if defined(HAS_INTERPOLATEROW_AVX2)
  if (TestCpuFlag(kCpuHasAVX2)) {
    InterpolateRow = InterpolateRow_Any_AVX2;
    if (IS_ALIGNED(dst_width, 8)) {
      InterpolateRow = InterpolateRow_AVX2;
    }
  }
#endif
#if defined(HAS_INTERPOLATEROW_NEON)
  if (TestCpuFlag(kCpuHasNEON)) {
    InterpolateRow = InterpolateRow_Any_NEON;
    if (IS_ALIGNED(dst_width, 4)) {
      InterpolateRow = InterpolateRow_NEON;
    }
  }
#endif
#if defined(HAS_INTERPOLATEROW_DSPR2)
  if (TestCpuFlag(kCpuHasDSPR2) &&
      IS_ALIGNED(dst_argb, 4) && IS_ALIGNED(dst_stride, 4)) {
    InterpolateRow = InterpolateRow_DSPR2;
  }
#endif
  if (src_width >= 32768) {
    ScaleARGBFilterCols = filtering ?
        ScaleARGBFilterCols64_C : ScaleARGBCols64_C;
  }
#if defined(HAS_SCALEARGBFILTERCOLS_SSSE3)
  if (filtering && TestCpuFlag(kCpuHasSSSE3) && src_width < 32768) {
    ScaleARGBFilterCols = ScaleARGBFilterCols_SSSE3;
  }
#endif
#if defined(HAS_SCALEARGBFILTERCOLS_NEON)
  if (filtering && TestCpuFlag(kCpuHasNEON)) {
    ScaleARGBFilterCols = ScaleARGBFilterCols_Any_NEON;
    if (IS_ALIGNED(dst_width, 4)) {
      ScaleARGBFilterCols = ScaleARGBFilterCols_NEON;
    }
  }
#endif
#if defined(HAS_SCALEARGBCOLS_SSE2)
  if (!filtering && TestCpuFlag(kCpuHasSSE2) && src_width < 32768) {
    ScaleARGBFilterCols = ScaleARGBCols_SSE2;
  }
#endif
#if defined(HAS_SCALEARGBCOLS_NEON)
  if (!filtering && TestCpuFlag(kCpuHasNEON)) {
    ScaleARGBFilterCols = ScaleARGBCols_Any_NEON;
    if (IS_ALIGNED(dst_width, 8)) {
      ScaleARGBFilterCols = ScaleARGBCols_NEON;
    }
  }
#endif
  if (!filtering && src_width * 2 == dst_width && x < 0x8000) {
    ScaleARGBFilterCols = ScaleARGBColsUp2_C;
#if defined(HAS_SCALEARGBCOLSUP2_SSE2)
    if (TestCpuFlag(kCpuHasSSE2) && IS_ALIGNED(dst_width, 8)) {
      ScaleARGBFilterCols = ScaleARGBColsUp2_SSE2;
    }
#endif
  }

  if (y > max_y) {
    y = max_y;
  }

  {
    int yi = y >> 16;
    const uint8* src = src_argb + yi * src_stride;

    // Allocate 2 rows of ARGB.
    const int kRowSize = (dst_width * 4 + 31) & ~31;
    align_buffer_64(row, kRowSize * 2);

    uint8* rowptr = row;
    int rowstride = kRowSize;
    int lasty = yi;

    ScaleARGBFilterCols(rowptr, src, dst_width, x, dx);
    if (src_height > 1) {
      src += src_stride;
    }
    ScaleARGBFilterCols(rowptr + rowstride, src, dst_width, x, dx);
    src += src_stride;

    for (j = 0; j < dst_height; ++j) {
      yi = y >> 16;
      if (yi != lasty) {
        if (y > max_y) {
          y = max_y;
          yi = y >> 16;
          src = src_argb + yi * src_stride;
        }
        if (yi != lasty) {
          ScaleARGBFilterCols(rowptr, src, dst_width, x, dx);
          rowptr += rowstride;
          rowstride = -rowstride;
          lasty = yi;
          src += src_stride;
        }
      }
      if (filtering == kFilterLinear) {
        InterpolateRow(dst_argb, rowptr, 0, dst_width * 4, 0);
      } else {
        int yf = (y >> 8) & 255;
        InterpolateRow(dst_argb, rowptr, rowstride, dst_width * 4, yf);
      }
      dst_argb += dst_stride;
      y += dy;
    }
    free_aligned_buffer_64(row);
  }
}

#ifdef YUVSCALEUP
// Scale YUV to ARGB up with bilinear interpolation.
static void ScaleYUVToARGBBilinearUp(int src_width, int src_height,
                                     int dst_width, int dst_height,
                                     int src_stride_y,
                                     int src_stride_u,
                                     int src_stride_v,
                                     int dst_stride_argb,
                                     const uint8* src_y,
                                     const uint8* src_u,
                                     const uint8* src_v,
                                     uint8* dst_argb,
                                     int x, int dx, int y, int dy,
                                     enum FilterMode filtering) {
  int j;
  void (*I422ToARGBRow)(const uint8* y_buf,
                        const uint8* u_buf,
                        const uint8* v_buf,
                        uint8* rgb_buf,
                        int width) = I422ToARGBRow_C;
#if defined(HAS_I422TOARGBROW_SSSE3)
  if (TestCpuFlag(kCpuHasSSSE3)) {
    I422ToARGBRow = I422ToARGBRow_Any_SSSE3;
    if (IS_ALIGNED(src_width, 8)) {
      I422ToARGBRow = I422ToARGBRow_SSSE3;
    }
  }
#endif
#if defined(HAS_I422TOARGBROW_AVX2)
  if (TestCpuFlag(kCpuHasAVX2)) {
    I422ToARGBRow = I422ToARGBRow_Any_AVX2;
    if (IS_ALIGNED(src_width, 16)) {
      I422ToARGBRow = I422ToARGBRow_AVX2;
    }
  }
#endif
#if defined(HAS_I422TOARGBROW_NEON)
  if (TestCpuFlag(kCpuHasNEON)) {
    I422ToARGBRow = I422ToARGBRow_Any_NEON;
    if (IS_ALIGNED(src_width, 8)) {
      I422ToARGBRow = I422ToARGBRow_NEON;
    }
  }
#endif
#if defined(HAS_I422TOARGBROW_DSPR2)
  if (TestCpuFlag(kCpuHasDSPR2) && IS_ALIGNED(src_width, 4) &&
      IS_ALIGNED(src_y, 4) && IS_ALIGNED(src_stride_y, 4) &&
      IS_ALIGNED(src_u, 2) && IS_ALIGNED(src_stride_u, 2) &&
      IS_ALIGNED(src_v, 2) && IS_ALIGNED(src_stride_v, 2) &&
      IS_ALIGNED(dst_argb, 4) && IS_ALIGNED(dst_stride_argb, 4)) {
    I422ToARGBRow = I422ToARGBRow_DSPR2;
  }
#endif

  void (*InterpolateRow)(uint8* dst_argb, const uint8* src_argb,
      ptrdiff_t src_stride, int dst_width, int source_y_fraction) =
      InterpolateRow_C;
#if defined(HAS_INTERPOLATEROW_SSSE3)
  if (TestCpuFlag(kCpuHasSSSE3)) {
    InterpolateRow = InterpolateRow_Any_SSSE3;
    if (IS_ALIGNED(dst_width, 4)) {
      InterpolateRow = InterpolateRow_SSSE3;
    }
  }
#endif
#if defined(HAS_INTERPOLATEROW_AVX2)
  if (TestCpuFlag(kCpuHasAVX2)) {
    InterpolateRow = InterpolateRow_Any_AVX2;
    if (IS_ALIGNED(dst_width, 8)) {
      InterpolateRow = InterpolateRow_AVX2;
    }
  }
#endif
#if defined(HAS_INTERPOLATEROW_NEON)
  if (TestCpuFlag(kCpuHasNEON)) {
    InterpolateRow = InterpolateRow_Any_NEON;
    if (IS_ALIGNED(dst_width, 4)) {
      InterpolateRow = InterpolateRow_NEON;
    }
  }
#endif
#if defined(HAS_INTERPOLATEROW_DSPR2)
  if (TestCpuFlag(kCpuHasDSPR2) &&
      IS_ALIGNED(dst_argb, 4) && IS_ALIGNED(dst_stride_argb, 4)) {
    InterpolateRow = InterpolateRow_DSPR2;
  }
#endif

  void (*ScaleARGBFilterCols)(uint8* dst_argb, const uint8* src_argb,
      int dst_width, int x, int dx) =
      filtering ? ScaleARGBFilterCols_C : ScaleARGBCols_C;
  if (src_width >= 32768) {
    ScaleARGBFilterCols = filtering ?
        ScaleARGBFilterCols64_C : ScaleARGBCols64_C;
  }
#if defined(HAS_SCALEARGBFILTERCOLS_SSSE3)
  if (filtering && TestCpuFlag(kCpuHasSSSE3) && src_width < 32768) {
    ScaleARGBFilterCols = ScaleARGBFilterCols_SSSE3;
  }
#endif
#if defined(HAS_SCALEARGBFILTERCOLS_NEON)
  if (filtering && TestCpuFlag(kCpuHasNEON)) {
    ScaleARGBFilterCols = ScaleARGBFilterCols_Any_NEON;
    if (IS_ALIGNED(dst_width, 4)) {
      ScaleARGBFilterCols = ScaleARGBFilterCols_NEON;
    }
  }
#endif
#if defined(HAS_SCALEARGBCOLS_SSE2)
  if (!filtering && TestCpuFlag(kCpuHasSSE2) && src_width < 32768) {
    ScaleARGBFilterCols = ScaleARGBCols_SSE2;
  }
#endif
#if defined(HAS_SCALEARGBCOLS_NEON)
  if (!filtering && TestCpuFlag(kCpuHasNEON)) {
    ScaleARGBFilterCols = ScaleARGBCols_Any_NEON;
    if (IS_ALIGNED(dst_width, 8)) {
      ScaleARGBFilterCols = ScaleARGBCols_NEON;
    }
  }
#endif
  if (!filtering && src_width * 2 == dst_width && x < 0x8000) {
    ScaleARGBFilterCols = ScaleARGBColsUp2_C;
#if defined(HAS_SCALEARGBCOLSUP2_SSE2)
    if (TestCpuFlag(kCpuHasSSE2) && IS_ALIGNED(dst_width, 8)) {
      ScaleARGBFilterCols = ScaleARGBColsUp2_SSE2;
    }
#endif
  }

  const int max_y = (src_height - 1) << 16;
  if (y > max_y) {
    y = max_y;
  }
  const int kYShift = 1;  // Shift Y by 1 to convert Y plane to UV coordinate.
  int yi = y >> 16;
  int uv_yi = yi >> kYShift;
  const uint8* src_row_y = src_y + yi * src_stride_y;
  const uint8* src_row_u = src_u + uv_yi * src_stride_u;
  const uint8* src_row_v = src_v + uv_yi * src_stride_v;

  // Allocate 2 rows of ARGB.
  const int kRowSize = (dst_width * 4 + 31) & ~31;
  align_buffer_64(row, kRowSize * 2);

  // Allocate 1 row of ARGB for source conversion.
  align_buffer_64(argb_row, src_width * 4);

  uint8* rowptr = row;
  int rowstride = kRowSize;
  int lasty = yi;

  // TODO(fbarchard): Convert first 2 rows of YUV to ARGB.
  ScaleARGBFilterCols(rowptr, src_row_y, dst_width, x, dx);
  if (src_height > 1) {
    src_row_y += src_stride_y;
    if (yi & 1) {
      src_row_u += src_stride_u;
      src_row_v += src_stride_v;
    }
  }
  ScaleARGBFilterCols(rowptr + rowstride, src_row_y, dst_width, x, dx);
  if (src_height > 2) {
    src_row_y += src_stride_y;
    if (!(yi & 1)) {
      src_row_u += src_stride_u;
      src_row_v += src_stride_v;
    }
  }

  for (j = 0; j < dst_height; ++j) {
    yi = y >> 16;
    if (yi != lasty) {
      if (y > max_y) {
        y = max_y;
        yi = y >> 16;
        uv_yi = yi >> kYShift;
        src_row_y = src_y + yi * src_stride_y;
        src_row_u = src_u + uv_yi * src_stride_u;
        src_row_v = src_v + uv_yi * src_stride_v;
      }
      if (yi != lasty) {
        // TODO(fbarchard): Convert the clipped region of row.
        I422ToARGBRow(src_row_y, src_row_u, src_row_v, argb_row, src_width);
        ScaleARGBFilterCols(rowptr, argb_row, dst_width, x, dx);
        rowptr += rowstride;
        rowstride = -rowstride;
        lasty = yi;
        src_row_y += src_stride_y;
        if (yi & 1) {
          src_row_u += src_stride_u;
          src_row_v += src_stride_v;
        }
      }
    }
    if (filtering == kFilterLinear) {
      InterpolateRow(dst_argb, rowptr, 0, dst_width * 4, 0);
    } else {
      int yf = (y >> 8) & 255;
      InterpolateRow(dst_argb, rowptr, rowstride, dst_width * 4, yf);
    }
    dst_argb += dst_stride_argb;
    y += dy;
  }
  free_aligned_buffer_64(row);
  free_aligned_buffer_64(row_argb);
}
#endif

// Scale ARGB to/from any dimensions, without interpolation.
// Fixed point math is used for performance: The upper 16 bits
// of x and dx is the integer part of the source position and
// the lower 16 bits are the fixed decimal part.

static void ScaleARGBSimple(int src_width, int src_height,
                            int dst_width, int dst_height,
                            int src_stride, int dst_stride,
                            const uint8* src_argb, uint8* dst_argb,
                            int x, int dx, int y, int dy) {
  int j;
  void (*ScaleARGBCols)(uint8* dst_argb, const uint8* src_argb,
      int dst_width, int x, int dx) =
      (src_width >= 32768) ? ScaleARGBCols64_C : ScaleARGBCols_C;
#if defined(HAS_SCALEARGBCOLS_SSE2)
  if (TestCpuFlag(kCpuHasSSE2) && src_width < 32768) {
    ScaleARGBCols = ScaleARGBCols_SSE2;
  }
#endif
#if defined(HAS_SCALEARGBCOLS_NEON)
  if (TestCpuFlag(kCpuHasNEON)) {
    ScaleARGBCols = ScaleARGBCols_Any_NEON;
    if (IS_ALIGNED(dst_width, 8)) {
      ScaleARGBCols = ScaleARGBCols_NEON;
    }
  }
#endif
  if (src_width * 2 == dst_width && x < 0x8000) {
    ScaleARGBCols = ScaleARGBColsUp2_C;
#if defined(HAS_SCALEARGBCOLSUP2_SSE2)
    if (TestCpuFlag(kCpuHasSSE2) && IS_ALIGNED(dst_width, 8)) {
      ScaleARGBCols = ScaleARGBColsUp2_SSE2;
    }
#endif
  }

  for (j = 0; j < dst_height; ++j) {
    ScaleARGBCols(dst_argb, src_argb + (y >> 16) * src_stride,
                  dst_width, x, dx);
    dst_argb += dst_stride;
    y += dy;
  }
}

// ScaleARGB a ARGB.
// This function in turn calls a scaling function
// suitable for handling the desired resolutions.
static void ScaleARGB(const uint8* src, int src_stride,
                      int src_width, int src_height,
                      uint8* dst, int dst_stride,
                      int dst_width, int dst_height,
                      int clip_x, int clip_y, int clip_width, int clip_height,
                      enum FilterMode filtering) {
  // Initial source x/y coordinate and step values as 16.16 fixed point.
  int x = 0;
  int y = 0;
  int dx = 0;
  int dy = 0;
  // ARGB does not support box filter yet, but allow the user to pass it.
  // Simplify filtering when possible.
  filtering = ScaleFilterReduce(src_width, src_height,
                                dst_width, dst_height,
                                filtering);

  // Negative src_height means invert the image.
  if (src_height < 0) {
    src_height = -src_height;
    src = src + (src_height - 1) * src_stride;
    src_stride = -src_stride;
  }
  ScaleSlope(src_width, src_height, dst_width, dst_height, filtering,
             &x, &y, &dx, &dy);
  src_width = Abs(src_width);
  if (clip_x) {
    int64 clipf = (int64)(clip_x) * dx;
    x += (clipf & 0xffff);
    src += (clipf >> 16) * 4;
    dst += clip_x * 4;
  }
  if (clip_y) {
    int64 clipf = (int64)(clip_y) * dy;
    y += (clipf & 0xffff);
    src += (clipf >> 16) * src_stride;
    dst += clip_y * dst_stride;
  }

  // Special case for integer step values.
  if (((dx | dy) & 0xffff) == 0) {
    if (!dx || !dy) {  // 1 pixel wide and/or tall.
      filtering = kFilterNone;
    } else {
      // Optimized even scale down. ie 2, 4, 6, 8, 10x.
      if (!(dx & 0x10000) && !(dy & 0x10000)) {
        if (dx == 0x20000) {
          // Optimized 1/2 downsample.
          ScaleARGBDown2(src_width, src_height,
                         clip_width, clip_height,
                         src_stride, dst_stride, src, dst,
                         x, dx, y, dy, filtering);
          return;
        }
        if (dx == 0x40000 && filtering == kFilterBox) {
          // Optimized 1/4 box downsample.
          ScaleARGBDown4Box(src_width, src_height,
                            clip_width, clip_height,
                            src_stride, dst_stride, src, dst,
                            x, dx, y, dy);
          return;
        }
        ScaleARGBDownEven(src_width, src_height,
                          clip_width, clip_height,
                          src_stride, dst_stride, src, dst,
                          x, dx, y, dy, filtering);
        return;
      }
      // Optimized odd scale down. ie 3, 5, 7, 9x.
      if ((dx & 0x10000) && (dy & 0x10000)) {
        filtering = kFilterNone;
        if (dx == 0x10000 && dy == 0x10000) {
          // Straight copy.
          ARGBCopy(src + (y >> 16) * src_stride + (x >> 16) * 4, src_stride,
                   dst, dst_stride, clip_width, clip_height);
          return;
        }
      }
    }
  }
  if (dx == 0x10000 && (x & 0xffff) == 0) {
    // Arbitrary scale vertically, but unscaled vertically.
    ScalePlaneVertical(src_height,
                       clip_width, clip_height,
                       src_stride, dst_stride, src, dst,
                       x, y, dy, 4, filtering);
    return;
  }
  if (filtering && dy < 65536) {
    ScaleARGBBilinearUp(src_width, src_height,
                        clip_width, clip_height,
                        src_stride, dst_stride, src, dst,
                        x, dx, y, dy, filtering);
    return;
  }
  if (filtering) {
    ScaleARGBBilinearDown(src_width, src_height,
                          clip_width, clip_height,
                          src_stride, dst_stride, src, dst,
                          x, dx, y, dy, filtering);
    return;
  }
  ScaleARGBSimple(src_width, src_height, clip_width, clip_height,
                  src_stride, dst_stride, src, dst,
                  x, dx, y, dy);
}

LIBYUV_API
int ARGBScaleClip(const uint8* src_argb, int src_stride_argb,
                  int src_width, int src_height,
                  uint8* dst_argb, int dst_stride_argb,
                  int dst_width, int dst_height,
                  int clip_x, int clip_y, int clip_width, int clip_height,
                  enum FilterMode filtering) {
  if (!src_argb || src_width == 0 || src_height == 0 ||
      !dst_argb || dst_width <= 0 || dst_height <= 0 ||
      clip_x < 0 || clip_y < 0 ||
      clip_width > 32768 || clip_height > 32768 ||
      (clip_x + clip_width) > dst_width ||
      (clip_y + clip_height) > dst_height) {
    return -1;
  }
  ScaleARGB(src_argb, src_stride_argb, src_width, src_height,
            dst_argb, dst_stride_argb, dst_width, dst_height,
            clip_x, clip_y, clip_width, clip_height, filtering);
  return 0;
}

// Scale an ARGB image.
LIBYUV_API
int ARGBScale(const uint8* src_argb, int src_stride_argb,
              int src_width, int src_height,
              uint8* dst_argb, int dst_stride_argb,
              int dst_width, int dst_height,
              enum FilterMode filtering) {
  if (!src_argb || src_width == 0 || src_height == 0 ||
      src_width > 32768 || src_height > 32768 ||
      !dst_argb || dst_width <= 0 || dst_height <= 0) {
    return -1;
  }
  ScaleARGB(src_argb, src_stride_argb, src_width, src_height,
            dst_argb, dst_stride_argb, dst_width, dst_height,
            0, 0, dst_width, dst_height, filtering);
  return 0;
}

// Scale with YUV conversion to ARGB and clipping.
LIBYUV_API
int YUVToARGBScaleClip(const uint8* src_y, int src_stride_y,
                       const uint8* src_u, int src_stride_u,
                       const uint8* src_v, int src_stride_v,
                       uint32 src_fourcc,
                       int src_width, int src_height,
                       uint8* dst_argb, int dst_stride_argb,
                       uint32 dst_fourcc,
                       int dst_width, int dst_height,
                       int clip_x, int clip_y, int clip_width, int clip_height,
                       enum FilterMode filtering) {
  uint8* argb_buffer = (uint8*)malloc(src_width * src_height * 4);
  int r;
  I420ToARGB(src_y, src_stride_y,
             src_u, src_stride_u,
             src_v, src_stride_v,
             argb_buffer, src_width * 4,
             src_width, src_height);

  r = ARGBScaleClip(argb_buffer, src_width * 4,
                    src_width, src_height,
                    dst_argb, dst_stride_argb,
                    dst_width, dst_height,
                    clip_x, clip_y, clip_width, clip_height,
                    filtering);
  free(argb_buffer);
  return r;
}

#ifdef __cplusplus
}  // extern "C"
}  // namespace libyuv
#endif


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

#ifndef REMOTING_HOST_PLUGIN_HOST_SCRIPT_OBJECT_H_
#define REMOTING_HOST_PLUGIN_HOST_SCRIPT_OBJECT_H_

#include <string>
#include <vector>

#include "base/compiler_specific.h"
#include "base/memory/ref_counted.h"
#include "base/memory/scoped_ptr.h"
#include "base/memory/weak_ptr.h"
#include "base/strings/string16.h"
#include "base/synchronization/cancellation_flag.h"
#include "base/synchronization/lock.h"
#include "base/synchronization/waitable_event.h"
#include "base/thread_task_runner_handle.h"
#include "base/threading/platform_thread.h"
#include "base/threading/thread.h"
#include "base/time/time.h"
#include "remoting/base/auto_thread_task_runner.h"
#include "remoting/host/chromoting_host_context.h"
#include "remoting/host/log_to_server.h"
#include "remoting/host/plugin/host_plugin_utils.h"
#include "remoting/host/setup/daemon_controller.h"
#include "remoting/jingle_glue/xmpp_signal_strategy.h"
#include "remoting/protocol/pairing_registry.h"
#include "third_party/npapi/bindings/npapi.h"
#include "third_party/npapi/bindings/npfunctions.h"
#include "third_party/npapi/bindings/npruntime.h"

namespace remoting {

// NPAPI plugin implementation for remoting host script object.
// HostNPScriptObject creates threads that are required to run
// ChromotingHost and starts/stops the host on those threads. When
// destroyed it synchronously shuts down the host and all threads.
class HostNPScriptObject {
 public:
  HostNPScriptObject(NPP plugin,
                     NPObject* parent,
                     scoped_refptr<AutoThreadTaskRunner> plugin_task_runner);
  virtual ~HostNPScriptObject();

  // Implementations used to implement the NPObject interface.
  bool HasMethod(const std::string& method_name);
  bool InvokeDefault(const NPVariant* args,
                     uint32_t arg_count,
                     NPVariant* result);
  bool Invoke(const std::string& method_name,
              const NPVariant* args,
              uint32_t arg_count,
              NPVariant* result);
  bool HasProperty(const std::string& property_name);
  bool GetProperty(const std::string& property_name, NPVariant* result);
  bool SetProperty(const std::string& property_name, const NPVariant* value);
  bool RemoveProperty(const std::string& property_name);
  bool Enumerate(std::vector<std::string>* values);

  // Post LogDebugInfo to the correct proxy (and thus, on the correct thread).
  // This should only be called by HostLogHandler. To log to the UI, use the
  // standard LOG(INFO) and it will be sent to this method.
  void PostLogDebugInfo(const std::string& message);

  void SetWindow(NPWindow* np_window);

 private:
  //////////////////////////////////////////////////////////
  // Definitions for It2Me host.

  class It2MeImpl;

  // These state values are duplicated in host_session.js. Remember to update
  // both copies when making changes.
  enum State {
    kDisconnected,
    kStarting,
    kRequestedAccessCode,
    kReceivedAccessCode,
    kConnected,
    kDisconnecting,
    kError,
    kInvalidDomainError
  };

  //////////////////////////////////////////////////////////
  // Plugin methods for It2Me host.

  // Start connection. args are:
  //   string uid, string auth_token
  // No result.
  bool Connect(const NPVariant* args, uint32_t arg_count, NPVariant* result);

  // Disconnect. No arguments or result.
  bool Disconnect(const NPVariant* args, uint32_t arg_count, NPVariant* result);

  // Localize strings. args are:
  //   localize_func - a callback function which returns a localized string for
  //   a given tag name.
  // No result.
  bool Localize(const NPVariant* args, uint32_t arg_count, NPVariant* result);

  //////////////////////////////////////////////////////////
  // Plugin methods for Me2Me host.

  // Deletes all paired clients from the registry.
  bool ClearPairedClients(const NPVariant* args,
                          uint32_t arg_count,
                          NPVariant* result);

  // Deletes a paired client referenced by client id.
  bool DeletePairedClient(const NPVariant* args,
                          uint32_t arg_count,
                          NPVariant* result);

  // Fetches the host name, passing it to the supplied callback. Args are:
  //   function(string) callback
  // Returns false if the parameters are invalid.
  bool GetHostName(const NPVariant* args,
                   uint32_t arg_count,
                   NPVariant* result);

  // Calculates PIN hash value to be stored in the config. Args are:
  //   string hostId Host ID.
  //   string pin The PIN.
  //   function(string) callback
  // Passes the resulting hash value base64-encoded to the callback.
  // Returns false if the parameters are invalid.
  bool GetPinHash(const NPVariant* args,
                  uint32_t arg_count,
                  NPVariant* result);

  // Generates new key pair to use for the host. The specified
  // callback is called when when the key is generated. The key is
  // returned in format understood by the host (PublicKeyInfo
  // structure encoded with ASN.1 DER, and then BASE64). Args are:
  //   function(string) callback The callback to be called when done.
  bool GenerateKeyPair(const NPVariant* args,
                       uint32_t arg_count,
                       NPVariant* result);

  // Update host config for Me2Me. Args are:
  //   string config
  //   function(number) done_callback
  bool UpdateDaemonConfig(const NPVariant* args,
                          uint32_t arg_count,
                          NPVariant* result);

  // Loads daemon config. The first argument specifies the callback to be
  // called once the config has been loaded. The config is passed as a JSON
  // formatted string. Args are:
  //   function(string) callback
  bool GetDaemonConfig(const NPVariant* args,
                       uint32_t arg_count,
                       NPVariant* result);

  // Retrieves daemon version. The first argument specifies the callback to be
  // called with the obtained version. The version is passed as a dotted
  // version string, described in daemon_controller.h.
  bool GetDaemonVersion(const NPVariant* args,
                        uint32_t arg_count,
                        NPVariant* result);

  // Retrieves the list of paired clients as a JSON-encoded string.
  bool GetPairedClients(const NPVariant* args,
                        uint32_t arg_count,
                        NPVariant* result);

  // Retrieves the user's consent to report crash dumps. The first argument
  // specifies the callback to be called with the recorder consent. Possible
  // consent codes are defined in remoting/host/breakpad.h.
  bool GetUsageStatsConsent(const NPVariant* args,
                            uint32_t arg_count,
                            NPVariant* result);

  // Start the daemon process with the specified config. Args are:
  //   string config
  //   function(number) done_callback
  bool StartDaemon(const NPVariant* args,
                   uint32_t arg_count,
                   NPVariant* result);

  // Stop the daemon process. Args are:
  //   function(number) done_callback
  bool StopDaemon(const NPVariant* args, uint32_t arg_count, NPVariant* result);

  //////////////////////////////////////////////////////////
  // Helper methods used by the It2Me host implementation.

  // Notifies OnStateChanged handler of a state change.
  void NotifyStateChanged(State state);

  // If the web-app has registered a callback to be notified of changes to the
  // NAT traversal policy, notify it.
  void NotifyNatPolicyChanged(bool nat_traversal_enabled);

  // Stores the Access Code for the web-app to query.
  void StoreAccessCode(const std::string& access_code,
                       base::TimeDelta access_code_lifetime);

  // Stores the client user's name for the web-app to query.
  void StoreClientUsername(const std::string& client_username);

  // Used to generate localized strings to pass to the It2Me host core.
  void LocalizeStrings(NPObject* localize_func);

  // Helper function for executing InvokeDefault on an NPObject that performs
  // a string->string mapping without substitution. Stores the translation in
  // |result| and returns true on success, or leaves it unchanged and returns
  // false on failure.
  bool LocalizeString(NPObject* localize_func, const char* tag,
                      string16* result);

  // Helper function for executing InvokeDefault on an NPObject that performs
  // a string->string mapping with one substitution. Stores the translation in
  // |result| and returns true on success, or leaves it unchanged and returns
  // false on failure.
  bool LocalizeStringWithSubstitution(NPObject* localize_func,
                                      const char* tag,
                                      const char* substitution,
                                      string16* result);

  //////////////////////////////////////////////////////////
  // Helper methods for Me2Me host.

  // Helpers for GenerateKeyPair().
  void DoGenerateKeyPair(const ScopedRefNPObject& callback);
  void InvokeGenerateKeyPairCallback(const ScopedRefNPObject& callback,
                                     const std::string& private_key,
                                     const std::string& public_key);

  // Callback handler for SetConfigAndStart(), Stop(), SetPin() and
  // SetUsageStatsConsent() in DaemonController.
  void InvokeAsyncResultCallback(const ScopedRefNPObject& callback,
                                 DaemonController::AsyncResult result);

  // Callback handler for PairingRegistry methods that return a boolean
  // success status.
  void InvokeBooleanCallback(const ScopedRefNPObject& callback, bool result);

  // Callback handler for DaemonController::GetConfig().
  void InvokeGetDaemonConfigCallback(const ScopedRefNPObject& callback,
                                     scoped_ptr<base::DictionaryValue> config);

  // Callback handler for DaemonController::GetVersion().
  void InvokeGetDaemonVersionCallback(const ScopedRefNPObject& callback,
                                      const std::string& version);

  // Callback handler for GetPairedClients().
  void InvokeGetPairedClientsCallback(
      const ScopedRefNPObject& callback,
      scoped_ptr<base::ListValue> paired_clients);

  // Callback handler for DaemonController::GetUsageStatsConsent().
  void InvokeGetUsageStatsConsentCallback(const ScopedRefNPObject& callback,
                                          bool supported,
                                          bool allowed,
                                          bool set_by_policy);

  //////////////////////////////////////////////////////////
  // Basic helper methods used for both It2Me and Me2me.

  // Call LogDebugInfo handler if there is one.
  // This must be called on the correct thread.
  void LogDebugInfo(const std::string& message);

  // Helper function for executing InvokeDefault on an NPObject, and ignoring
  // the return value.
  bool InvokeAndIgnoreResult(NPObject* func,
                             const NPVariant* args,
                             uint32_t arg_count);

  // Set an exception for the current call.
  void SetException(const std::string& exception_string);

  //////////////////////////////////////////////////////////
  // Plugin state variables shared between It2Me and Me2Me.

  NPP plugin_;
  NPObject* parent_;
  scoped_refptr<AutoThreadTaskRunner> plugin_task_runner_;
  scoped_ptr<base::ThreadTaskRunnerHandle> plugin_task_runner_handle_;

  // True if we're in the middle of handling a log message.
  bool am_currently_logging_;

  ScopedRefNPObject log_debug_info_func_;

  //////////////////////////////////////////////////////////
  // It2Me host state.

  // Internal implementation of the It2Me host function.
  scoped_refptr<It2MeImpl> it2me_impl_;

  // Cached, read-only copies of |it2me_impl_| session state.
  State state_;
  std::string access_code_;
  base::TimeDelta access_code_lifetime_;
  std::string client_username_;

  // IT2Me Talk server configuration used by |it2me_impl_| to connect.
  XmppSignalStrategy::XmppServerConfig xmpp_server_config_;

  // Chromoting Bot JID used by |it2me_impl_| to register the host.
  std::string directory_bot_jid_;

  // Callbacks to notify in response to |it2me_impl_| events.
  ScopedRefNPObject on_nat_traversal_policy_changed_func_;
  ScopedRefNPObject on_state_changed_func_;

  //////////////////////////////////////////////////////////
  // Me2Me host state.

  // Platform-specific installation & configuration implementation.
  scoped_ptr<DaemonController> daemon_controller_;

  // TODO(sergeyu): Replace this thread with
  // SequencedWorkerPool. Problem is that SequencedWorkerPool relies
  // on MessageLoopProxy::current().
  scoped_refptr<AutoThreadTaskRunner> worker_thread_;

  // Used to load and update the paired clients for this host.
  scoped_refptr<protocol::PairingRegistry> pairing_registry_;

  //////////////////////////////////////////////////////////
  // Plugin state used for both Ir2Me and Me2Me.

  // Used to cancel pending tasks for this object when it is destroyed.
  base::WeakPtrFactory<HostNPScriptObject> weak_factory_;
  base::WeakPtr<HostNPScriptObject> weak_ptr_;

  DISALLOW_COPY_AND_ASSIGN(HostNPScriptObject);
};

}  // namespace remoting

#endif  // REMOTING_HOST_PLUGIN_HOST_SCRIPT_OBJECT_H_


/***************************************************************************
 *   This file is part of the CuteReport project                           *
 *   Copyright (C) 2013-2014 by Alexander Mikhalov                         *
 *   alexander.mikhalov@gmail.com                                          *
 *                                                                         *
 **                   GNU General Public License Usage                    **
 *                                                                         *
 *   This library is free software: you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation, either version 3 of the License, or     *
 *   (at your option) any later version.                                   *
 *   You should have received a copy of the GNU General Public License     *
 *   along with this program.  If not, see <http://www.gnu.org/licenses/>. *
 *                                                                         *
 **                  GNU Lesser General Public License                    **
 *                                                                         *
 *   This library is free software: you can redistribute it and/or modify  *
 *   it under the terms of the GNU Lesser General Public License as        *
 *   published by the Free Software Foundation, either version 3 of the    *
 *   License, or (at your option) any later version.                       *
 *   You should have received a copy of the GNU Lesser General Public      *
 *   License along with this library.                                      *
 *   If not, see <http://www.gnu.org/licenses/>.                           *
 *                                                                         *
 *   This library is distributed in the hope that it will be useful,       *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU General Public License for more details.                          *
 ***************************************************************************/
#include "csvdataset.h"
#include "csvdatasethelper.h"
#include "csvdatasetmodel.h"
#include "reportcore.h"
#include "cutereport_functions.h"

#include <QtCore>
#include <QIcon>

#define DATASET_NAME "CSV"

using namespace CuteReport;

CsvDataset::CsvDataset(QObject *parent)
    : DatasetInterface(parent),
      m_firstRowIsHeader(false),
      m_currentRow(0),
      m_isPopulated(false),
      m_delimeter(","),
      m_fixFileIssues(false)
{
    m_model = new Model (this);
    m_fmodel = new QSortFilterProxyModel(this);
    m_fmodel->setSourceModel(m_model);
}

CsvDataset::CsvDataset(const CsvDataset &dd, QObject * parent)
    : DatasetInterface(parent),
      m_firstRowIsHeader(dd.m_firstRowIsHeader),
      m_currentRow(0),
      m_isPopulated(false),
      m_delimeter(dd.m_delimeter),
      m_fixFileIssues(dd.m_fixFileIssues)
{
    m_model = new Model (this);
    m_fmodel = new QSortFilterProxyModel(this);
    m_fmodel->setSourceModel(m_model);
    if (dd.m_isPopulated) {
        populate();
        setCurrentRowNumber(dd.m_currentRow);
    }
}

CsvDataset::~CsvDataset()
{
}

QIcon CsvDataset::icon()
{
    QIcon icon(":/images/csv.jpeg");
    return icon;
}

DatasetInterface * CsvDataset::createInstance(QObject* parent) const
{
    return new CsvDataset(parent);
}

DatasetHelperInterface * CsvDataset::helper()
{
    if (!m_helper)
        m_helper = new CsvDatasetHelper(this);

    return m_helper;
}

DatasetInterface *CsvDataset::objectClone() const
{
    return new CsvDataset(*this, parent());
}

QString CsvDataset::moduleShortName() const
{
    return QString("CSV");
}

QSet<QString> CsvDataset::variables() const
{
    QSet<QString> set;

    set.unite( findVariables(m_fileName) );

    return set;
}

QString CsvDataset::getLastError()
{
    return m_lastError;
}

QString	CsvDataset::getFileName() const
{
    return m_fileName;
}

void CsvDataset::setFileName(const QString &str)
{
    if (m_fileName == str)
        return;

    m_fileName = str;

    emit fileNameChanged(m_fileName);
    emit changed();
}

QString CsvDataset::getDelimeter () const
{
    return m_delimeter;
}

void CsvDataset::setDelimeter (const QString &str)
{
    if (m_delimeter == str)
        return;

    m_delimeter = str;

    emit delimiterChanged(m_delimeter);
    emit changed();
}

bool CsvDataset::getFirstRowIsHeader()
{
    return m_firstRowIsHeader;
}

void CsvDataset::setFirstRowIsHeader(bool value)
{
    if (m_firstRowIsHeader == value)
        return;

    m_firstRowIsHeader = value;

    emit firstRowIsHeaderChanged(m_firstRowIsHeader);
    emit changed();
}

bool CsvDataset::getFixFileIssues()
{
    return m_fixFileIssues;
}

void CsvDataset::setFixFileIssues(bool value)
{
    if (m_fixFileIssues == value)
        return;
    m_fixFileIssues = value;

    emit fixFileIssuesChanged(m_fixFileIssues);
    emit changed();
}

QByteArray CsvDataset::fixIssues(const QByteArray &ba)
{
    QString str(ba);
    str.replace(QRegExp("\r\n|\n|\r"),"\n");
    return str.toUtf8();
}

QString CsvDataset::getFieldName(int column )
{
    return m_model->headerData ( column, Qt::Horizontal).toString();
}

QVariant::Type CsvDataset::getFieldType(int column)
{
    Q_UNUSED(column);
    return QVariant::String;
}

QAbstractItemModel * CsvDataset::model()
{
    return m_fmodel;
}

bool CsvDataset::populate()
{
    emit beforePopulate();

    QStringList list;

    if (m_fileName.isEmpty()) {
        m_lastError = tr("Filename is empty. Please enter a filename first");
        return false;
    }

    CuteReport::ReportInterface * report = static_cast<CuteReport::ReportInterface*> (parent());

    QStringList missedVariables;
    if (!isStringValued(m_fileName, report->variables(), &missedVariables)) {
        m_lastError = QString("Variable is not defined in the \'File\' field: %1").arg(missedVariables.join(", "));
        return false;
    }

    QString fileURL = report ? setVariablesValue(m_fileName, report->variables()) : m_fileName;

    QByteArray fileData = reportCore()->loadObject(fileURL, report);
    if (m_fixFileIssues)
        fileData = fixIssues(fileData);

    QTextStream stream(fileData, QIODevice::Text| QIODevice::ReadOnly | QIODevice::Unbuffered);
    stream.setAutoDetectUnicode(true);

    QString line;
    do {
        line = stream.readLine();
        list << line;
    } while (!line.isNull());

    Array array;
    m_model->setHeader((m_firstRowIsHeader && !list.isEmpty()) ? list[0].split(m_delimeter) : QStringList());

    for (int i = (m_firstRowIsHeader ? 1:0); i<list.count(); i++) {
        array.append(list.at(i).split(m_delimeter));
    }
    m_model->setArray(array);

    m_isPopulated = true;
    m_currentRow = array.size() > 0 ? 0 : -1;

    emit afterPopulate();
    return true;
}

bool CsvDataset::isPopulated()
{
    return m_isPopulated;
}

void CsvDataset::setPopulated(bool b)
{
    m_isPopulated = b;
}

void CsvDataset::reset()
{
    m_isPopulated = false;
    m_model->clear();
    m_currentRow = -1;
    m_lastError = "";
}

void CsvDataset::resetCursor()
{
    m_currentRow = -1;
}

bool CsvDataset::setFirstRow()
{
    populateIfNotPopulated();
    emit(beforeFirst());
    m_currentRow = 0;
    bool ret = getRowCount();
    emit(afterFirst());
    return ret;
}

bool CsvDataset::setLastRow()
{
    populateIfNotPopulated();
    emit(beforeLast());
    m_currentRow = m_fmodel->rowCount();
    bool ret = m_currentRow < m_fmodel->rowCount() ? true:false;
    emit(afterLast());
    return ret;
}

bool CsvDataset::setNextRow()
{
    populateIfNotPopulated();
    emit(beforeNext());
    m_currentRow++;
    bool ret = m_currentRow < getRowCount();
    emit(afterNext());
    return ret;
}

bool CsvDataset::setPreviousRow()
{
    populateIfNotPopulated();
    emit(beforePrevious());
    m_currentRow--;
    bool ret = m_currentRow >= 0;
    emit(afterPrevious());
    return ret;
}

int CsvDataset::getCurrentRowNumber()
{
    return m_currentRow;
}

bool CsvDataset::setCurrentRowNumber(int index)
{
    populateIfNotPopulated();
    emit(beforeSeek(index));
    m_currentRow = index;
    bool ret = (m_currentRow >=0 && m_currentRow < m_fmodel->rowCount() ? true:false);
    emit(afterSeek(index));
    return ret;
}

int CsvDataset::getRowCount()
{
    populateIfNotPopulated();
    return m_fmodel->rowCount();
}

int CsvDataset::getColumnCount()
{
    populateIfNotPopulated();
    return m_fmodel->columnCount();
}

QVariant CsvDataset::getValue(int column)
{    populateIfNotPopulated();
     return m_fmodel->data( m_fmodel->index(m_currentRow,column) );
}

QVariant CsvDataset::getValue(const QString & fieldName)
{
    populateIfNotPopulated();
    return getValue(m_model->fieldIndex(fieldName));
}

QVariant CsvDataset::getNextRowValue(int column)
{
    populateIfNotPopulated();
    return m_model->data(m_model->index(m_currentRow+1, column));
}

QVariant CsvDataset::getNextRowValue(const QString & fieldName)
{
    populateIfNotPopulated();
    return getNextRowValue(m_model->fieldIndex(fieldName));
}

QVariant CsvDataset::getPreviousRowValue(int column)
{
    populateIfNotPopulated();
    return m_model->data(m_model->index(m_currentRow+1, column));
}

QVariant CsvDataset::getPreviousRowValue(const QString & fieldName)
{
    populateIfNotPopulated();
    return getPreviousRowValue(m_model->fieldIndex(fieldName));
}

#if QT_VERSION < 0x050000
Q_EXPORT_PLUGIN2(DatasetCSV, CsvDataset)
#endif


00:01 So here's an interesting question— what if I want to find all the books
00:03 where user 720 has rated that book exactly a nine.
00:09 You would think that this would do it, right,
00:11 we're using both values in this prototypical object or this document here
00:15 and it says that the book is going to have to have
00:18 a rating of nine and user id 720 has rated it.
00:21 However, when we run this, you'll see we get mixed results.
00:24 The bottom one looks perfect, we got a book with the user id 720
00:29 an a value of nine in the ratings, great;
00:32 but this other one, what's up with this, the red one?
00:34 Well, user 601 rated this as a nine,
00:38 and user 720 actually hated the book, they gave it a one.
00:41 However, taken as a whole, does the book have a rating by user id 720— yes,
00:46 does it have a rating of nine— yes, so it matches this and clause.
00:49 So, oftentimes if you're looking for this exact subdocument match
00:54 and that thing you're looking in is an array
00:56 so ratings is an array of documents, if ratings was one subdocument,
01:00 this would work fine, but if it's an array and you want to say
01:04 I need to make sure that the thing in that array is
01:07 that subdocument itself matches value and user id as I've specified here
01:11 you need a different query operator, and that is dollar element match;
01:15 so you can run this and it'll look down inside and say
01:18 I want to find all the things in ratings,
01:21 where both, the user id is 720 and the value is nine.
01:25 So this is a slightly more complex version
01:27 that you have to run and you have to use
01:29 because you run into that problem we had before
01:31 where somebody voted a 9, user 720 voted,
01:33 but it was not user 720 who voted nine.
01:35 So a little bit different than if you were working in
01:38 say a sequel traditional tabular language
01:41 because you don't ever have this kind of duplication within the one result,
01:45 so it would be a lot simpler, but this is something
01:48 that you kind of got to get your head around a little bit,
01:50 you luckily don't use it very often, and if you are using the higher level of things
01:54 like MongoEngine, you won't run into it,
01:56 but down here at the shell or in PyMongo,
01:58 you have to be really careful if this is actually
02:00 the question you're trying to ask and answer.


package com.softwaremill.codebrag.eventstream

import com.softwaremill.codebrag.common.Clock
import com.softwaremill.codebrag.domain._
import org.joda.time.DateTime

sealed trait Hook {
  val hookDate: DateTime
  def hookName: String
}

case class LikeHook(
   commitInfo: Option[CommitInfo],
   likedBy: Option[User],
   like: Like,
   override val hookName: String
  )(implicit clock: Clock)
  extends Hook {

  override val hookDate: DateTime = clock.nowUtc
}

case class UnlikeHook(
  commitInfo: Option[CommitInfo],
  unlikedBy: Option[User],
  like: Like,
  override val hookName: String
  ) (implicit clock: Clock)
  extends Hook {

  override val hookDate: DateTime = clock.nowUtc
}

case class CommentAddedHook(
  commitInfo: Option[CommitInfo],
  commentedBy: Option[User],
  comment: Comment,
  override val hookName: String
  ) (implicit clock: Clock)
  extends Hook {

  override val hookDate: DateTime = clock.nowUtc
}

case class CommitReviewedHook(
  commitInfo: CommitInfo,
  reviewedBy: Option[User],
  override val hookName: String
  ) (implicit clock: Clock)
  extends Hook {

  override val hookDate: DateTime = clock.nowUtc
}

case class AllCommitsReviewedHook(
  repoName: String,
  branchName: String,
  reviewedBy: Option[User],
  override val hookName: String
  ) (implicit clock: Clock)
  extends Hook {

  override val hookDate: DateTime = clock.nowUtc
}

case class NewCommitsLoadedHook(
  user: Option[User],
  repoName: String,
  currentSHA: String,
  newCommits: List[PartialCommitInfo],
  override val hookName: String
  ) (implicit clock: Clock)
  extends Hook {

  override val hookDate: DateTime = clock.nowUtc
}

case class NewUserRegisteredHook(
  newUser: Option[User],
  login: String,
  fullName: String,
  override val hookName: String
  ) (implicit clock: Clock)
  extends Hook {

  override val hookDate: DateTime = clock.nowUtc
}