<commit_before>#include "QR.h"

using namespace cv;
using namespace std;
using namespace zbar;

QR::QR(CV_Handler *cv) {
    initializeQR();
    cvHandler = cv;
}

int QR::checkQR(void) {

    cv::Mat img(cvHandler->storedImageBW.size().y,
                  cvHandler->storedImageBW.size().x,
                    CV_8UC1,
                  cvHandler->storedImageBW.data());

    ImageScanner scanner;
    scanner.set_config(ZBAR_NONE, ZBAR_CFG_ENABLE, 1);

    {
        Mat grey;

        cvtColor(img,grey,CV_BGR2GRAY);
        int width = img.cols;
        int height = img.rows;
        uchar *raw = grey.data;

        // wrap image data
        Image image(width, height, "Y800", raw, width * height);

        // scan the image for barcodes
        int n = scanner.scan(image);                    // Returns number of codes in the image.
        //cout << "Number of QR codes in the image is " << n << endl;
        int x0[5], x1[5], x2[5], x3[5], y0[5], y1[5], y2[5], y3[5], xsize[5], ysize[5], xmidt[5], ymidt[5], QRsize[5];
        int QRcount = 0;    // Used to seperate the found QR codes
        double QRdistance[5];

        // extract results
        for(Image::SymbolIterator symbol = image.symbol_begin()    ; symbol != image.symbol_end()     ; ++symbol) {
            vector<Point> vp;

            // do something useful with results
            //cout << "decoded " << symbol->get_type_name() << " symbol \"" << symbol->get_data() << '"' << " " << endl;
            int n = symbol->get_location_size();        // Returns 4 if QR code is scanned
            for (int i = 0; i < n; i++) {
                vp.push_back(Point(symbol->get_location_x(i), symbol->get_location_y(i)));      //Update VP
                //cout << "symbol->get_location_x = " << symbol->get_location_x(i) << endl;
                //cout << "symbol->get_location_y = " << symbol->get_location_y(i) << endl;
            }

            //cout << "vp = " << vp.at(1) << endl;
            //cout << "myvector contains:";
            //½cout << "VectorPoint contains " << vp << endl;
            //std::cout << '\n';
            x0[QRcount] = symbol->get_location_x(0);    //
            x1[QRcount] = symbol->get_location_x(1);    //
            x2[QRcount] = symbol->get_location_x(2);    //
            x3[QRcount] = symbol->get_location_x(3);    //  Saves the size of the QR code being detected
            y0[QRcount] = symbol->get_location_y(0);    //
            y1[QRcount] = symbol->get_location_y(1);    //
            y2[QRcount] = symbol->get_location_y(2);    //
            y3[QRcount] = symbol->get_location_y(3);    //

            xsize[QRcount] = (abs((x0[QRcount] - x2[QRcount]))+abs((x1[QRcount]-x3[QRcount])))/2;      // Vertical size of the QR
            ysize[QRcount] = (abs((y0[QRcount] - y2[QRcount]))+abs((y3[QRcount]-y1[QRcount])))/2;      // Horizontal size of the QR

            xmidt[QRcount] = (x0[QRcount]+x1[QRcount]+x2[QRcount]+x3[QRcount])/4;           // The horizontal middle of the QR
            ymidt[QRcount] = (y0[QRcount]+y1[QRcount]+y2[QRcount]+y3[QRcount])/4;           // The vertical middle of the QR

            QRsize[QRcount] = (xsize[QRcount]+ysize[QRcount])/2;                    // The size of the QR
            QRdistance[QRcount] = (-0.000003055555555555479*(QRsize[QRcount]^3))+(0.0009988095238095032*(QRsize[QRcount]^2))-(0.120253968253967*QRsize[QRcount])+6.30;

            cout << "QR[" << QRcount << "], Placering (x,y) = " << xmidt[QRcount] << "," << ymidt[QRcount] << ". Distance = " << calculateDistance(QRsize[QRcount])
            << "cm, with the text: " << symbol->get_data() << endl << endl;

            int yleft[5], yright[5];
            yleft[QRcount] = y1[QRcount] - y0[QRcount];
            yright[QRcount] = y2[QRcount] - y3[QRcount];

            //int displacementAngle[5];
            //displacementAngle[QRcount] =

            cout << "Yleft = " << yleft[QRcount] << ", Yright = " << yright[QRcount] << endl;

            //cout<<"Angle: "<<r.angle<<endl;
            QRcount++;
        }
        return 0;
        /*imshow("MyVideo", frame); //show the frame in "MyVideo" window
        if (waitKey(30) == 27) //wait for 'esc' key press for 30ms. If 'esc' key is pressed, break loop
        {
            cout << "esc key is pressed by user" << endl;
            break;
        }*/
    }
}

double QR::calculateDistance(int pixel){
    if(pixel < 38) return -1;       // If distance is more than 2,9m
    else if (pixel > 130) return -2;    // If distance is less than 1m.
    else return distanceToQR[pixel]; // Returns distance in cm.
}

void QR::initializeQR() {
    string value;
    int i = 0;
    ifstream file ( "../workspaces/dronemis_ws/src/dronemis/src/OpenCv/WallCoordinates.csv" );
    if (!file.good())
        cout << "Unable to read QR csv file" << endl;
    getline(file, value);

    while (!file.eof()) {
        getline ( file, value, ';' );
        QRWallCode[i].name = value;
        getline ( file, value, ';' );
        QRWallCode[i].x = std::atoi(value.c_str());
        getline ( file, value );
        QRWallCode[i].y = std::atoi(value.c_str());
        i++;
    }

    cout << i << " QR codes initialized" << endl;

    distanceToQR[38] = 310;
    distanceToQR[39] = 298;
    distanceToQR[40] = 290;
    distanceToQR[41] = 284;
    distanceToQR[42] = 279;
    distanceToQR[43] = 274;
    distanceToQR[44] = 269;
    distanceToQR[45] = 264;
    distanceToQR[46] = 259;
    distanceToQR[47] = 254;
    distanceToQR[48] = 250;
    distanceToQR[49] = 245;
    distanceToQR[50] = 241;
    distanceToQR[51] = 236;
    distanceToQR[52] = 232;
    distanceToQR[53] = 228;
    distanceToQR[54] = 224;
    distanceToQR[55] = 220;
    distanceToQR[56] = 217;
    distanceToQR[57] = 213;
    distanceToQR[58] = 209;
    distanceToQR[59] = 206;
    distanceToQR[60] = 203;
    distanceToQR[61] = 199;
    distanceToQR[62] = 196;
    distanceToQR[63] = 193;
    distanceToQR[64] = 190;
    distanceToQR[65] = 187;
    distanceToQR[66] = 184;
    distanceToQR[67] = 181;
    distanceToQR[68] = 179;
    distanceToQR[69] = 176;
    distanceToQR[70] = 173;
    distanceToQR[71] = 171;
    distanceToQR[72] = 168;
    distanceToQR[73] = 166;
    distanceToQR[74] = 164;
    distanceToQR[75] = 161;
    distanceToQR[76] = 159;
    distanceToQR[77] = 157;
    distanceToQR[78] = 155;
    distanceToQR[79] = 153;
    distanceToQR[80] = 151;
    distanceToQR[81] = 149;
    distanceToQR[82] = 148;
    distanceToQR[83] = 146;
    distanceToQR[84] = 144;
    distanceToQR[85] = 142;
    distanceToQR[86] = 141;
    distanceToQR[87] = 139;
    distanceToQR[88] = 137;
    distanceToQR[89] = 136;
    distanceToQR[90] = 136;
    distanceToQR[91] = 133;
    distanceToQR[92] = 132;
    distanceToQR[93] = 130;
    distanceToQR[94] = 129;
    distanceToQR[95] = 128;
    distanceToQR[96] = 126;
    distanceToQR[97] = 125;
    distanceToQR[98] = 124;
    distanceToQR[99] = 122;
    distanceToQR[100] = 121;
    distanceToQR[101] = 120;
    distanceToQR[102] = 119;
    distanceToQR[103] = 118;
    distanceToQR[104] = 116;
    distanceToQR[105] = 115;
    distanceToQR[106] = 114;
    distanceToQR[107] = 113;
    distanceToQR[108] = 112;
    distanceToQR[109] = 111;
    distanceToQR[110] = 110;
    distanceToQR[111] = 108;
    distanceToQR[112] = 108;
    distanceToQR[113] = 106;
    distanceToQR[114] = 105;
    distanceToQR[115] = 104;
    distanceToQR[116] = 103;
    distanceToQR[117] = 101;
    distanceToQR[118] = 100;
    distanceToQR[119] = 99;
    distanceToQR[120] = 98;
    distanceToQR[121] = 97;
    distanceToQR[122] = 96;
    distanceToQR[123] = 95;
    distanceToQR[124] = 94;
    distanceToQR[125] = 93;
    distanceToQR[126] = 92;
    distanceToQR[127] = 91;
    distanceToQR[128] = 90;
    distanceToQR[129] = 89;
    distanceToQR[130] = 88;
}

<commit_msg>Changed cout to ROS_INFO() to get time-stamps<commit_after>#include "QR.h"

using namespace cv;
using namespace std;
using namespace zbar;

QR::QR(CV_Handler *cv) {
    initializeQR();
    cvHandler = cv;
}

int QR::checkQR(void) {

    cv::Mat img(cvHandler->storedImageBW.size().y,
                  cvHandler->storedImageBW.size().x,
                    CV_8UC1,
                  cvHandler->storedImageBW.data());

    ImageScanner scanner;
    scanner.set_config(ZBAR_NONE, ZBAR_CFG_ENABLE, 1);

    {
        Mat grey;

        cvtColor(img,grey,CV_BGR2GRAY);
        int width = img.cols;
        int height = img.rows;
        uchar *raw = grey.data;

        // wrap image data
        Image image(width, height, "Y800", raw, width * height);

        // scan the image for barcodes
        int n = scanner.scan(image);                    // Returns number of codes in the image.
        //cout << "Number of QR codes in the image is " << n << endl;
        int x0[5], x1[5], x2[5], x3[5], y0[5], y1[5], y2[5], y3[5], xsize[5], ysize[5], xmidt[5], ymidt[5], QRsize[5];
        int QRcount = 0;    // Used to seperate the found QR codes
        double QRdistance[5];

        // extract results
        for(Image::SymbolIterator symbol = image.symbol_begin()    ; symbol != image.symbol_end()     ; ++symbol) {
            vector<Point> vp;

            // do something useful with results
            //cout << "decoded " << symbol->get_type_name() << " symbol \"" << symbol->get_data() << '"' << " " << endl;
            int n = symbol->get_location_size();        // Returns 4 if QR code is scanned
            for (int i = 0; i < n; i++) {
                vp.push_back(Point(symbol->get_location_x(i), symbol->get_location_y(i)));      //Update VP
                //cout << "symbol->get_location_x = " << symbol->get_location_x(i) << endl;
                //cout << "symbol->get_location_y = " << symbol->get_location_y(i) << endl;
            }

            //cout << "vp = " << vp.at(1) << endl;
            //cout << "myvector contains:";
            //½cout << "VectorPoint contains " << vp << endl;
            //std::cout << '\n';
            x0[QRcount] = symbol->get_location_x(0);    //
            x1[QRcount] = symbol->get_location_x(1);    //
            x2[QRcount] = symbol->get_location_x(2);    //
            x3[QRcount] = symbol->get_location_x(3);    //  Saves the size of the QR code being detected
            y0[QRcount] = symbol->get_location_y(0);    //
            y1[QRcount] = symbol->get_location_y(1);    //
            y2[QRcount] = symbol->get_location_y(2);    //
            y3[QRcount] = symbol->get_location_y(3);    //

            xsize[QRcount] = (abs((x0[QRcount] - x2[QRcount]))+abs((x1[QRcount]-x3[QRcount])))/2;      // Vertical size of the QR
            ysize[QRcount] = (abs((y0[QRcount] - y2[QRcount]))+abs((y3[QRcount]-y1[QRcount])))/2;      // Horizontal size of the QR

            xmidt[QRcount] = (x0[QRcount]+x1[QRcount]+x2[QRcount]+x3[QRcount])/4;           // The horizontal middle of the QR
            ymidt[QRcount] = (y0[QRcount]+y1[QRcount]+y2[QRcount]+y3[QRcount])/4;           // The vertical middle of the QR

            QRsize[QRcount] = (xsize[QRcount]+ysize[QRcount])/2;                    // The size of the QR
            QRdistance[QRcount] = (-0.000003055555555555479*(QRsize[QRcount]^3))+(0.0009988095238095032*(QRsize[QRcount]^2))-(0.120253968253967*QRsize[QRcount])+6.30;

            cout << "QR[" << QRcount << "], Placering (x,y) = " << xmidt[QRcount] << "," << ymidt[QRcount] << ". Distance = " << calculateDistance(QRsize[QRcount])
            << "cm, with the text: " << symbol->get_data() << endl << endl;

            int yleft[5], yright[5];
            yleft[QRcount] = y1[QRcount] - y0[QRcount];
            yright[QRcount] = y2[QRcount] - y3[QRcount];

            //int displacementAngle[5];
            //displacementAngle[QRcount] =

            cout << "Yleft = " << yleft[QRcount] << ", Yright = " << yright[QRcount] << endl;

            //cout<<"Angle: "<<r.angle<<endl;
            QRcount++;
        }
        return 0;
        /*imshow("MyVideo", frame); //show the frame in "MyVideo" window
        if (waitKey(30) == 27) //wait for 'esc' key press for 30ms. If 'esc' key is pressed, break loop
        {
            cout << "esc key is pressed by user" << endl;
            break;
        }*/
    }
}

double QR::calculateDistance(int pixel){
    if(pixel < 38) return -1;       // If distance is more than 2,9m
    else if (pixel > 130) return -2;    // If distance is less than 1m.
    else return distanceToQR[pixel]; // Returns distance in cm.
}

void QR::initializeQR() {
    string value;
    int i = 0;
    ifstream file ( "../workspaces/dronemis_ws/src/dronemis/src/OpenCv/WallCoordinates.csv" );
    if (!file.good())
        ROS_INFO("Unable to read QR csv file");

    getline(file, value);
    while (!file.eof()) {
        getline ( file, value, ';' );
        QRWallCode[i].name = value;
        getline ( file, value, ';' );
        QRWallCode[i].x = std::atoi(value.c_str());
        getline ( file, value );
        QRWallCode[i].y = std::atoi(value.c_str());
        i++;
    }

    ROS_INFO("%d QR codes initialized", i);

    distanceToQR[38] = 310;
    distanceToQR[39] = 298;
    distanceToQR[40] = 290;
    distanceToQR[41] = 284;
    distanceToQR[42] = 279;
    distanceToQR[43] = 274;
    distanceToQR[44] = 269;
    distanceToQR[45] = 264;
    distanceToQR[46] = 259;
    distanceToQR[47] = 254;
    distanceToQR[48] = 250;
    distanceToQR[49] = 245;
    distanceToQR[50] = 241;
    distanceToQR[51] = 236;
    distanceToQR[52] = 232;
    distanceToQR[53] = 228;
    distanceToQR[54] = 224;
    distanceToQR[55] = 220;
    distanceToQR[56] = 217;
    distanceToQR[57] = 213;
    distanceToQR[58] = 209;
    distanceToQR[59] = 206;
    distanceToQR[60] = 203;
    distanceToQR[61] = 199;
    distanceToQR[62] = 196;
    distanceToQR[63] = 193;
    distanceToQR[64] = 190;
    distanceToQR[65] = 187;
    distanceToQR[66] = 184;
    distanceToQR[67] = 181;
    distanceToQR[68] = 179;
    distanceToQR[69] = 176;
    distanceToQR[70] = 173;
    distanceToQR[71] = 171;
    distanceToQR[72] = 168;
    distanceToQR[73] = 166;
    distanceToQR[74] = 164;
    distanceToQR[75] = 161;
    distanceToQR[76] = 159;
    distanceToQR[77] = 157;
    distanceToQR[78] = 155;
    distanceToQR[79] = 153;
    distanceToQR[80] = 151;
    distanceToQR[81] = 149;
    distanceToQR[82] = 148;
    distanceToQR[83] = 146;
    distanceToQR[84] = 144;
    distanceToQR[85] = 142;
    distanceToQR[86] = 141;
    distanceToQR[87] = 139;
    distanceToQR[88] = 137;
    distanceToQR[89] = 136;
    distanceToQR[90] = 136;
    distanceToQR[91] = 133;
    distanceToQR[92] = 132;
    distanceToQR[93] = 130;
    distanceToQR[94] = 129;
    distanceToQR[95] = 128;
    distanceToQR[96] = 126;
    distanceToQR[97] = 125;
    distanceToQR[98] = 124;
    distanceToQR[99] = 122;
    distanceToQR[100] = 121;
    distanceToQR[101] = 120;
    distanceToQR[102] = 119;
    distanceToQR[103] = 118;
    distanceToQR[104] = 116;
    distanceToQR[105] = 115;
    distanceToQR[106] = 114;
    distanceToQR[107] = 113;
    distanceToQR[108] = 112;
    distanceToQR[109] = 111;
    distanceToQR[110] = 110;
    distanceToQR[111] = 108;
    distanceToQR[112] = 108;
    distanceToQR[113] = 106;
    distanceToQR[114] = 105;
    distanceToQR[115] = 104;
    distanceToQR[116] = 103;
    distanceToQR[117] = 101;
    distanceToQR[118] = 100;
    distanceToQR[119] = 99;
    distanceToQR[120] = 98;
    distanceToQR[121] = 97;
    distanceToQR[122] = 96;
    distanceToQR[123] = 95;
    distanceToQR[124] = 94;
    distanceToQR[125] = 93;
    distanceToQR[126] = 92;
    distanceToQR[127] = 91;
    distanceToQR[128] = 90;
    distanceToQR[129] = 89;
    distanceToQR[130] = 88;
}

<|endoftext|>


<commit_before><commit_msg>Disable it for real this time.<commit_after><|endoftext|>


<commit_before>// Copyright (c) 2011 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/safe_browsing/malware_dom_details.h"

#include "base/compiler_specific.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/render_messages.h"
#include "chrome/common/render_messages_params.h"
#include "chrome/renderer/render_view.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebDocument.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebElement.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebFrame.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebNodeCollection.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebString.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebView.h"

namespace safe_browsing {

// An upper limit on the number of nodes we collect.
uint32 MalwareDOMDetails::kMaxNodes = 500;

MalwareDOMDetails::MalwareDOMDetails(RenderView* render_view)
    : RenderViewObserver(render_view),
      render_view_(render_view) {
}

MalwareDOMDetails::~MalwareDOMDetails() {
}

bool MalwareDOMDetails::OnMessageReceived(const IPC::Message& message) {
  bool handled = true;
  IPC_BEGIN_MESSAGE_MAP(MalwareDOMDetails, message)
    IPC_MESSAGE_HANDLER(ViewMsg_GetMalwareDOMDetails, OnGetMalwareDOMDetails)
    IPC_MESSAGE_UNHANDLED(handled = false)
  IPC_END_MESSAGE_MAP()
  return handled;
}

void MalwareDOMDetails::OnGetMalwareDOMDetails() {
  ViewHostMsg_MalwareDOMDetails_Params resources;
  ExtractResources(&resources);
  // Notify the browser.
  render_view()->Send(new ViewHostMsg_MalwareDOMDetails(
      render_view()->routing_id(), resources));
}

void MalwareDOMDetails::ExtractResources(
    ViewHostMsg_MalwareDOMDetails_Params* resources) {
  WebKit::WebView* web_view = render_view_->webview();
  if (!web_view) {
    NOTREACHED();
    return;
  }
  WebKit::WebFrame* cur_frame = web_view->mainFrame();
  for (; cur_frame;
       cur_frame = cur_frame->traverseNext(false /* don't wrap around */)) {
    DCHECK(cur_frame);
    if (!cur_frame)
      break;
    ViewHostMsg_MalwareDOMDetails_Node frame_node;
    frame_node.url = GURL(cur_frame->url());
    WebKit::WebDocument doc = cur_frame->document();
    if (doc.isNull()) {
      // Nothing in this frame, move on to the next one.
      resources->nodes.push_back(frame_node);
      continue;
    }

    WebKit::WebNodeCollection elements = doc.all();
    WebKit::WebNode cur_node = elements.firstItem();
    for (; !cur_node.isNull(); cur_node = elements.nextItem()) {
      if (!cur_node.isElementNode()) {
        continue;
      }
      WebKit::WebElement element = cur_node.to<WebKit::WebElement>();
      if (element.hasTagName("iframe") || element.hasTagName("frame") ||
          element.hasTagName("embed") || element.hasTagName("script")) {
        HandleElement(element, &frame_node, resources);
        if (resources->nodes.size() >= kMaxNodes) {
          // We have reached kMaxNodes, exit early.
          resources->nodes.push_back(frame_node);
          return;
        }
      }
    }

    resources->nodes.push_back(frame_node);
  }
}

void MalwareDOMDetails::HandleElement(
    const WebKit::WebElement& element,
    ViewHostMsg_MalwareDOMDetails_Node* parent_node,
    ViewHostMsg_MalwareDOMDetails_Params* resources) {
  if (!element.hasAttribute("src")) {
    return;
  }

  // Retrieve the link and resolve the link in case it's relative.
  WebKit::WebURL full_url = element.document().completeURL(
      element.getAttribute("src"));

  const GURL& child_url = GURL(full_url);

  // Add to the parent node.
  parent_node->children.push_back(child_url);

  // Create the child node.
  ViewHostMsg_MalwareDOMDetails_Node child_node;
  child_node.url = child_url;
  child_node.tag_name = element.tagName().utf8();
  child_node.parent = parent_node->url;
  resources->nodes.push_back(child_node);
}

}  // namespace safe_browsing
<commit_msg>Coverity: Remove DCHECK failure handler in MalwareDOMDetails::ExtractResources.<commit_after>// Copyright (c) 2011 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/safe_browsing/malware_dom_details.h"

#include "base/compiler_specific.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/render_messages.h"
#include "chrome/common/render_messages_params.h"
#include "chrome/renderer/render_view.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebDocument.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebElement.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebFrame.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebNodeCollection.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebString.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebView.h"

namespace safe_browsing {

// An upper limit on the number of nodes we collect.
uint32 MalwareDOMDetails::kMaxNodes = 500;

MalwareDOMDetails::MalwareDOMDetails(RenderView* render_view)
    : RenderViewObserver(render_view),
      render_view_(render_view) {
}

MalwareDOMDetails::~MalwareDOMDetails() {
}

bool MalwareDOMDetails::OnMessageReceived(const IPC::Message& message) {
  bool handled = true;
  IPC_BEGIN_MESSAGE_MAP(MalwareDOMDetails, message)
    IPC_MESSAGE_HANDLER(ViewMsg_GetMalwareDOMDetails, OnGetMalwareDOMDetails)
    IPC_MESSAGE_UNHANDLED(handled = false)
  IPC_END_MESSAGE_MAP()
  return handled;
}

void MalwareDOMDetails::OnGetMalwareDOMDetails() {
  ViewHostMsg_MalwareDOMDetails_Params resources;
  ExtractResources(&resources);
  // Notify the browser.
  render_view()->Send(new ViewHostMsg_MalwareDOMDetails(
      render_view()->routing_id(), resources));
}

void MalwareDOMDetails::ExtractResources(
    ViewHostMsg_MalwareDOMDetails_Params* resources) {
  WebKit::WebView* web_view = render_view_->webview();
  if (!web_view) {
    NOTREACHED();
    return;
  }
  WebKit::WebFrame* cur_frame = web_view->mainFrame();
  for (; cur_frame;
       cur_frame = cur_frame->traverseNext(false /* don't wrap around */)) {
    DCHECK(cur_frame);
    ViewHostMsg_MalwareDOMDetails_Node frame_node;
    frame_node.url = GURL(cur_frame->url());
    WebKit::WebDocument doc = cur_frame->document();
    if (doc.isNull()) {
      // Nothing in this frame, move on to the next one.
      resources->nodes.push_back(frame_node);
      continue;
    }

    WebKit::WebNodeCollection elements = doc.all();
    WebKit::WebNode cur_node = elements.firstItem();
    for (; !cur_node.isNull(); cur_node = elements.nextItem()) {
      if (!cur_node.isElementNode()) {
        continue;
      }
      WebKit::WebElement element = cur_node.to<WebKit::WebElement>();
      if (element.hasTagName("iframe") || element.hasTagName("frame") ||
          element.hasTagName("embed") || element.hasTagName("script")) {
        HandleElement(element, &frame_node, resources);
        if (resources->nodes.size() >= kMaxNodes) {
          // We have reached kMaxNodes, exit early.
          resources->nodes.push_back(frame_node);
          return;
        }
      }
    }

    resources->nodes.push_back(frame_node);
  }
}

void MalwareDOMDetails::HandleElement(
    const WebKit::WebElement& element,
    ViewHostMsg_MalwareDOMDetails_Node* parent_node,
    ViewHostMsg_MalwareDOMDetails_Params* resources) {
  if (!element.hasAttribute("src")) {
    return;
  }

  // Retrieve the link and resolve the link in case it's relative.
  WebKit::WebURL full_url = element.document().completeURL(
      element.getAttribute("src"));

  const GURL& child_url = GURL(full_url);

  // Add to the parent node.
  parent_node->children.push_back(child_url);

  // Create the child node.
  ViewHostMsg_MalwareDOMDetails_Node child_node;
  child_node.url = child_url;
  child_node.tag_name = element.tagName().utf8();
  child_node.parent = parent_node->url;
  resources->nodes.push_back(child_node);
}

}  // namespace safe_browsing
<|endoftext|>


<commit_before>// Copyright (c) 2011 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/safe_browsing/phishing_classifier.h"

#include <string>

#include "base/callback.h"
#include "base/compiler_specific.h"
#include "base/logging.h"
#include "base/string_util.h"
#include "chrome/common/safe_browsing/csd.pb.h"
#include "chrome/common/url_constants.h"
#include "chrome/renderer/safe_browsing/feature_extractor_clock.h"
#include "chrome/renderer/safe_browsing/features.h"
#include "chrome/renderer/safe_browsing/phishing_dom_feature_extractor.h"
#include "chrome/renderer/safe_browsing/phishing_term_feature_extractor.h"
#include "chrome/renderer/safe_browsing/phishing_url_feature_extractor.h"
#include "chrome/renderer/safe_browsing/scorer.h"
#include "content/renderer/render_view.h"
#include "crypto/sha2.h"
#include "googleurl/src/gurl.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebDataSource.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebFrame.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebURL.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebURLRequest.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebView.h"

namespace safe_browsing {

const float PhishingClassifier::kInvalidScore = -1.0;
const float PhishingClassifier::kPhishyThreshold = 0.5;

PhishingClassifier::PhishingClassifier(RenderView* render_view,
                                       FeatureExtractorClock* clock)
    : render_view_(render_view),
      scorer_(NULL),
      clock_(clock),
      ALLOW_THIS_IN_INITIALIZER_LIST(method_factory_(this)) {
  Clear();
}

PhishingClassifier::~PhishingClassifier() {
  // The RenderView should have called CancelPendingClassification() before
  // we are destroyed.
  CheckNoPendingClassification();
}

void PhishingClassifier::set_phishing_scorer(const Scorer* scorer) {
  DCHECK(!scorer_);
  scorer_ = scorer;
  url_extractor_.reset(new PhishingUrlFeatureExtractor);
  dom_extractor_.reset(
      new PhishingDOMFeatureExtractor(render_view_, clock_.get()));
  term_extractor_.reset(new PhishingTermFeatureExtractor(
      &scorer_->page_terms(),
      &scorer_->page_words(),
      scorer_->max_words_per_term(),
      clock_.get()));
}

bool PhishingClassifier::is_ready() const {
  return scorer_ != NULL;
}

void PhishingClassifier::BeginClassification(const string16* page_text,
                                             DoneCallback* done_callback) {
  DCHECK(is_ready());

  // The RenderView should have called CancelPendingClassification() before
  // starting a new classification, so DCHECK this.
  CheckNoPendingClassification();
  // However, in an opt build, we will go ahead and clean up the pending
  // classification so that we can start in a known state.
  CancelPendingClassification();

  page_text_ = page_text;
  done_callback_.reset(done_callback);

  // For consistency, we always want to invoke the DoneCallback
  // asynchronously, rather than directly from this method.  To ensure that
  // this is the case, post a task to begin feature extraction on the next
  // iteration of the message loop.
  MessageLoop::current()->PostTask(
      FROM_HERE,
      method_factory_.NewRunnableMethod(
          &PhishingClassifier::BeginFeatureExtraction));
}

void PhishingClassifier::BeginFeatureExtraction() {
  WebKit::WebView* web_view = render_view_->webview();
  if (!web_view) {
    RunFailureCallback();
    return;
  }

  WebKit::WebFrame* frame = web_view->mainFrame();
  if (!frame) {
    RunFailureCallback();
    return;
  }

  // Check whether the URL is one that we should classify.
  // Currently, we only classify http: URLs that are GET requests.
  GURL url(frame->url());
  if (!url.SchemeIs(chrome::kHttpScheme)) {
    RunFailureCallback();
    return;
  }

  WebKit::WebDataSource* ds = frame->dataSource();
  if (!ds || !EqualsASCII(ds->request().httpMethod(), "GET")) {
    RunFailureCallback();
    return;
  }

  features_.reset(new FeatureMap);
  if (!url_extractor_->ExtractFeatures(url, features_.get())) {
    RunFailureCallback();
    return;
  }

  // DOM feature extraction can take awhile, so it runs asynchronously
  // in several chunks of work and invokes the callback when finished.
  dom_extractor_->ExtractFeatures(
      features_.get(),
      NewCallback(this, &PhishingClassifier::DOMExtractionFinished));
}

void PhishingClassifier::CancelPendingClassification() {
  // Note that cancelling the feature extractors is simply a no-op if they
  // were not running.
  DCHECK(is_ready());
  dom_extractor_->CancelPendingExtraction();
  term_extractor_->CancelPendingExtraction();
  method_factory_.RevokeAll();
  Clear();
}

void PhishingClassifier::DOMExtractionFinished(bool success) {
  if (success) {
    // Term feature extraction can take awhile, so it runs asynchronously
    // in several chunks of work and invokes the callback when finished.
    term_extractor_->ExtractFeatures(
        page_text_,
        features_.get(),
        NewCallback(this, &PhishingClassifier::TermExtractionFinished));
  } else {
    RunFailureCallback();
  }
}

void PhishingClassifier::TermExtractionFinished(bool success) {
  if (success) {
    // Hash all of the features so that they match the model, then compute
    // the score.
    FeatureMap hashed_features;
    ClientPhishingRequest verdict;
    verdict.set_url(render_view_->webview()->mainFrame()->url().spec());
    for (base::hash_map<std::string, double>::const_iterator it =
             features_->features().begin();
         it != features_->features().end(); ++it) {
      VLOG(2) << "Feature: " << it->first << " = " << it->second;
      bool result = hashed_features.AddRealFeature(
          crypto::SHA256HashString(it->first), it->second);
      DCHECK(result);
      ClientPhishingRequest::Feature* feature = verdict.add_feature_map();
      feature->set_name(it->first);
      feature->set_value(it->second);
    }
    float score = static_cast<float>(scorer_->ComputeScore(hashed_features));
    verdict.set_client_score(score);
    verdict.set_is_phishing(score >= kPhishyThreshold);
    RunCallback(verdict);
  } else {
    RunFailureCallback();
  }
}

void PhishingClassifier::CheckNoPendingClassification() {
  DCHECK(!done_callback_.get());
  DCHECK(!page_text_);
  if (done_callback_.get() || page_text_) {
    LOG(ERROR) << "Classification in progress, missing call to "
               << "CancelPendingClassification";
  }
}

void PhishingClassifier::RunCallback(const ClientPhishingRequest& verdict) {
  done_callback_->Run(verdict);
  Clear();
}

void PhishingClassifier::RunFailureCallback() {
  ClientPhishingRequest verdict;
  // In this case we're not guaranteed to have a valid URL.  Just set it
  // to the empty string to make sure we have a valid protocol buffer.
  verdict.set_url("");
  verdict.set_client_score(kInvalidScore);
  verdict.set_is_phishing(false);
  RunCallback(verdict);
}

void PhishingClassifier::Clear() {
  page_text_ = NULL;
  done_callback_.reset(NULL);
  features_.reset(NULL);
}

}  // namespace safe_browsing
<commit_msg>Fix missing include<commit_after>// Copyright (c) 2011 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/safe_browsing/phishing_classifier.h"

#include <string>

#include "base/callback.h"
#include "base/compiler_specific.h"
#include "base/logging.h"
#include "base/message_loop.h"
#include "base/string_util.h"
#include "chrome/common/safe_browsing/csd.pb.h"
#include "chrome/common/url_constants.h"
#include "chrome/renderer/safe_browsing/feature_extractor_clock.h"
#include "chrome/renderer/safe_browsing/features.h"
#include "chrome/renderer/safe_browsing/phishing_dom_feature_extractor.h"
#include "chrome/renderer/safe_browsing/phishing_term_feature_extractor.h"
#include "chrome/renderer/safe_browsing/phishing_url_feature_extractor.h"
#include "chrome/renderer/safe_browsing/scorer.h"
#include "content/renderer/render_view.h"
#include "crypto/sha2.h"
#include "googleurl/src/gurl.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebDataSource.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebFrame.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebURL.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebURLRequest.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebView.h"

namespace safe_browsing {

const float PhishingClassifier::kInvalidScore = -1.0;
const float PhishingClassifier::kPhishyThreshold = 0.5;

PhishingClassifier::PhishingClassifier(RenderView* render_view,
                                       FeatureExtractorClock* clock)
    : render_view_(render_view),
      scorer_(NULL),
      clock_(clock),
      ALLOW_THIS_IN_INITIALIZER_LIST(method_factory_(this)) {
  Clear();
}

PhishingClassifier::~PhishingClassifier() {
  // The RenderView should have called CancelPendingClassification() before
  // we are destroyed.
  CheckNoPendingClassification();
}

void PhishingClassifier::set_phishing_scorer(const Scorer* scorer) {
  DCHECK(!scorer_);
  scorer_ = scorer;
  url_extractor_.reset(new PhishingUrlFeatureExtractor);
  dom_extractor_.reset(
      new PhishingDOMFeatureExtractor(render_view_, clock_.get()));
  term_extractor_.reset(new PhishingTermFeatureExtractor(
      &scorer_->page_terms(),
      &scorer_->page_words(),
      scorer_->max_words_per_term(),
      clock_.get()));
}

bool PhishingClassifier::is_ready() const {
  return scorer_ != NULL;
}

void PhishingClassifier::BeginClassification(const string16* page_text,
                                             DoneCallback* done_callback) {
  DCHECK(is_ready());

  // The RenderView should have called CancelPendingClassification() before
  // starting a new classification, so DCHECK this.
  CheckNoPendingClassification();
  // However, in an opt build, we will go ahead and clean up the pending
  // classification so that we can start in a known state.
  CancelPendingClassification();

  page_text_ = page_text;
  done_callback_.reset(done_callback);

  // For consistency, we always want to invoke the DoneCallback
  // asynchronously, rather than directly from this method.  To ensure that
  // this is the case, post a task to begin feature extraction on the next
  // iteration of the message loop.
  MessageLoop::current()->PostTask(
      FROM_HERE,
      method_factory_.NewRunnableMethod(
          &PhishingClassifier::BeginFeatureExtraction));
}

void PhishingClassifier::BeginFeatureExtraction() {
  WebKit::WebView* web_view = render_view_->webview();
  if (!web_view) {
    RunFailureCallback();
    return;
  }

  WebKit::WebFrame* frame = web_view->mainFrame();
  if (!frame) {
    RunFailureCallback();
    return;
  }

  // Check whether the URL is one that we should classify.
  // Currently, we only classify http: URLs that are GET requests.
  GURL url(frame->url());
  if (!url.SchemeIs(chrome::kHttpScheme)) {
    RunFailureCallback();
    return;
  }

  WebKit::WebDataSource* ds = frame->dataSource();
  if (!ds || !EqualsASCII(ds->request().httpMethod(), "GET")) {
    RunFailureCallback();
    return;
  }

  features_.reset(new FeatureMap);
  if (!url_extractor_->ExtractFeatures(url, features_.get())) {
    RunFailureCallback();
    return;
  }

  // DOM feature extraction can take awhile, so it runs asynchronously
  // in several chunks of work and invokes the callback when finished.
  dom_extractor_->ExtractFeatures(
      features_.get(),
      NewCallback(this, &PhishingClassifier::DOMExtractionFinished));
}

void PhishingClassifier::CancelPendingClassification() {
  // Note that cancelling the feature extractors is simply a no-op if they
  // were not running.
  DCHECK(is_ready());
  dom_extractor_->CancelPendingExtraction();
  term_extractor_->CancelPendingExtraction();
  method_factory_.RevokeAll();
  Clear();
}

void PhishingClassifier::DOMExtractionFinished(bool success) {
  if (success) {
    // Term feature extraction can take awhile, so it runs asynchronously
    // in several chunks of work and invokes the callback when finished.
    term_extractor_->ExtractFeatures(
        page_text_,
        features_.get(),
        NewCallback(this, &PhishingClassifier::TermExtractionFinished));
  } else {
    RunFailureCallback();
  }
}

void PhishingClassifier::TermExtractionFinished(bool success) {
  if (success) {
    // Hash all of the features so that they match the model, then compute
    // the score.
    FeatureMap hashed_features;
    ClientPhishingRequest verdict;
    verdict.set_url(render_view_->webview()->mainFrame()->url().spec());
    for (base::hash_map<std::string, double>::const_iterator it =
             features_->features().begin();
         it != features_->features().end(); ++it) {
      VLOG(2) << "Feature: " << it->first << " = " << it->second;
      bool result = hashed_features.AddRealFeature(
          crypto::SHA256HashString(it->first), it->second);
      DCHECK(result);
      ClientPhishingRequest::Feature* feature = verdict.add_feature_map();
      feature->set_name(it->first);
      feature->set_value(it->second);
    }
    float score = static_cast<float>(scorer_->ComputeScore(hashed_features));
    verdict.set_client_score(score);
    verdict.set_is_phishing(score >= kPhishyThreshold);
    RunCallback(verdict);
  } else {
    RunFailureCallback();
  }
}

void PhishingClassifier::CheckNoPendingClassification() {
  DCHECK(!done_callback_.get());
  DCHECK(!page_text_);
  if (done_callback_.get() || page_text_) {
    LOG(ERROR) << "Classification in progress, missing call to "
               << "CancelPendingClassification";
  }
}

void PhishingClassifier::RunCallback(const ClientPhishingRequest& verdict) {
  done_callback_->Run(verdict);
  Clear();
}

void PhishingClassifier::RunFailureCallback() {
  ClientPhishingRequest verdict;
  // In this case we're not guaranteed to have a valid URL.  Just set it
  // to the empty string to make sure we have a valid protocol buffer.
  verdict.set_url("");
  verdict.set_client_score(kInvalidScore);
  verdict.set_is_phishing(false);
  RunCallback(verdict);
}

void PhishingClassifier::Clear() {
  page_text_ = NULL;
  done_callback_.reset(NULL);
  features_.reset(NULL);
}

}  // namespace safe_browsing
<|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 <string>

#include "base/command_line.h"
#include "base/logging.h"
#include "base/process_util.h"

#include "chrome/test/test_launcher/test_runner.h"
#include "chrome/test/unit/chrome_test_suite.h"

// This version of the test launcher forks a new process for each test it runs.

namespace {

const char kGTestListTestsFlag[] = "gtest_list_tests";
const char kGTestOutputFlag[] = "gtest_output";
const char kGTestHelpFlag[]   = "gtest_help";
const char kSingleProcessTestsFlag[]   = "single_process";
const char kSingleProcessTestsAndChromeFlag[]   = "single-process";
const char kTestTerminateTimeoutFlag[] = "test-terminate-timeout";
// The following is kept for historical reasons (so people that are used to
// using it don't get surprised).
const char kChildProcessFlag[]   = "child";
const char kHelpFlag[]   = "help";

const int64 kDefaultTestTimeoutMs = 30000;

class OutOfProcTestRunner : public tests::TestRunner {
 public:
  OutOfProcTestRunner() {
  }

  virtual ~OutOfProcTestRunner() {
  }

  bool Init() {
    return true;
  }

  // Returns true if the test succeeded, false if it failed.
  bool RunTest(const std::string& test_name) {
    const CommandLine* cmd_line = CommandLine::ForCurrentProcess();
    // Construct the new command line.  Strip out gtest_output flag if
    // it has been given because otherwise each test outputs the same file
    // over and over overriding the previous one every time.
    // We will generate the final output file later in RunTests().
    CommandLine new_cmd_line(cmd_line->GetProgram());
    CommandLine::SwitchMap switches = cmd_line->GetSwitches();
    switches.erase(kGTestOutputFlag);
    for (CommandLine::SwitchMap::const_iterator iter = switches.begin();
         iter != switches.end(); ++iter) {
      new_cmd_line.AppendSwitchWithValue((*iter).first, (*iter).second);
    }

    // Always enable disabled tests.  This method is not called with disabled
    // tests unless this flag was specified to the browser test executable.
    new_cmd_line.AppendSwitch("gtest_also_run_disabled_tests");
    new_cmd_line.AppendSwitchWithValue("gtest_filter", test_name);
    new_cmd_line.AppendSwitch(kChildProcessFlag);

    base::ProcessHandle process_handle;
    if (!base::LaunchApp(new_cmd_line, false, false, &process_handle))
      return false;

    int test_terminate_timeout_ms = kDefaultTestTimeoutMs;
    if (cmd_line->HasSwitch(kTestTerminateTimeoutFlag)) {
      std::wstring timeout_str(
          cmd_line->GetSwitchValue(kTestTerminateTimeoutFlag));
      int timeout = StringToInt(WideToUTF16Hack(timeout_str));
      test_terminate_timeout_ms = std::max(test_terminate_timeout_ms, timeout);
    }

    int exit_code = 0;
    if (!base::WaitForExitCodeWithTimeout(process_handle, &exit_code,
                                          test_terminate_timeout_ms)) {
      LOG(ERROR) << "Test timeout (" << test_terminate_timeout_ms
                 << " ms) exceeded!";

      exit_code = -1;  // Set a non-zero exit code to signal a failure.

      // Ensure that the process terminates.
      base::KillProcess(process_handle, -1, true);
    }

    return exit_code == 0;
  }

 private:
  DISALLOW_COPY_AND_ASSIGN(OutOfProcTestRunner);
};

class OutOfProcTestRunnerFactory : public tests::TestRunnerFactory {
 public:
  OutOfProcTestRunnerFactory() { }

  virtual tests::TestRunner* CreateTestRunner() const {
    return new OutOfProcTestRunner();
  }

 private:
  DISALLOW_COPY_AND_ASSIGN(OutOfProcTestRunnerFactory);
};

void PrintUsage() {
  fprintf(stdout,
      "Runs tests using the gtest framework, each test being run in its own\n"
      "process.  Any gtest flags can be specified.\n"
      "  --single_process\n"
      "    Runs the tests and the launcher in the same process. Useful for \n"
      "    debugging a specific test in a debugger.\n"
      "  --single-process\n"
      "    Same as above, and also runs Chrome in single-process mode.\n"
      "  --test-terminate-timeout\n"
      "    Specifies a timeout (in milliseconds) after which a running test\n"
      "    will be forcefully terminated.\n"
      "  --help\n"
      "    Shows this message.\n"
      "  --gtest_help\n"
      "    Shows the gtest help message.\n");
}

}  // namespace

int main(int argc, char** argv) {
  CommandLine::Init(argc, argv);
  const CommandLine* command_line = CommandLine::ForCurrentProcess();

  if (command_line->HasSwitch(kHelpFlag)) {
    PrintUsage();
    return 0;
  }

  // TODO(pkasting): This "single_process vs. single-process" design is terrible
  // UI.  Instead, there should be some sort of signal flag on the command line,
  // with all subsequent arguments passed through to the underlying browser.
  if (command_line->HasSwitch(kChildProcessFlag) ||
      command_line->HasSwitch(kSingleProcessTestsFlag) ||
      command_line->HasSwitch(kSingleProcessTestsAndChromeFlag) ||
      command_line->HasSwitch(kGTestListTestsFlag) ||
      command_line->HasSwitch(kGTestHelpFlag)) {
    return ChromeTestSuite(argc, argv).Run();
  }

  fprintf(stdout,
      "Starting tests...\n"
      "IMPORTANT DEBUGGING NOTE: each test is run inside its own process.\n"
      "For debugging a test inside a debugger, use the\n"
      "--gtest_filter=<your_test_name> flag along with either\n"
      "--single_process (to run all tests in one launcher/browser process) or\n"
      "--single-process (to do the above, and also run Chrome in single-\n"
      "process mode).\n");
  OutOfProcTestRunnerFactory test_runner_factory;
  return tests::RunTests(test_runner_factory) ? 0 : 1;
}
<commit_msg>Add test name to OOP timeout log message so the log parser knows which one timed out.<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 <string>

#include "base/command_line.h"
#include "base/logging.h"
#include "base/process_util.h"

#include "chrome/test/test_launcher/test_runner.h"
#include "chrome/test/unit/chrome_test_suite.h"

// This version of the test launcher forks a new process for each test it runs.

namespace {

const char kGTestListTestsFlag[] = "gtest_list_tests";
const char kGTestOutputFlag[] = "gtest_output";
const char kGTestHelpFlag[]   = "gtest_help";
const char kSingleProcessTestsFlag[]   = "single_process";
const char kSingleProcessTestsAndChromeFlag[]   = "single-process";
const char kTestTerminateTimeoutFlag[] = "test-terminate-timeout";
// The following is kept for historical reasons (so people that are used to
// using it don't get surprised).
const char kChildProcessFlag[]   = "child";
const char kHelpFlag[]   = "help";

const int64 kDefaultTestTimeoutMs = 30000;

class OutOfProcTestRunner : public tests::TestRunner {
 public:
  OutOfProcTestRunner() {
  }

  virtual ~OutOfProcTestRunner() {
  }

  bool Init() {
    return true;
  }

  // Returns true if the test succeeded, false if it failed.
  bool RunTest(const std::string& test_name) {
    const CommandLine* cmd_line = CommandLine::ForCurrentProcess();
    // Construct the new command line.  Strip out gtest_output flag if
    // it has been given because otherwise each test outputs the same file
    // over and over overriding the previous one every time.
    // We will generate the final output file later in RunTests().
    CommandLine new_cmd_line(cmd_line->GetProgram());
    CommandLine::SwitchMap switches = cmd_line->GetSwitches();
    switches.erase(kGTestOutputFlag);
    for (CommandLine::SwitchMap::const_iterator iter = switches.begin();
         iter != switches.end(); ++iter) {
      new_cmd_line.AppendSwitchWithValue((*iter).first, (*iter).second);
    }

    // Always enable disabled tests.  This method is not called with disabled
    // tests unless this flag was specified to the browser test executable.
    new_cmd_line.AppendSwitch("gtest_also_run_disabled_tests");
    new_cmd_line.AppendSwitchWithValue("gtest_filter", test_name);
    new_cmd_line.AppendSwitch(kChildProcessFlag);

    base::ProcessHandle process_handle;
    if (!base::LaunchApp(new_cmd_line, false, false, &process_handle))
      return false;

    int test_terminate_timeout_ms = kDefaultTestTimeoutMs;
    if (cmd_line->HasSwitch(kTestTerminateTimeoutFlag)) {
      std::wstring timeout_str(
          cmd_line->GetSwitchValue(kTestTerminateTimeoutFlag));
      int timeout = StringToInt(WideToUTF16Hack(timeout_str));
      test_terminate_timeout_ms = std::max(test_terminate_timeout_ms, timeout);
    }

    int exit_code = 0;
    if (!base::WaitForExitCodeWithTimeout(process_handle, &exit_code,
                                          test_terminate_timeout_ms)) {
      LOG(ERROR) << "Test timeout (" << test_terminate_timeout_ms
                 << " ms) exceeded for " << test_name;

      exit_code = -1;  // Set a non-zero exit code to signal a failure.

      // Ensure that the process terminates.
      base::KillProcess(process_handle, -1, true);
    }

    return exit_code == 0;
  }

 private:
  DISALLOW_COPY_AND_ASSIGN(OutOfProcTestRunner);
};

class OutOfProcTestRunnerFactory : public tests::TestRunnerFactory {
 public:
  OutOfProcTestRunnerFactory() { }

  virtual tests::TestRunner* CreateTestRunner() const {
    return new OutOfProcTestRunner();
  }

 private:
  DISALLOW_COPY_AND_ASSIGN(OutOfProcTestRunnerFactory);
};

void PrintUsage() {
  fprintf(stdout,
      "Runs tests using the gtest framework, each test being run in its own\n"
      "process.  Any gtest flags can be specified.\n"
      "  --single_process\n"
      "    Runs the tests and the launcher in the same process. Useful for \n"
      "    debugging a specific test in a debugger.\n"
      "  --single-process\n"
      "    Same as above, and also runs Chrome in single-process mode.\n"
      "  --test-terminate-timeout\n"
      "    Specifies a timeout (in milliseconds) after which a running test\n"
      "    will be forcefully terminated.\n"
      "  --help\n"
      "    Shows this message.\n"
      "  --gtest_help\n"
      "    Shows the gtest help message.\n");
}

}  // namespace

int main(int argc, char** argv) {
  CommandLine::Init(argc, argv);
  const CommandLine* command_line = CommandLine::ForCurrentProcess();

  if (command_line->HasSwitch(kHelpFlag)) {
    PrintUsage();
    return 0;
  }

  // TODO(pkasting): This "single_process vs. single-process" design is terrible
  // UI.  Instead, there should be some sort of signal flag on the command line,
  // with all subsequent arguments passed through to the underlying browser.
  if (command_line->HasSwitch(kChildProcessFlag) ||
      command_line->HasSwitch(kSingleProcessTestsFlag) ||
      command_line->HasSwitch(kSingleProcessTestsAndChromeFlag) ||
      command_line->HasSwitch(kGTestListTestsFlag) ||
      command_line->HasSwitch(kGTestHelpFlag)) {
    return ChromeTestSuite(argc, argv).Run();
  }

  fprintf(stdout,
      "Starting tests...\n"
      "IMPORTANT DEBUGGING NOTE: each test is run inside its own process.\n"
      "For debugging a test inside a debugger, use the\n"
      "--gtest_filter=<your_test_name> flag along with either\n"
      "--single_process (to run all tests in one launcher/browser process) or\n"
      "--single-process (to do the above, and also run Chrome in single-\n"
      "process mode).\n");
  OutOfProcTestRunnerFactory test_runner_factory;
  return tests::RunTests(test_runner_factory) ? 0 : 1;
}
<|endoftext|>


<commit_before>#include <iterator>
#include <algorithm>

namespace Linqpp
{
	template <class Iterator>
	class Enumeration
	{
	private:
		Iterator _first;
		Iterator _last;

	public:
		using value_type = typename std::iterator_traits<Iterator>::value_type;

	public:
		Enumeration(Iterator first, Iterator last)
			: _first(first), _last(last)
		{ }

	public:
		auto begin() const { return _first; }
		auto end() const { return _last; }

	public:
		bool Any() const { return _first != _last; }

		template <class Predicate>
		bool Any(Predicate predicate) const { return std::any_of(_first, _last, predicate); }

		template <class Predicate>
		bool All(Predicate predicate) const { return std::all_of(_first, _last, predicate); }

		size_t Count() const { return std::distance(_first, _last); }

		auto Skip(size_t n) const { return Create(std::next(_first, n), _last); }

		auto Take(size_t n) const { return Create(_first, std::next(_first, n)); }

		auto ToVector() const { return std::vector<value_type>(_first, _last); }
	};

	template <class Iterator>
	auto From(Iterator first, Iterator last)
	{
		return Enumerable<Iterator>(first, last);
	}

	template <class Container>
	auto From(Container&& container)
	{
		return From(std::begin(std::forward<Container>(container)), std::end(std::forward<Container>(container)));
	}
}
<commit_msg>renamed Create to From<commit_after>#include <iterator>
#include <algorithm>

namespace Linqpp
{
	template <class Iterator>
	class Enumeration;

	template <class Iterator>
	auto From(Iterator first, Iterator last)
	{
		return Enumerable<Iterator>(first, last);
	}

	template <class Container>
	auto From(Container&& container)
	{
		return From(std::begin(std::forward<Container>(container)), std::end(std::forward<Container>(container)));
	}

	template <class Iterator>
	class Enumeration
	{
	private:
		Iterator _first;
		Iterator _last;

	public:
		using value_type = typename std::iterator_traits<Iterator>::value_type;

	public:
		Enumeration(Iterator first, Iterator last)
			: _first(first), _last(last)
		{ }

	public:
		auto begin() const { return _first; }
		auto end() const { return _last; }

	public:
		bool Any() const { return _first != _last; }

		template <class Predicate>
		bool Any(Predicate predicate) const { return std::any_of(_first, _last, predicate); }

		template <class Predicate>
		bool All(Predicate predicate) const { return std::all_of(_first, _last, predicate); }

		size_t Count() const { return std::distance(_first, _last); }

		auto Skip(size_t n) const { return From(std::next(_first, n), _last); }

		auto Take(size_t n) const { return From(_first, std::next(_first, n)); }

		auto ToVector() const { return std::vector<value_type>(_first, _last); }
	};
}
<|endoftext|>


<commit_before>// This file (SampleCode.cpp) was converted from SampleCode.Bas
// with uCalc Transform 2.5 on 2/24/2014 3:28:33 PM using the Open Source
// PowerBASIC to C++ converter found at https://github.com/uCalc/powerbasic-to-cpp

#include <math.h>
#include <stdlib.h>
#include <iostream>
#include <fstream>
#include <algorithm>
#include <string>
#include "pbstrings.h"
using namespace std;

//  File name: SampleCode.Bas
//  To convert this file to C++ make sure you have uCalc Transform on your PC
//  and *.uc from github.com/uCalc/powerbasic-to-cpp/tree/master/convert
//  Do the following at the Command Prompt:
//
//  C:\> PBtoCPP.Bat SampleCode.Bas

const int MyEquate = 0x100;
const int Other = 0x200;

int ProgStatus;

#if defined Other
//  Something
#elif !defined abcd
//  Something else
#else
//  Etc
#endif

#define MyMacroNum 12345
#define MyMacro(a, b, c) (a + b * (c))

struct point {
   int x;
   int y;
};

struct MyBits {
   unsigned int Year : 7;
   unsigned int Month : 5;
   unsigned int DayOfMonth : 4;
   unsigned int DayOfWeek : 3;
   unsigned char Red : 1;
   unsigned char Blue : 1;
   unsigned char Green : 1;
   double Other;
};

int MyFunc(int x)
{
   return x * 2;
}

int MyFunction(int a, float& b)
{
   int x;
   int y;
   int *Test = new int [a+25+1];
   int yVar;
   int MyValue;
   //  Dim q As Long
   //  The commented line above is not translated

   MyFunc(a);
   x = MyFunc(b)+1;

   if (b > 5) {
      for (x=1; x<=10; x += 1) {
         for (yVar=10; yVar>=1; yVar += -1) {
            if (x > y) {
               return a+y;
            }
            while (Test[a+5] == yVar) {
               while (!(a+1 == 1234)) {
                  if (y < MyEquate) {
                     return Test[x-y]*10;
                  }
                  a = a + 1;
                  do {
                     b = a * 5 + b;
                  } while (!(b == 300));
               }
            }
         }
      }
   }

   delete[] Test;
}

void MySub(int x)
{
   int y;
   float *Test;
   float *Number = new float [10+1];
   int *Other = new int [x+1];
   int z;

   ProgStatus = 10;
   y = x + 1;
   z = y+x;
   Other[x] = x+1;

   while (x < 10) {
      y = MyFunction(x, *Test);
      Test = &x;
      Number[z] = *Test + Other[5+x];
      x = x+1;
      if (Test < 0) {
         continue;
      }
      if (Test == y) {
         return;
      }
      if (Test == z) {
         break;
      }
   }

   delete[] Other;
   delete[] Number;
}
//   ' This line is broken up using a _ (underscore)
//   This is a commment (even without ')
//   Everything after _ is a comment

void TestCertainOperators(int x, int y, int z, double& OtherVar, float *FinalArg)
{
   //  Note: comments after _ are regrouped into a different place

   int *MyArray = new int [10+1];
   Point MyPoint;
   Point *pp;
   int n;

   for (x=1; x<=10; x += 1) {
      n = y == z //  This works differently in PB than in C++
      MyArray[x] = x*2;
      if (x == 5) {
         y = x+5;
      } else {
         y = 23*2;
      }
      y = x == z;
      MyArray[5] = MyArray[n] == MyArray[n+1];
      if (x == y == z) {
         y = n == 2;
      } else {
         y = n == 3;
      }
      if (x == y && x != 10 || y == x && x < 25) {
         y = x || y == z;
      }
      if ((x == y & x != 10 | y == x & x < 25)) {
         y = x || y == z;
      }
      if ((x == y & x != 10) || y == x && x < 25) {
         y = x || y == z;
      }
      if (~(x == y | x == z)) {
         x = y + 10;
      }
      if (~(x == y | x == z)) {
         x = y + 10;
      }

      if (x != y) {
         MyPoint.x = y;
      } else {
         MyPoint.x = x;
      }

      pp = &p;
      MyPoint.x = MyPoint.y+1;
      n = MyPoint.x == MyPoint.y;
      *pp.x = *pp.y == *pp.x+1;
   }

   delete[] MyArray;
}

//  The section below is a test for variables declared implicitely with data type
//  based on Def[Type] declarations or on type specifiers.

float MyValue;
string Label;
Currency Price;
double ExtVal;
__int64 qNum;

int TestFunc(int& a, unsigned char& b, int& c, short& i, String& s, float& n)
{
   Print MyValue, Label, PriceB;

   Label = "Missing quote at the end of this line is added by Refactor.uc";
}

string Report(string& LastName, int x, double& NewPrice, float& n, short i, float& nValue, __int64& qValue)
{
   string FirstName;
   unsigned char Age;
   double Total;
   static int Index;

   Print LastName, x, NewPrice, n, i, nValue, qValue;
   Report = FirstName + LastName;
}

string Hello(string& txt)
{
   Print txt;
   return txt + " friend!";
}

unsigned char  Bye() {
   Print "Bye";
}

//  This section is a test for Subs or Functions that are called as a statement
//  without parentheses.  The converter adds them.

// #Include "Win32API.inc"
extern __declspec(dllimport) unsigned int ShellExecute(unsigned int hwnd, lpOperation As LPCSTR, lpFile As LPCSTR, lpParameters As LPCSTR, lpDirectory As LPCSTR, int nShowCmd);
extern __declspec(dllimport) int SetCursorPos(int x, int y);
extern __declspec(dllimport) void SetLastError(unsigned int dwErrCode);

void DoSomething(int Arg1, string& txt, double& Number, Optional unsigned int *xyz)
{
   SetCursorPos(10, Arg1 + 5);
   if (Arg1 == 15) {
      SetLastError(123);
   }
}

float main()
{
   double x;
   double pi;
   string MyString;
   DoSomething(Len("Test")+5, "Hello " + "world!", Sin(x+1)*pi, &x-4) //  Comment

   DoSomething(10, "abc", 5, 1);
   DoSomething(1, "x", 5, 0)  //  Etc...

   if (x > 1) {
      DoSomething(1, "x", 5, 0) //  Parenthesis already here
   }

   MyFunc(5);

   ShellExecute(0, "Open", "ReadMe.Txt", $Nul, $Nul, SW_ShowNormal);

   BinFile = 1;
   InFile  = 2;

   //  File handling test
   fstream file_BinFile (string("MyBin.Txt").c_str(), ios::binary | ios::in | ios::out);
   fstream file_InFile (string("MyInput.Txt").c_str(), ios::in);
   fstream file_3 (string("MyOutput.Txt").c_str(), ios::out | ios::trunc);
   fstream file_4 (string("MyAppend.Txt").c_str(), ios::out | ios::app);

   i = (missing);
   i = file_BinFile.tellg()+1;
   i = file_1.eof();
   file_BinFile.seekg(i+100-1);
   file_BinFile.seekp(i+100-1);

   MyString.resize(500);
   file_1.read(&MyString[0], 500);
   file_1.write(&MyString[0], MyString.size());

   file_3.close() //  PB: Close #3
   file_4.close() //  PB: Close #4
   file_BinFile.close() //  PB: Close #BinFile
   file_InFile.close() //  PB: Close #InFile

   i = (x > 1 ? Sin(x)+1 : Cos(x)-1) * 2;
   MyString = (x>50 ? PB_LEFT(MyString, 10) : PB_MID(MyString, 25, FULL_STRING));
} int;

//  This section tests transforms found in strings.uc
string StringTest(string& MyString, string OtherString)
{
   string MyText;
   int i;
   wstring MyWideStr;
   string Txt;
   string x;
   string y;
   wstring z;

   i = PB_INSTR(1, MyString, "abc");
   i = PB_INSTR(i+10, MyString, "xyz")*2;
   i = PB_INSTR_ANY(1, MyString, "aeiou");
   i = PB_INSTR(i+10, "This is a test", "is");
   i = PB_INSTR_ANY(1, "This is a test", "aeiou");
   i = PB_ASC("This is a test", 1);
   i = PB_ASC("This is a test", 10);
   y = PB_UCASE(MyString) + PB_LCASE(MyString);
   x = string(25, ' ') + string(10, '*') + string(10, 65);
   x = PB_TRIM_ANY(x, " ")+PB_LTRIM_ANY(x, " ")+PB_RTRIM_ANY(x, " ")+PB_TRIM_ANY(x, ".,! ")+PB_LTRIM_ANY(x, ".,! ")+PB_RTRIM_ANY(x, ".,! ");
   x = PB_REPEAT("Test", i+5);
   x = (i ? "This" : (i ? "That" : (i ? "Other" : (i ? "Misc" : 0))));
   i = ((rand() % (5) + (1)) ? 5 : ((rand() % (5) + (1)) ? 10 : ((rand() % (5) + (1)) ? 15 : ((rand() % (5) + (1)) ? 20 : ((rand() % (5) + (1)) ? 25 : 0)))));
   MyText = PB_LEFT(MyString, 3) + PB_MID(OtherString, 5, 10) + PB_RIGHT(x, i+1);
   MyText = PB_EXTRACT(1, MyText, "::") + PB_EXTRACT(5+2*i, x, "::");
   MyText = PB_EXTRACT_ANY(1, MyText, ".!?") + PB_EXTRACT_ANY(15, y, ".!?");
   MyText = PB_REMAIN(1, MyText, "::") + PB_REMAIN(5+2*i, x, "::");
   MyText = PB_REMAIN_ANY(1, MyText, ".!?") + PB_REMAIN_ANY(15, y, ".!?");
   MyText = PB_REMOVE(MyText, "test") + PB_REMOVE_ANY(MyText, ".!?");
   PB_REPLACE(MyText, "abc", "xyz");
   PB_REPLACE_ANY(MyText, "abc", "xyz");
   if (PB_MID(MyText, 3, 5) == y) {
      PB_MID_REPLACE(MyText, "Test" + to_string(i*15), 20, FULL_STRING);
   }
   PB_MID_REPLACE(x, y, 25, stold(y) +1);
   PB_MID_REPLACE(MyString, PB_MID(y, stold(x), 7), 25, 5);
   PB_MID_REPLACE(x, y, 25, FULL_STRING);
   PB_MID_REPLACE(MyString, PB_MID(y, stold(x), FULL_STRING), 25, FULL_STRING);
}

//  This tests exported subs/functions
extern "C" __declspec(dllexport) int __stdcall MyExport(int n) {
   StringTest("abc", "xyz");
}

extern "C" __declspec(dllexport) void __stdcall MyExportSub(int a, unsigned char b) {
   DoSomething(1, "xyz", 2, 3);
}

//  Math test
//  If x Mod 2 > Cint(Sqr(x^2 + y^2)) Then Incr q Else Decr q
double DoMath()
{
   if (x % 2 > lround(sqrt(pow(x, 2) + pow(y, 2)))) {
      q++;
   } else {
      q--;
   }
   n = sqrt(x) * atan(y) + 2 // * x^2 + Tan(x^3-1)^2
   pow(n == x, 2) + pow(y, 2);
   y = trunc(3.14159);

   srand(1234);
   y = (rand() / RAND_MAX) + (rand() / RAND_MAX) + (rand() % (2014) + (1995));
   x = (x >> 1);
   x = (x << 1);
}

//  Console routines
int PBConsoleTest()
{
   cout << "PB Semicolon at the end = No new line.  ";
   cout << "No semicolon = New Line at the end."  << endl;
}
<commit_msg>Update SampleCode.cpp<commit_after>// This file (SampleCode.cpp) was converted from SampleCode.Bas
// with uCalc Transform 2.5 on 2/25/2014 7:51:19 AM using the Open Source
// PowerBASIC to C++ converter found at https://github.com/uCalc/powerbasic-to-cpp

#include <math.h>
#include <stdlib.h>
#include <iostream>
#include <fstream>
#include <algorithm>
#include <string>
#include "pbstrings.h"
using namespace std;

//  File name: SampleCode.Bas
//  To convert this file to C++ make sure you have uCalc Transform on your PC
//  and *.uc from github.com/uCalc/powerbasic-to-cpp/tree/master/convert
//  Do the following at the Command Prompt:
//
//  C:\> PBtoCPP.Bat SampleCode.Bas

const int MyEquate = 0x100;
const int Other = 0x200;

int ProgStatus;

#if defined Other
//  Something
#elif !defined abcd
//  Something else
#else
//  Etc
#endif

#define MyMacroNum 12345
#define MyMacro(a, b, c) (a + b * (c))

struct point {
   int x;
   int y;
};

struct MyBits {
   unsigned int Year : 7;
   unsigned int Month : 5;
   unsigned int DayOfMonth : 4;
   unsigned int DayOfWeek : 3;
   unsigned char Red : 1;
   unsigned char Blue : 1;
   unsigned char Green : 1;
   double Other;
   long double xyz;
};

int MyFunc(int x)
{
   return x * 2;
}

int MyFunction(int a, float& b)
{
   int x;
   int y;
   int *Test = new int [a+25+1];
   int yVar;
   int MyValue;
   //  Dim q As Long
   //  The commented line above is not translated

   MyFunc(a);
   x = MyFunc(b)+1;

   if (b > 5) {
      for (x=1; x<=10; x += 1) {
         for (yVar=10; yVar>=1; yVar += -1) {
            if (x > y) {
               return a+y;
            }
            while (Test[a+5] == yVar) {
               while (!(a+1 == 1234)) {
                  if (y < MyEquate) {
                     return Test[x-y]*10;
                  }
                  a = a + 1;
                  do {
                     b = a * 5 + b;
                  } while (!(b == 300));
               }
            }
         }
      }
   }

   delete[] Test;
}

void MySub(int x)
{
   int y;
   float *Test;
   float *Number = new float [10+1];
   int *Other = new int [x+1];
   int z;

   ProgStatus = 10;
   y = x + 1;
   z = y+x;
   Other[x] = x+1;

   while (x < 10) {
      y = MyFunction(x, *Test);
      Test = &x;
      Number[z] = *Test + Other[5+x];
      x = x+1;
      if (Test < 0) {
         continue;
      }
      if (Test == y) {
         return;
      }
      if (Test == z) {
         break;
      }
   }

   delete[] Other;
   delete[] Number;
}
//   ' This line is broken up using a _ (underscore)
//   This is a commment (even without ')
//   Everything after _ is a comment

void TestCertainOperators(int x, int y, int z, double& OtherVar, float *FinalArg)
{
   //  Note: comments after _ are regrouped into a different place

   int *MyArray = new int [10+1];
   Point MyPoint;
   Point *pp;
   int n;

   for (x=1; x<=10; x += 1) {
      n = y == z //  This works differently in PB than in C++
      MyArray[x] = x*2;
      if (x == 5) {
         y = x+5;
      } else {
         y = 23*2;
      }
      y = x == z;
      MyArray[5] = MyArray[n] == MyArray[n+1];
      if (x == y == z) {
         y = n == 2;
      } else {
         y = n == 3;
      }
      if (x == y && x != 10 || y == x && x < 25) {
         y = x || y == z;
      }
      if ((x == y & x != 10 | y == x & x < 25)) {
         y = x || y == z;
      }
      if ((x == y & x != 10) || y == x && x < 25) {
         y = x || y == z;
      }
      if (~(x == y | x == z)) {
         x = y + 10;
      }
      if (~(x == y | x == z)) {
         x = y + 10;
      }

      if (x != y) {
         MyPoint.x = y;
      } else {
         MyPoint.x = x;
      }

      pp = &p;
      MyPoint.x = MyPoint.y+1;
      n = MyPoint.x == MyPoint.y;
      *pp.x = *pp.y == *pp.x+1;
   }

   delete[] MyArray;
}

//  The section below is a test for variables declared implicitely with data type
//  based on Def[Type] declarations or on type specifiers.

float MyValue;
string Label;
Currency Price;
long double ExtVal;
__int64 qNum;

int TestFunc(int& a, unsigned char& b, int& c, short& i, String& s, float& n)
{
   Print MyValue, Label, PriceB;

   Label = "Missing quote at the end of this line is added by Refactor.uc";
}

string Report(string& LastName, int x, double& NewPrice, float& n, short i, float& nValue, __int64& qValue)
{
   string FirstName;
   unsigned char Age;
   double Total;
   static int Index;

   Print LastName, x, NewPrice, n, i, nValue, qValue;
   Report = FirstName + LastName;
}

string Hello(string& txt)
{
   Print txt;
   return txt + " friend!";
}

unsigned char  Bye() {
   Print "Bye";
}

//  This section is a test for Subs or Functions that are called as a statement
//  without parentheses.  The converter adds them.

// #Include "Win32API.inc"
extern __declspec(dllimport) unsigned int ShellExecute(unsigned int hwnd, lpOperation As LPCSTR, lpFile As LPCSTR, lpParameters As LPCSTR, lpDirectory As LPCSTR, int nShowCmd);
extern __declspec(dllimport) int SetCursorPos(int x, int y);
extern __declspec(dllimport) void SetLastError(unsigned int dwErrCode);

void DoSomething(int Arg1, string& txt, long double& Number, Optional unsigned int *xyz)
{
   SetCursorPos(10, Arg1 + 5);
   if (Arg1 == 15) {
      SetLastError(123);
   }
}

float main()
{
   long double x;
   long double pi;
   string MyString;
   DoSomething(Len("Test")+5, "Hello " + "world!", Sin(x+1)*pi, &x-4) //  Comment

   DoSomething(10, "abc", 5, 1);
   DoSomething(1, "x", 5, 0)  //  Etc...

   if (x > 1) {
      DoSomething(1, "x", 5, 0) //  Parenthesis already here
   }

   MyFunc(5);

   ShellExecute(0, "Open", "ReadMe.Txt", $Nul, $Nul, SW_ShowNormal);

   BinFile = 1;
   InFile  = 2;

   //  File handling test
   fstream file_BinFile (string("MyBin.Txt").c_str(), ios::binary | ios::in | ios::out);
   fstream file_InFile (string("MyInput.Txt").c_str(), ios::in);
   fstream file_3 (string("MyOutput.Txt").c_str(), ios::out | ios::trunc);
   fstream file_4 (string("MyAppend.Txt").c_str(), ios::out | ios::app);

   i = (missing);
   i = file_BinFile.tellg()+1;
   i = file_1.eof();
   file_BinFile.seekg(i+100-1);
   file_BinFile.seekp(i+100-1);

   MyString.resize(500);
   file_1.read(&MyString[0], 500);
   file_1.write(&MyString[0], MyString.size());

   file_3.close() //  PB: Close #3
   file_4.close() //  PB: Close #4
   file_BinFile.close() //  PB: Close #BinFile
   file_InFile.close() //  PB: Close #InFile

   i = (x > 1 ? Sin(x)+1 : Cos(x)-1) * 2;
   MyString = (x>50 ? PB_LEFT(MyString, 10) : PB_MID(MyString, 25, FULL_STRING));
} int;

//  This section tests transforms found in strings.uc
string StringTest(string& MyString, string OtherString)
{
   string MyText;
   int i;
   wstring MyWideStr;
   string Txt;
   string x;
   string y;
   wstring z;

   i = PB_INSTR(1, MyString, "abc");
   i = PB_INSTR(i+10, MyString, "xyz")*2;
   i = PB_INSTR_ANY(1, MyString, "aeiou");
   i = PB_INSTR(i+10, "This is a test", "is");
   i = PB_INSTR_ANY(1, "This is a test", "aeiou");
   i = PB_ASC("This is a test", 1);
   i = PB_ASC("This is a test", 10);
   y = PB_UCASE(MyString) + PB_LCASE(MyString);
   x = string(25, ' ') + string(10, '*') + string(10, 65);
   x = PB_TRIM_ANY(x, " ")+PB_LTRIM_ANY(x, " ")+PB_RTRIM_ANY(x, " ")+PB_TRIM_ANY(x, ".,! ")+PB_LTRIM_ANY(x, ".,! ")+PB_RTRIM_ANY(x, ".,! ");
   x = PB_REPEAT("Test", i+5);
   x = (i ? "This" : (i ? "That" : (i ? "Other" : (i ? "Misc" : 0))));
   i = ((rand() % (5) + (1)) ? 5 : ((rand() % (5) + (1)) ? 10 : ((rand() % (5) + (1)) ? 15 : ((rand() % (5) + (1)) ? 20 : ((rand() % (5) + (1)) ? 25 : 0)))));
   MyText = PB_LEFT(MyString, 3) + PB_MID(OtherString, 5, 10) + PB_RIGHT(x, i+1);
   MyText = PB_EXTRACT(1, MyText, "::") + PB_EXTRACT(5+2*i, x, "::");
   MyText = PB_EXTRACT_ANY(1, MyText, ".!?") + PB_EXTRACT_ANY(15, y, ".!?");
   MyText = PB_REMAIN(1, MyText, "::") + PB_REMAIN(5+2*i, x, "::");
   MyText = PB_REMAIN_ANY(1, MyText, ".!?") + PB_REMAIN_ANY(15, y, ".!?");
   MyText = PB_REMOVE(MyText, "test") + PB_REMOVE_ANY(MyText, ".!?");
   PB_REPLACE(MyText, "abc", "xyz");
   PB_REPLACE_ANY(MyText, "abc", "xyz");
   if (PB_MID(MyText, 3, 5) == y) {
      PB_MID_REPLACE(MyText, "Test" + to_string((long double)i*15), 20, FULL_STRING);
   }
   PB_MID_REPLACE(x, y, 25, stold(y) +1);
   PB_MID_REPLACE(MyString, PB_MID(y, stold(x), 7), 25, 5);
   PB_MID_REPLACE(x, y, 25, FULL_STRING);
   PB_MID_REPLACE(MyString, PB_MID(y, stold(x), FULL_STRING), 25, FULL_STRING);
}

//  This tests exported subs/functions
extern "C" __declspec(dllexport) int __stdcall MyExport(int n) {
   StringTest("abc", "xyz");
}

extern "C" __declspec(dllexport) void __stdcall MyExportSub(int a, unsigned char b) {
   DoSomething(1, "xyz", 2, 3);
}

//  Math test
//  If x Mod 2 > Cint(Sqr(x^2 + y^2)) Then Incr q Else Decr q
double DoMath()
{
   if (x % 2 > lround(sqrt(pow(x, 2) + pow(y, 2)))) {
      q++;
   } else {
      q--;
   }
   n = sqrt(x) * atan(y) + 2 // * x^2 + Tan(x^3-1)^2
   pow(n == x, 2) + pow(y, 2);
   y = trunc(3.14159);

   srand(1234);
   y = (rand() / RAND_MAX) + (rand() / RAND_MAX) + (rand() % (2014) + (1995));
   x = (x >> 1);
   x = (x << 1);
}

//  Console routines
int PBConsoleTest()
{
   cout << "PB Semicolon at the end = No new line.  ";
   cout << "No semicolon = New Line at the end."  << endl;
}
<|endoftext|>


<commit_before>#include <string>
#include <vector>
#include <list>
#include <map>
#include <set>
#include <deque>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <iterator>
#include <tuple>
#include <regex>
#include <array>
#include <valarray>
#define all(v)begin(v),end(v)
#define dump(v)copy(all(v),ostream_iterator<decltype(*v.begin())>(cout,"\n"))
#define rg(i,a,b)for(int i=a,i##e=b;i<i##e;++i)
#define fr(i,n)for(int i=0,i##e=n;i<i##e;++i)
#define rf(i,n)for(int i=n-1;i>=0;--i)
#define ei(a,m)for(auto&a:m)if(int a##i=&a-&*begin(m)+1)if(--a##i,1)
#define sz(v)int(v.size())
#define sr(v)sort(all(v))
#define rs(v)sort(all(v),greater<int>())
#define rev(v)reverse(all(v))
#define eb emplace_back
#define stst stringstream
#define big numeric_limits<int>::max()
#define g(t,i)get<i>(t)
#define cb(v,w)copy(all(v),back_inserter(w))
#define uni(v)sort(all(v));v.erase(unique(all(v)),end(v))
#define vt(...)vector<tuple<__VA_ARGS__>>
#define smx(a,b)a=max(a,b)
#define smn(a,b)a=min(a,b)
#define words(w,q)vector<string>w;[&w](string&&s){stringstream u(s);string r;while(u>>r)w.eb(r);}(q);
#define digits(d,n,s)vector<int>d;[&d](int m){while(m)d.eb(m%s),m/=s;}(n);
typedef long long ll;
using namespace std;

struct MinDifference {
	int closestElements(int A0, int X, int Y, int M, int n) {
		int p = A0;
		int mn = big;
		for (int i = 1; i <= n - 1; ++i) {
			int n = (p * X + Y) % M;
			if (i < 10) cout << n << endl;
			mn = min(mn, abs(n - p));
			p = n;
		}
		return mn;
	}
};

// BEGIN KAWIGIEDIT TESTING
// Generated by KawigiEdit-pf 2.3.0
#include <iostream>
#include <string>
#include <vector>
#include <ctime>
#include <cmath>
using namespace std;
bool KawigiEdit_RunTest(int testNum, int p0, int p1, int p2, int p3, int p4, bool hasAnswer, int p5) {
	cout << "Test " << testNum << ": [" << p0 << "," << p1 << "," << p2 << "," << p3 << "," << p4;
	cout << "]" << endl;
	MinDifference *obj;
	int answer;
	obj = new MinDifference();
	clock_t startTime = clock();
	answer = obj->closestElements(p0, p1, p2, p3, p4);
	clock_t endTime = clock();
	delete obj;
	bool res;
	res = true;
	cout << "Time: " << double(endTime - startTime) / CLOCKS_PER_SEC << " seconds" << endl;
	if (hasAnswer) {
		cout << "Desired answer:" << endl;
		cout << "\t" << p5 << endl;
	}
	cout << "Your answer:" << endl;
	cout << "\t" << answer << endl;
	if (hasAnswer) {
		res = answer == p5;
	}
	if (!res) {
		cout << "DOESN'T MATCH!!!!" << endl;
	} else if (double(endTime - startTime) / CLOCKS_PER_SEC >= 2) {
		cout << "FAIL the timeout" << endl;
		res = false;
	} else if (hasAnswer) {
		cout << "Match :-)" << endl;
	} else {
		cout << "OK, but is it right?" << endl;
	}
	cout << "" << endl;
	return res;
}
int main() {
	bool all_right;
	bool disabled;
	bool tests_disabled;
	all_right = true;
	tests_disabled = false;

	int p0;
	int p1;
	int p2;
	int p3;
	int p4;
	int p5;

	// ----- test 0 -----
	disabled = false;
	p0 = 3;
	p1 = 7;
	p2 = 1;
	p3 = 101;
	p4 = 5;
	p5 = 6;
	all_right = (disabled || KawigiEdit_RunTest(0, p0, p1, p2, p3, p4, true, p5) ) && all_right;
	tests_disabled = tests_disabled || disabled;
	// ------------------

	// ----- test 1 -----
	disabled = false;
	p0 = 3;
	p1 = 9;
	p2 = 8;
	p3 = 32;
	p4 = 8;
	p5 = 0;
	all_right = (disabled || KawigiEdit_RunTest(1, p0, p1, p2, p3, p4, true, p5) ) && all_right;
	tests_disabled = tests_disabled || disabled;
	// ------------------

	// ----- test 2 -----
	disabled = false;
	p0 = 67;
	p1 = 13;
	p2 = 17;
	p3 = 4003;
	p4 = 23;
	p5 = 14;
	all_right = (disabled || KawigiEdit_RunTest(2, p0, p1, p2, p3, p4, true, p5) ) && all_right;
	tests_disabled = tests_disabled || disabled;
	// ------------------

	// ----- test 3 -----
	disabled = false;
	p0 = 1;
	p1 = 1221;
	p2 = 3553;
	p3 = 9889;
	p4 = 11;
	p5 = 275;
	all_right = (disabled || KawigiEdit_RunTest(3, p0, p1, p2, p3, p4, true, p5) ) && all_right;
	tests_disabled = tests_disabled || disabled;
	// ------------------

	// ----- test 4 -----
	disabled = false;
	p0 = 1;
	p1 = 1;
	p2 = 1;
	p3 = 2;
	p4 = 10000;
	p5 = 0;
	all_right = (disabled || KawigiEdit_RunTest(4, p0, p1, p2, p3, p4, true, p5) ) && all_right;
	tests_disabled = tests_disabled || disabled;
	// ------------------

	// ----- test 5 -----
	disabled = false;
	p0 = 1567;
	p1 = 5003;
	p2 = 9661;
	p3 = 8929;
	p4 = 43;
	p5 = 14;
	all_right = (disabled || KawigiEdit_RunTest(5, p0, p1, p2, p3, p4, true, p5) ) && all_right;
	tests_disabled = tests_disabled || disabled;
	// ------------------

	if (all_right) {
		if (tests_disabled) {
			cout << "You're a stud (but some test cases were disabled)!" << endl;
		} else {
			cout << "You're a stud (at least on given cases)!" << endl;
		}
	} else {
		cout << "Some of the test cases had errors." << endl;
	}
	return 0;
}
// END KAWIGIEDIT TESTING
<commit_msg>MinDifference<commit_after>#include <string>
#include <vector>
#include <list>
#include <map>
#include <set>
#include <deque>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <iterator>
#include <tuple>
#include <regex>
#include <array>
#include <valarray>
#define all(v)begin(v),end(v)
#define dump(v)copy(all(v),ostream_iterator<decltype(*v.begin())>(cout,"\n"))
#define rg(i,a,b)for(int i=a,i##e=b;i<i##e;++i)
#define fr(i,n)for(int i=0,i##e=n;i<i##e;++i)
#define rf(i,n)for(int i=n-1;i>=0;--i)
#define ei(a,m)for(auto&a:m)if(int a##i=&a-&*begin(m)+1)if(--a##i,1)
#define sz(v)int(v.size())
#define sr(v)sort(all(v))
#define rs(v)sort(all(v),greater<int>())
#define rev(v)reverse(all(v))
#define eb emplace_back
#define stst stringstream
#define big numeric_limits<int>::max()
#define g(t,i)get<i>(t)
#define cb(v,w)copy(all(v),back_inserter(w))
#define uni(v)sort(all(v));v.erase(unique(all(v)),end(v))
#define vt(...)vector<tuple<__VA_ARGS__>>
#define smx(a,b)a=max(a,b)
#define smn(a,b)a=min(a,b)
#define words(w,q)vector<string>w;[&w](string&&s){stringstream u(s);string r;while(u>>r)w.eb(r);}(q);
#define digits(d,n,s)vector<int>d;[&d](int m){while(m)d.eb(m%s),m/=s;}(n);
typedef long long ll;
using namespace std;

struct MinDifference {
	int closestElements(int A0, int X, int Y, int M, int n) {
		vector<int> v(A0);
		int mn = big;
		for (int i = 1; i <= n - 1; ++i) {
			v.push_back((v.back() * X + Y + M) % M);
		}
		sr(v);
		ei(a, v) if (ai > 0) mn = min(mn, abs(a - v[ai - 1]));
		return mn;
	}
};

// BEGIN KAWIGIEDIT TESTING
// Generated by KawigiEdit-pf 2.3.0
#include <iostream>
#include <string>
#include <vector>
#include <ctime>
#include <cmath>
using namespace std;
bool KawigiEdit_RunTest(int testNum, int p0, int p1, int p2, int p3, int p4, bool hasAnswer, int p5) {
	cout << "Test " << testNum << ": [" << p0 << "," << p1 << "," << p2 << "," << p3 << "," << p4;
	cout << "]" << endl;
	MinDifference *obj;
	int answer;
	obj = new MinDifference();
	clock_t startTime = clock();
	answer = obj->closestElements(p0, p1, p2, p3, p4);
	clock_t endTime = clock();
	delete obj;
	bool res;
	res = true;
	cout << "Time: " << double(endTime - startTime) / CLOCKS_PER_SEC << " seconds" << endl;
	if (hasAnswer) {
		cout << "Desired answer:" << endl;
		cout << "\t" << p5 << endl;
	}
	cout << "Your answer:" << endl;
	cout << "\t" << answer << endl;
	if (hasAnswer) {
		res = answer == p5;
	}
	if (!res) {
		cout << "DOESN'T MATCH!!!!" << endl;
	} else if (double(endTime - startTime) / CLOCKS_PER_SEC >= 2) {
		cout << "FAIL the timeout" << endl;
		res = false;
	} else if (hasAnswer) {
		cout << "Match :-)" << endl;
	} else {
		cout << "OK, but is it right?" << endl;
	}
	cout << "" << endl;
	return res;
}
int main() {
	bool all_right;
	bool disabled;
	bool tests_disabled;
	all_right = true;
	tests_disabled = false;

	int p0;
	int p1;
	int p2;
	int p3;
	int p4;
	int p5;

	// ----- test 0 -----
	disabled = false;
	p0 = 3;
	p1 = 7;
	p2 = 1;
	p3 = 101;
	p4 = 5;
	p5 = 6;
	all_right = (disabled || KawigiEdit_RunTest(0, p0, p1, p2, p3, p4, true, p5) ) && all_right;
	tests_disabled = tests_disabled || disabled;
	// ------------------

	// ----- test 1 -----
	disabled = false;
	p0 = 3;
	p1 = 9;
	p2 = 8;
	p3 = 32;
	p4 = 8;
	p5 = 0;
	all_right = (disabled || KawigiEdit_RunTest(1, p0, p1, p2, p3, p4, true, p5) ) && all_right;
	tests_disabled = tests_disabled || disabled;
	// ------------------

	// ----- test 2 -----
	disabled = false;
	p0 = 67;
	p1 = 13;
	p2 = 17;
	p3 = 4003;
	p4 = 23;
	p5 = 14;
	all_right = (disabled || KawigiEdit_RunTest(2, p0, p1, p2, p3, p4, true, p5) ) && all_right;
	tests_disabled = tests_disabled || disabled;
	// ------------------

	// ----- test 3 -----
	disabled = false;
	p0 = 1;
	p1 = 1221;
	p2 = 3553;
	p3 = 9889;
	p4 = 11;
	p5 = 275;
	all_right = (disabled || KawigiEdit_RunTest(3, p0, p1, p2, p3, p4, true, p5) ) && all_right;
	tests_disabled = tests_disabled || disabled;
	// ------------------

	// ----- test 4 -----
	disabled = false;
	p0 = 1;
	p1 = 1;
	p2 = 1;
	p3 = 2;
	p4 = 10000;
	p5 = 0;
	all_right = (disabled || KawigiEdit_RunTest(4, p0, p1, p2, p3, p4, true, p5) ) && all_right;
	tests_disabled = tests_disabled || disabled;
	// ------------------

	// ----- test 5 -----
	disabled = false;
	p0 = 1567;
	p1 = 5003;
	p2 = 9661;
	p3 = 8929;
	p4 = 43;
	p5 = 14;
	all_right = (disabled || KawigiEdit_RunTest(5, p0, p1, p2, p3, p4, true, p5) ) && all_right;
	tests_disabled = tests_disabled || disabled;
	// ------------------

	if (all_right) {
		if (tests_disabled) {
			cout << "You're a stud (but some test cases were disabled)!" << endl;
		} else {
			cout << "You're a stud (at least on given cases)!" << endl;
		}
	} else {
		cout << "Some of the test cases had errors." << endl;
	}
	return 0;
}
// END KAWIGIEDIT TESTING
<|endoftext|>


<commit_before>#include "diagramactoritem.h"
#include "diagramscene.h"

DiagramActorItem::DiagramActorItem(QGraphicsItem *parent, QGraphicsScene *scene)
    : QGraphicsTextItem(parent, scene)
{
    setFlag(QGraphicsItem::ItemIsMovable);
    setFlag(QGraphicsItem::ItemIsSelectable);
	this->typeElementData = Comment;

}
QVariant DiagramActorItem::itemChange(GraphicsItemChange change,
                     const QVariant &value)
{
    if (change == QGraphicsItem::ItemSelectedHasChanged)
        emit selectedChange(this);
    return value;
}
void DiagramActorItem::focusOutEvent(QFocusEvent *event)
{
    setTextInteractionFlags(Qt::NoTextInteraction);
    emit lostFocus(this);
    QGraphicsTextItem::focusOutEvent(event);
}
void DiagramActorItem::mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event)
{
    if (textInteractionFlags() == Qt::NoTextInteraction)
        setTextInteractionFlags(Qt::TextEditorInteraction);
    QGraphicsTextItem::mouseDoubleClickEvent(event);
}<commit_msg>поправил отображение картинки "участника"<commit_after>#include "diagramactoritem.h"
#include "diagramscene.h"

DiagramActorItem::DiagramActorItem(QGraphicsItem *parent, QGraphicsScene *scene)
    : QGraphicsTextItem(parent, scene)
{
    setFlag(QGraphicsItem::ItemIsMovable);
    setFlag(QGraphicsItem::ItemIsSelectable);
	this->typeElementData = Comment;

}
QVariant DiagramActorItem::itemChange(GraphicsItemChange change,
                     const QVariant &value)
{
    if (change == QGraphicsItem::ItemSelectedHasChanged)
        emit selectedChange(this);
    return value;
}
void DiagramActorItem::focusOutEvent(QFocusEvent *event)
{
    QString str;
    setTextInteractionFlags(Qt::NoTextInteraction);
    str=this->toPlainText();
    int i=0;
    int pos=0;
    bool imgFlag=false;
    while(i<str.size()&&imgFlag!=true)
    {
        if(str.at(i).unicode()>256)
        {
            imgFlag=true;
            pos=i;
        }
        i++;
    }
    if(imgFlag==false)
    {
        this->setHtml(QString("")+"
"+str+"
");
    }
    if(imgFlag==true&&(pos-1)!=0)
    {
        this->setHtml(QString("")+"
"+str.right(str.size()-2-pos+1)+"
");
    }
    emit lostFocus(this);
    QGraphicsTextItem::focusOutEvent(event);
}
void DiagramActorItem::mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event)
{
    if (textInteractionFlags() == Qt::NoTextInteraction)
        setTextInteractionFlags(Qt::TextEditorInteraction);
    QGraphicsTextItem::mouseDoubleClickEvent(event);
}<|endoftext|>


<commit_before>// Copyright (c) 2011 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 "printing/printed_document.h"

#include "base/logging.h"
#include "base/string_util.h"
#include "base/utf_string_conversions.h"
#include "printing/page_number.h"
#include "printing/page_overlays.h"
#include "printing/printed_pages_source.h"
#include "printing/printed_page.h"
#include "printing/units.h"
#include "skia/ext/platform_device.h"
#include "ui/gfx/font.h"

namespace {

void SimpleModifyWorldTransform(HDC context,
                                int offset_x,
                                int offset_y,
                                double shrink_factor) {
  XFORM xform = { 0 };
  xform.eDx = static_cast<float>(offset_x);
  xform.eDy = static_cast<float>(offset_y);
  xform.eM11 = xform.eM22 = static_cast<float>(1. / shrink_factor);
  BOOL res = ModifyWorldTransform(context, &xform, MWT_LEFTMULTIPLY);
  DCHECK_NE(res, 0);
}

void DrawRect(HDC context, gfx::Rect rect) {
  Rectangle(context, rect.x(), rect.y(), rect.right(), rect.bottom());
}

// Creates a string interpretation of the time of day represented by the given
// SYSTEMTIME that's appropriate for the user's default locale.
// Format can be an empty string (for the default format), or a "format picture"
// as specified in the Windows documentation for GetTimeFormat().
string16 FormatSystemTime(const SYSTEMTIME& time, const string16& format) {
  // If the format string is empty, just use the default format.
  LPCTSTR format_ptr = NULL;
  if (!format.empty())
    format_ptr = format.c_str();

  int buffer_size = GetTimeFormat(LOCALE_USER_DEFAULT, NULL, &time, format_ptr,
                                  NULL, 0);

  string16 output;
  GetTimeFormat(LOCALE_USER_DEFAULT, NULL, &time, format_ptr,
                WriteInto(&output, buffer_size), buffer_size);

  return output;
}

// Creates a string interpretation of the date represented by the given
// SYSTEMTIME that's appropriate for the user's default locale.
// Format can be an empty string (for the default format), or a "format picture"
// as specified in the Windows documentation for GetDateFormat().
string16 FormatSystemDate(const SYSTEMTIME& date, const string16& format) {
  // If the format string is empty, just use the default format.
  LPCTSTR format_ptr = NULL;
  if (!format.empty())
    format_ptr = format.c_str();

  int buffer_size = GetDateFormat(LOCALE_USER_DEFAULT, NULL, &date, format_ptr,
                                  NULL, 0);

  string16 output;
  GetDateFormat(LOCALE_USER_DEFAULT, NULL, &date, format_ptr,
                WriteInto(&output, buffer_size), buffer_size);

  return output;
}

}  // namespace

namespace printing {

void PrintedDocument::RenderPrintedPage(
    const PrintedPage& page, gfx::NativeDrawingContext context) const {
#ifndef NDEBUG
  {
    // Make sure the page is from our list.
    base::AutoLock lock(lock_);
    DCHECK(&page == mutable_.pages_.find(page.page_number() - 1)->second.get());
  }
#endif

  DCHECK(context);

  const printing::PageSetup& page_setup(
      immutable_.settings_.page_setup_device_units());
  gfx::Rect content_area;
  page.GetCenteredPageContentRect(page_setup.physical_size(), &content_area);

  // Save the state to make sure the context this function call does not modify
  // the device context.
  int saved_state = SaveDC(context);
  DCHECK_NE(saved_state, 0);
  skia::PlatformDevice::InitializeDC(context);
  {
    // Save the state (again) to apply the necessary world transformation.
    int saved_state = SaveDC(context);
    DCHECK_NE(saved_state, 0);

    // Setup the matrix to translate and scale to the right place. Take in
    // account the actual shrinking factor.
    // Note that the printing output is relative to printable area of the page.
    // That is 0,0 is offset by PHYSICALOFFSETX/Y from the page.
    SimpleModifyWorldTransform(
        context,
        content_area.x() - page_setup.printable_area().x(),
        content_area.y() - page_setup.printable_area().y(),
        mutable_.shrink_factor);

    if (!page.native_metafile()->SafePlayback(context)) {
      NOTREACHED();
    }

    BOOL res = RestoreDC(context, saved_state);
    DCHECK_NE(res, 0);
  }

  // Print the header and footer.  Offset by printable area offset (see comment
  // above).
  SimpleModifyWorldTransform(
      context,
      -page_setup.printable_area().x(),
      -page_setup.printable_area().y(),
      1);
  int base_font_size = gfx::Font().GetHeight();
  int new_font_size = ConvertUnit(10,
                                  immutable_.settings_.desired_dpi,
                                  immutable_.settings_.device_units_per_inch());
  DCHECK_GT(new_font_size, base_font_size);
  gfx::Font font(gfx::Font().DeriveFont(new_font_size - base_font_size));
  HGDIOBJ old_font = SelectObject(context, font.GetNativeFont());
  DCHECK(old_font != NULL);
  // We don't want a white square around the text ever if overflowing.
  SetBkMode(context, TRANSPARENT);
  PrintHeaderFooter(context, page, PageOverlays::LEFT, PageOverlays::TOP,
                    font);
  PrintHeaderFooter(context, page, PageOverlays::CENTER, PageOverlays::TOP,
                    font);
  PrintHeaderFooter(context, page, PageOverlays::RIGHT, PageOverlays::TOP,
                    font);
  PrintHeaderFooter(context, page, PageOverlays::LEFT, PageOverlays::BOTTOM,
                    font);
  PrintHeaderFooter(context, page, PageOverlays::CENTER, PageOverlays::BOTTOM,
                    font);
  PrintHeaderFooter(context, page, PageOverlays::RIGHT, PageOverlays::BOTTOM,
                    font);
  int res = RestoreDC(context, saved_state);
  DCHECK_NE(res, 0);
}

void PrintedDocument::Immutable::SetDocumentDate() {
  // Use the native time formatting for printing on Windows.
  SYSTEMTIME systemtime;
  GetLocalTime(&systemtime);
  date_ =
      WideToUTF16Hack(FormatSystemDate(systemtime, std::wstring()));
  time_ =
      WideToUTF16Hack(FormatSystemTime(systemtime, std::wstring()));
}

void PrintedDocument::DrawHeaderFooter(gfx::NativeDrawingContext context,
                                       std::wstring text,
                                       gfx::Rect bounds) const {
  // Save the state for the clipping region.
  int saved_state = SaveDC(context);
  DCHECK_NE(saved_state, 0);

  int result = IntersectClipRect(context, bounds.x(), bounds.y(),
                                 bounds.right() + 1, bounds.bottom() + 1);
  DCHECK(result == SIMPLEREGION || result == COMPLEXREGION);
  TextOut(context,
          bounds.x(), bounds.y(),
          text.c_str(),
          static_cast<int>(text.size()));
  int res = RestoreDC(context, saved_state);
  DCHECK_NE(res, 0);
}

}  // namespace printing
<commit_msg>Printing: Disable printing the header/footer on Windows.<commit_after>// Copyright (c) 2011 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 "printing/printed_document.h"

#include "base/logging.h"
#include "base/string_util.h"
#include "base/utf_string_conversions.h"
#include "printing/page_number.h"
#include "printing/page_overlays.h"
#include "printing/printed_pages_source.h"
#include "printing/printed_page.h"
#include "printing/units.h"
#include "skia/ext/platform_device.h"
#include "ui/gfx/font.h"

namespace {

void SimpleModifyWorldTransform(HDC context,
                                int offset_x,
                                int offset_y,
                                double shrink_factor) {
  XFORM xform = { 0 };
  xform.eDx = static_cast<float>(offset_x);
  xform.eDy = static_cast<float>(offset_y);
  xform.eM11 = xform.eM22 = static_cast<float>(1. / shrink_factor);
  BOOL res = ModifyWorldTransform(context, &xform, MWT_LEFTMULTIPLY);
  DCHECK_NE(res, 0);
}

void DrawRect(HDC context, gfx::Rect rect) {
  Rectangle(context, rect.x(), rect.y(), rect.right(), rect.bottom());
}

// Creates a string interpretation of the time of day represented by the given
// SYSTEMTIME that's appropriate for the user's default locale.
// Format can be an empty string (for the default format), or a "format picture"
// as specified in the Windows documentation for GetTimeFormat().
string16 FormatSystemTime(const SYSTEMTIME& time, const string16& format) {
  // If the format string is empty, just use the default format.
  LPCTSTR format_ptr = NULL;
  if (!format.empty())
    format_ptr = format.c_str();

  int buffer_size = GetTimeFormat(LOCALE_USER_DEFAULT, NULL, &time, format_ptr,
                                  NULL, 0);

  string16 output;
  GetTimeFormat(LOCALE_USER_DEFAULT, NULL, &time, format_ptr,
                WriteInto(&output, buffer_size), buffer_size);

  return output;
}

// Creates a string interpretation of the date represented by the given
// SYSTEMTIME that's appropriate for the user's default locale.
// Format can be an empty string (for the default format), or a "format picture"
// as specified in the Windows documentation for GetDateFormat().
string16 FormatSystemDate(const SYSTEMTIME& date, const string16& format) {
  // If the format string is empty, just use the default format.
  LPCTSTR format_ptr = NULL;
  if (!format.empty())
    format_ptr = format.c_str();

  int buffer_size = GetDateFormat(LOCALE_USER_DEFAULT, NULL, &date, format_ptr,
                                  NULL, 0);

  string16 output;
  GetDateFormat(LOCALE_USER_DEFAULT, NULL, &date, format_ptr,
                WriteInto(&output, buffer_size), buffer_size);

  return output;
}

}  // namespace

namespace printing {

void PrintedDocument::RenderPrintedPage(
    const PrintedPage& page, gfx::NativeDrawingContext context) const {
#ifndef NDEBUG
  {
    // Make sure the page is from our list.
    base::AutoLock lock(lock_);
    DCHECK(&page == mutable_.pages_.find(page.page_number() - 1)->second.get());
  }
#endif

  DCHECK(context);

  const printing::PageSetup& page_setup(
      immutable_.settings_.page_setup_device_units());
  gfx::Rect content_area;
  page.GetCenteredPageContentRect(page_setup.physical_size(), &content_area);

  // Save the state to make sure the context this function call does not modify
  // the device context.
  int saved_state = SaveDC(context);
  DCHECK_NE(saved_state, 0);
  skia::PlatformDevice::InitializeDC(context);
  {
    // Save the state (again) to apply the necessary world transformation.
    int saved_state = SaveDC(context);
    DCHECK_NE(saved_state, 0);

    // Setup the matrix to translate and scale to the right place. Take in
    // account the actual shrinking factor.
    // Note that the printing output is relative to printable area of the page.
    // That is 0,0 is offset by PHYSICALOFFSETX/Y from the page.
    SimpleModifyWorldTransform(
        context,
        content_area.x() - page_setup.printable_area().x(),
        content_area.y() - page_setup.printable_area().y(),
        mutable_.shrink_factor);

    if (!page.native_metafile()->SafePlayback(context)) {
      NOTREACHED();
    }

    BOOL res = RestoreDC(context, saved_state);
    DCHECK_NE(res, 0);
  }

  // Print the header and footer.  Offset by printable area offset (see comment
  // above).
  SimpleModifyWorldTransform(
      context,
      -page_setup.printable_area().x(),
      -page_setup.printable_area().y(),
      1);
  int base_font_size = gfx::Font().GetHeight();
  int new_font_size = ConvertUnit(10,
                                  immutable_.settings_.desired_dpi,
                                  immutable_.settings_.device_units_per_inch());
  DCHECK_GT(new_font_size, base_font_size);
  gfx::Font font(gfx::Font().DeriveFont(new_font_size - base_font_size));
  HGDIOBJ old_font = SelectObject(context, font.GetNativeFont());
  DCHECK(old_font != NULL);
  // We don't want a white square around the text ever if overflowing.
  SetBkMode(context, TRANSPARENT);
  // Disabling printing the header/footer on Windows for now to make the
  // behavior consistent with Mac/Linux.
  // TODO(thestig) re-enable this for print preview.
#if 0
  PrintHeaderFooter(context, page, PageOverlays::LEFT, PageOverlays::TOP,
                    font);
  PrintHeaderFooter(context, page, PageOverlays::CENTER, PageOverlays::TOP,
                    font);
  PrintHeaderFooter(context, page, PageOverlays::RIGHT, PageOverlays::TOP,
                    font);
  PrintHeaderFooter(context, page, PageOverlays::LEFT, PageOverlays::BOTTOM,
                    font);
  PrintHeaderFooter(context, page, PageOverlays::CENTER, PageOverlays::BOTTOM,
                    font);
  PrintHeaderFooter(context, page, PageOverlays::RIGHT, PageOverlays::BOTTOM,
                    font);
#endif
  int res = RestoreDC(context, saved_state);
  DCHECK_NE(res, 0);
}

void PrintedDocument::Immutable::SetDocumentDate() {
  // Use the native time formatting for printing on Windows.
  SYSTEMTIME systemtime;
  GetLocalTime(&systemtime);
  date_ =
      WideToUTF16Hack(FormatSystemDate(systemtime, std::wstring()));
  time_ =
      WideToUTF16Hack(FormatSystemTime(systemtime, std::wstring()));
}

void PrintedDocument::DrawHeaderFooter(gfx::NativeDrawingContext context,
                                       std::wstring text,
                                       gfx::Rect bounds) const {
  // Save the state for the clipping region.
  int saved_state = SaveDC(context);
  DCHECK_NE(saved_state, 0);

  int result = IntersectClipRect(context, bounds.x(), bounds.y(),
                                 bounds.right() + 1, bounds.bottom() + 1);
  DCHECK(result == SIMPLEREGION || result == COMPLEXREGION);
  TextOut(context,
          bounds.x(), bounds.y(),
          text.c_str(),
          static_cast<int>(text.size()));
  int res = RestoreDC(context, saved_state);
  DCHECK_NE(res, 0);
}

}  // namespace printing
<|endoftext|>