<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: cliptest.cxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: rt $ $Date: 2007-07-05 08:56:07 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// autogenerated file with codegen.pl

#include <cppunit/simpleheader.hxx>

#include <basegfx/vector/b2isize.hxx>
#include <basegfx/point/b2ipoint.hxx>
#include <basegfx/range/b2drange.hxx>
#include <basegfx/range/b2irange.hxx>
#include <basegfx/polygon/b2dpolygon.hxx>
#include <basegfx/polygon/b2dpolygontools.hxx>
#include <basegfx/polygon/b2dpolypolygon.hxx>
#include <basegfx/polygon/b2dpolypolygontools.hxx>

#include <basebmp/color.hxx>
#include <basebmp/scanlineformats.hxx>
#include <basebmp/bitmapdevice.hxx>
#include <basebmp/debug.hxx>
#include "tools.hxx"

#include <iostream>
#include <fstream>

using namespace ::basebmp;

namespace
{
/*
  std::ofstream output("32bpp_test.dump");
  debugDump( mpDevice32bpp, output );
*/

class ClipTest : public CppUnit::TestFixture
{
private:
    BitmapDeviceSharedPtr mpClipMask;
    BitmapDeviceSharedPtr mpDevice1bpp;
    BitmapDeviceSharedPtr mpDevice32bpp;

    void implTestPixelClip(const BitmapDeviceSharedPtr& rDevice)
    {
        const Color aBgCol(0);
        rDevice->clear(aBgCol);

        const basegfx::B2IPoint aPt(0,0);
        const Color aCol(0xFFFFFFFF);
        rDevice->setPixel( aPt, aCol, DrawMode_PAINT, mpClipMask );
        CPPUNIT_ASSERT_MESSAGE("get/setPixel clip #1",
                               rDevice->getPixel(aPt) == aBgCol);

        const basegfx::B2IPoint aPt2(10,10);
        rDevice->setPixel( aPt2, aCol, DrawMode_PAINT, mpClipMask );
        CPPUNIT_ASSERT_MESSAGE("get/setPixel clip #2",
                               rDevice->getPixel(aPt2) == aBgCol);

        const basegfx::B2IPoint aPt1(10,0);
        rDevice->setPixel( aPt1, aCol, DrawMode_PAINT, mpClipMask );
        CPPUNIT_ASSERT_MESSAGE("get/setPixel clip #3",
                               rDevice->getPixel(aPt1) != aBgCol);

        const basegfx::B2IPoint aPt3(0,10);
        rDevice->setPixel( aPt3, aCol, DrawMode_PAINT, mpClipMask );
        CPPUNIT_ASSERT_MESSAGE("get/setPixel clip #4",
                               rDevice->getPixel(aPt3) != aBgCol);
    }

    void implTestLineClip(const BitmapDeviceSharedPtr& rDevice)
    {
        const Color aBgCol(0);
        rDevice->clear(aBgCol);

        const basegfx::B2IPoint aPt1(0,0);
        const basegfx::B2IPoint aPt2(1,9);
        const Color aCol(0xFFFFFFFF);
        rDevice->drawLine( aPt1, aPt2, aCol, DrawMode_PAINT, mpClipMask );

        const basegfx::B2IPoint aPt3(1,5);
        CPPUNIT_ASSERT_MESSAGE("get line pixel",
                               rDevice->getPixel(aPt3) != aBgCol);
        CPPUNIT_ASSERT_MESSAGE("number of rendered line pixel is not 4",
                               countPixel( rDevice,
                                           rDevice->getPixel(aPt3) ) == 4);

        rDevice->drawLine( aPt1, aPt2, aCol, DrawMode_XOR, mpClipMask );
        CPPUNIT_ASSERT_MESSAGE("number of xor-rendered line pixel is not 0",
                               countPixel( rDevice,
                                           rDevice->getPixel(aPt3) ) == 121);
    }

    void implTestFillClip(const BitmapDeviceSharedPtr& rDevice)
    {
        rDevice->clear(Color(0));

        const basegfx::B2DRange aAllOver(-10,-10,20,20);
        const Color aCol(0xFFFFFFFF);
        rDevice->fillPolyPolygon( basegfx::B2DPolyPolygon(
                                      basegfx::tools::createPolygonFromRect(aAllOver)),
                                  aCol,
                                  DrawMode_PAINT,
                                  mpClipMask );
        const basegfx::B2IPoint aPt(0,10);
        CPPUNIT_ASSERT_MESSAGE("number of clipped pixel is not 30",
                               countPixel( rDevice, rDevice->getPixel(aPt) ) == 121-30);

        rDevice->fillPolyPolygon( basegfx::B2DPolyPolygon(
                                      basegfx::tools::createPolygonFromRect(aAllOver)),
                                  aCol,
                                  DrawMode_PAINT );
        CPPUNIT_ASSERT_MESSAGE("number of filled pixel is not 121",
                               countPixel( rDevice, rDevice->getPixel(aPt) ) == 121);

        rDevice->fillPolyPolygon( basegfx::B2DPolyPolygon(
                                      basegfx::tools::createPolygonFromRect(aAllOver)),
                                  aCol,
                                  DrawMode_XOR,
                                  mpClipMask );
        CPPUNIT_ASSERT_MESSAGE("number of xor-cleared pixel is not 91",
                               countPixel( rDevice, rDevice->getPixel(aPt) ) == 121-30);
    }

    void implTestBmpClip(const BitmapDeviceSharedPtr& rDevice)
    {
        BitmapDeviceSharedPtr pBmp( cloneBitmapDevice(
                                        basegfx::B2IVector(3,3),
                                        rDevice ));
        Color aCol1(0);
        Color aCol2(0xFFFFFFFF);
        pBmp->clear(aCol1);
        pBmp->setPixel(basegfx::B2IPoint(0,0),aCol2,DrawMode_PAINT);
        pBmp->setPixel(basegfx::B2IPoint(1,1),aCol2,DrawMode_PAINT);
        pBmp->setPixel(basegfx::B2IPoint(2,2),aCol2,basebmp::DrawMode_PAINT);

        rDevice->clear(aCol1);
        rDevice->drawBitmap(pBmp,
                            basegfx::B2IRange(0,0,3,3),
                            basegfx::B2IRange(-1,-1,4,4),
                            DrawMode_PAINT,
                            mpClipMask);

        const basegfx::B2IPoint aPt(1,1);
        CPPUNIT_ASSERT_MESSAGE("number of clipped pixel is not 5",
                               countPixel( rDevice,
                                           rDevice->getPixel(aPt) ) == 5);
    }

    void implTestMaskColorClip(const BitmapDeviceSharedPtr& rDevice)
    {
        BitmapDeviceSharedPtr pBmp( createBitmapDevice( rDevice->getSize(),
                                                        true,
                                                        Format::EIGHT_BIT_GREY ));

        ::rtl::OUString aSvg = ::rtl::OUString::createFromAscii(
            "m 0 0h5v10h5v-5h-10z" );

        basegfx::B2DPolyPolygon aPoly;
        basegfx::tools::importFromSvgD( aPoly, aSvg );
        const basebmp::Color aCol(0xFF);
        pBmp->clear( basebmp::Color(0) );
        pBmp->fillPolyPolygon(
            aPoly,
            aCol,
            basebmp::DrawMode_PAINT );

        const basegfx::B2IRange aSourceRect(0,0,10,10);
        const basegfx::B2IPoint aDestLeftTop(0,0);
        const Color aCol2(0xF0F0F0F0);
        rDevice->drawMaskedColor(
            aCol2,
            pBmp,
            aSourceRect,
            aDestLeftTop,
            mpClipMask );
        const basegfx::B2IPoint aPt(1,1);
        CPPUNIT_ASSERT_MESSAGE("number of rendered pixel is not 41",
                               countPixel( rDevice, rDevice->getPixel(aPt) ) == 41);

    }

public:
    void setUp()
    {
        const basegfx::B2ISize aSize(11,11);
        mpClipMask = createBitmapDevice( aSize,
                                         true,
                                         Format::ONE_BIT_MSB_GREY );
        mpDevice1bpp = createBitmapDevice( aSize,
                                           true,
                                           Format::ONE_BIT_MSB_PAL );
        mpDevice32bpp = createBitmapDevice( aSize,
                                           true,
                                           Format::THIRTYTWO_BIT_TC_MASK );

        ::rtl::OUString aSvg = ::rtl::OUString::createFromAscii(
            "m 0 0 h5 l5 5 v5 h-5 l-5-5 z" );
        basegfx::B2DPolyPolygon aPoly;
        basegfx::tools::importFromSvgD( aPoly, aSvg );
        mpClipMask->clear(Color(0));
        mpClipMask->drawPolygon(
            aPoly.getB2DPolygon(0),
            Color(0xFFFFFFFF),
            DrawMode_PAINT );
    }

    void testPixelClip()
    {
        implTestPixelClip( mpDevice1bpp );
        implTestPixelClip( mpDevice32bpp );
    }

    void testLineClip()
    {
        implTestLineClip( mpDevice1bpp );
        implTestLineClip( mpDevice32bpp );
    }

    void testFillClip()
    {
        implTestFillClip( mpDevice1bpp );
        implTestFillClip( mpDevice32bpp );
    }

    void testBmpClip()
    {
        implTestBmpClip( mpDevice1bpp );
        implTestBmpClip( mpDevice32bpp );
    }

    void testMaskColorClip()
    {
        implTestMaskColorClip( mpDevice1bpp );
        implTestMaskColorClip( mpDevice32bpp );
    }

    // Change the following lines only, if you add, remove or rename
    // member functions of the current class,
    // because these macros are need by auto register mechanism.

    CPPUNIT_TEST_SUITE(ClipTest);
    CPPUNIT_TEST(testPixelClip);
    CPPUNIT_TEST(testLineClip);
    CPPUNIT_TEST(testFillClip);
    CPPUNIT_TEST(testBmpClip);
    CPPUNIT_TEST(testMaskColorClip);
    CPPUNIT_TEST_SUITE_END();
};

// -----------------------------------------------------------------------------
CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(ClipTest, "ClipTest");
}

// -----------------------------------------------------------------------------

// this macro creates an empty function, which will called by the RegisterAllFunctions()
// to let the user the possibility to also register some functions by hand.
//NOADDITIONAL;

<commit_msg>INTEGRATION: CWS changefileheader (1.5.24); FILE MERGED 2008/03/31 13:07:57 rt 1.5.24.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: cliptest.cxx,v $
 * $Revision: 1.6 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

// autogenerated file with codegen.pl

#include <cppunit/simpleheader.hxx>

#include <basegfx/vector/b2isize.hxx>
#include <basegfx/point/b2ipoint.hxx>
#include <basegfx/range/b2drange.hxx>
#include <basegfx/range/b2irange.hxx>
#include <basegfx/polygon/b2dpolygon.hxx>
#include <basegfx/polygon/b2dpolygontools.hxx>
#include <basegfx/polygon/b2dpolypolygon.hxx>
#include <basegfx/polygon/b2dpolypolygontools.hxx>

#include <basebmp/color.hxx>
#include <basebmp/scanlineformats.hxx>
#include <basebmp/bitmapdevice.hxx>
#include <basebmp/debug.hxx>
#include "tools.hxx"

#include <iostream>
#include <fstream>

using namespace ::basebmp;

namespace
{
/*
  std::ofstream output("32bpp_test.dump");
  debugDump( mpDevice32bpp, output );
*/

class ClipTest : public CppUnit::TestFixture
{
private:
    BitmapDeviceSharedPtr mpClipMask;
    BitmapDeviceSharedPtr mpDevice1bpp;
    BitmapDeviceSharedPtr mpDevice32bpp;

    void implTestPixelClip(const BitmapDeviceSharedPtr& rDevice)
    {
        const Color aBgCol(0);
        rDevice->clear(aBgCol);

        const basegfx::B2IPoint aPt(0,0);
        const Color aCol(0xFFFFFFFF);
        rDevice->setPixel( aPt, aCol, DrawMode_PAINT, mpClipMask );
        CPPUNIT_ASSERT_MESSAGE("get/setPixel clip #1",
                               rDevice->getPixel(aPt) == aBgCol);

        const basegfx::B2IPoint aPt2(10,10);
        rDevice->setPixel( aPt2, aCol, DrawMode_PAINT, mpClipMask );
        CPPUNIT_ASSERT_MESSAGE("get/setPixel clip #2",
                               rDevice->getPixel(aPt2) == aBgCol);

        const basegfx::B2IPoint aPt1(10,0);
        rDevice->setPixel( aPt1, aCol, DrawMode_PAINT, mpClipMask );
        CPPUNIT_ASSERT_MESSAGE("get/setPixel clip #3",
                               rDevice->getPixel(aPt1) != aBgCol);

        const basegfx::B2IPoint aPt3(0,10);
        rDevice->setPixel( aPt3, aCol, DrawMode_PAINT, mpClipMask );
        CPPUNIT_ASSERT_MESSAGE("get/setPixel clip #4",
                               rDevice->getPixel(aPt3) != aBgCol);
    }

    void implTestLineClip(const BitmapDeviceSharedPtr& rDevice)
    {
        const Color aBgCol(0);
        rDevice->clear(aBgCol);

        const basegfx::B2IPoint aPt1(0,0);
        const basegfx::B2IPoint aPt2(1,9);
        const Color aCol(0xFFFFFFFF);
        rDevice->drawLine( aPt1, aPt2, aCol, DrawMode_PAINT, mpClipMask );

        const basegfx::B2IPoint aPt3(1,5);
        CPPUNIT_ASSERT_MESSAGE("get line pixel",
                               rDevice->getPixel(aPt3) != aBgCol);
        CPPUNIT_ASSERT_MESSAGE("number of rendered line pixel is not 4",
                               countPixel( rDevice,
                                           rDevice->getPixel(aPt3) ) == 4);

        rDevice->drawLine( aPt1, aPt2, aCol, DrawMode_XOR, mpClipMask );
        CPPUNIT_ASSERT_MESSAGE("number of xor-rendered line pixel is not 0",
                               countPixel( rDevice,
                                           rDevice->getPixel(aPt3) ) == 121);
    }

    void implTestFillClip(const BitmapDeviceSharedPtr& rDevice)
    {
        rDevice->clear(Color(0));

        const basegfx::B2DRange aAllOver(-10,-10,20,20);
        const Color aCol(0xFFFFFFFF);
        rDevice->fillPolyPolygon( basegfx::B2DPolyPolygon(
                                      basegfx::tools::createPolygonFromRect(aAllOver)),
                                  aCol,
                                  DrawMode_PAINT,
                                  mpClipMask );
        const basegfx::B2IPoint aPt(0,10);
        CPPUNIT_ASSERT_MESSAGE("number of clipped pixel is not 30",
                               countPixel( rDevice, rDevice->getPixel(aPt) ) == 121-30);

        rDevice->fillPolyPolygon( basegfx::B2DPolyPolygon(
                                      basegfx::tools::createPolygonFromRect(aAllOver)),
                                  aCol,
                                  DrawMode_PAINT );
        CPPUNIT_ASSERT_MESSAGE("number of filled pixel is not 121",
                               countPixel( rDevice, rDevice->getPixel(aPt) ) == 121);

        rDevice->fillPolyPolygon( basegfx::B2DPolyPolygon(
                                      basegfx::tools::createPolygonFromRect(aAllOver)),
                                  aCol,
                                  DrawMode_XOR,
                                  mpClipMask );
        CPPUNIT_ASSERT_MESSAGE("number of xor-cleared pixel is not 91",
                               countPixel( rDevice, rDevice->getPixel(aPt) ) == 121-30);
    }

    void implTestBmpClip(const BitmapDeviceSharedPtr& rDevice)
    {
        BitmapDeviceSharedPtr pBmp( cloneBitmapDevice(
                                        basegfx::B2IVector(3,3),
                                        rDevice ));
        Color aCol1(0);
        Color aCol2(0xFFFFFFFF);
        pBmp->clear(aCol1);
        pBmp->setPixel(basegfx::B2IPoint(0,0),aCol2,DrawMode_PAINT);
        pBmp->setPixel(basegfx::B2IPoint(1,1),aCol2,DrawMode_PAINT);
        pBmp->setPixel(basegfx::B2IPoint(2,2),aCol2,basebmp::DrawMode_PAINT);

        rDevice->clear(aCol1);
        rDevice->drawBitmap(pBmp,
                            basegfx::B2IRange(0,0,3,3),
                            basegfx::B2IRange(-1,-1,4,4),
                            DrawMode_PAINT,
                            mpClipMask);

        const basegfx::B2IPoint aPt(1,1);
        CPPUNIT_ASSERT_MESSAGE("number of clipped pixel is not 5",
                               countPixel( rDevice,
                                           rDevice->getPixel(aPt) ) == 5);
    }

    void implTestMaskColorClip(const BitmapDeviceSharedPtr& rDevice)
    {
        BitmapDeviceSharedPtr pBmp( createBitmapDevice( rDevice->getSize(),
                                                        true,
                                                        Format::EIGHT_BIT_GREY ));

        ::rtl::OUString aSvg = ::rtl::OUString::createFromAscii(
            "m 0 0h5v10h5v-5h-10z" );

        basegfx::B2DPolyPolygon aPoly;
        basegfx::tools::importFromSvgD( aPoly, aSvg );
        const basebmp::Color aCol(0xFF);
        pBmp->clear( basebmp::Color(0) );
        pBmp->fillPolyPolygon(
            aPoly,
            aCol,
            basebmp::DrawMode_PAINT );

        const basegfx::B2IRange aSourceRect(0,0,10,10);
        const basegfx::B2IPoint aDestLeftTop(0,0);
        const Color aCol2(0xF0F0F0F0);
        rDevice->drawMaskedColor(
            aCol2,
            pBmp,
            aSourceRect,
            aDestLeftTop,
            mpClipMask );
        const basegfx::B2IPoint aPt(1,1);
        CPPUNIT_ASSERT_MESSAGE("number of rendered pixel is not 41",
                               countPixel( rDevice, rDevice->getPixel(aPt) ) == 41);

    }

public:
    void setUp()
    {
        const basegfx::B2ISize aSize(11,11);
        mpClipMask = createBitmapDevice( aSize,
                                         true,
                                         Format::ONE_BIT_MSB_GREY );
        mpDevice1bpp = createBitmapDevice( aSize,
                                           true,
                                           Format::ONE_BIT_MSB_PAL );
        mpDevice32bpp = createBitmapDevice( aSize,
                                           true,
                                           Format::THIRTYTWO_BIT_TC_MASK );

        ::rtl::OUString aSvg = ::rtl::OUString::createFromAscii(
            "m 0 0 h5 l5 5 v5 h-5 l-5-5 z" );
        basegfx::B2DPolyPolygon aPoly;
        basegfx::tools::importFromSvgD( aPoly, aSvg );
        mpClipMask->clear(Color(0));
        mpClipMask->drawPolygon(
            aPoly.getB2DPolygon(0),
            Color(0xFFFFFFFF),
            DrawMode_PAINT );
    }

    void testPixelClip()
    {
        implTestPixelClip( mpDevice1bpp );
        implTestPixelClip( mpDevice32bpp );
    }

    void testLineClip()
    {
        implTestLineClip( mpDevice1bpp );
        implTestLineClip( mpDevice32bpp );
    }

    void testFillClip()
    {
        implTestFillClip( mpDevice1bpp );
        implTestFillClip( mpDevice32bpp );
    }

    void testBmpClip()
    {
        implTestBmpClip( mpDevice1bpp );
        implTestBmpClip( mpDevice32bpp );
    }

    void testMaskColorClip()
    {
        implTestMaskColorClip( mpDevice1bpp );
        implTestMaskColorClip( mpDevice32bpp );
    }

    // Change the following lines only, if you add, remove or rename
    // member functions of the current class,
    // because these macros are need by auto register mechanism.

    CPPUNIT_TEST_SUITE(ClipTest);
    CPPUNIT_TEST(testPixelClip);
    CPPUNIT_TEST(testLineClip);
    CPPUNIT_TEST(testFillClip);
    CPPUNIT_TEST(testBmpClip);
    CPPUNIT_TEST(testMaskColorClip);
    CPPUNIT_TEST_SUITE_END();
};

// -----------------------------------------------------------------------------
CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(ClipTest, "ClipTest");
}

// -----------------------------------------------------------------------------

// this macro creates an empty function, which will called by the RegisterAllFunctions()
// to let the user the possibility to also register some functions by hand.
//NOADDITIONAL;

<|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 "base/file_util.h"
#include "base/memory/ref_counted.h"
#include "base/path_service.h"
#include "chrome/browser/download/download_manager.h"
#include "chrome/browser/extensions/extension_error_reporter.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"
#include "content/browser/site_instance.h"
#include "content/browser/tab_contents/tab_contents.h"
#include "content/common/notification_details.h"
#include "content/common/notification_observer.h"
#include "content/common/notification_registrar.h"
#include "content/common/notification_type.h"
#include "net/base/net_util.h"
#include "net/test/test_server.h"

class RenderViewHostManagerTest : public InProcessBrowserTest {
 public:
  RenderViewHostManagerTest() {
    EnableDOMAutomation();
  }

  static bool GetFilePathWithHostAndPortReplacement(
      const std::string& original_file_path,
      const net::HostPortPair& host_port_pair,
      std::string* replacement_path) {
    std::vector<net::TestServer::StringPair> replacement_text;
    replacement_text.push_back(
        make_pair("REPLACE_WITH_HOST_AND_PORT", host_port_pair.ToString()));
    return net::TestServer::GetFilePathWithReplacements(
        original_file_path, replacement_text, replacement_path);
  }
};

// Test for crbug.com/24447.  Following a cross-site link with rel=noreferrer
// and target=_blank should create a new SiteInstance.
IN_PROC_BROWSER_TEST_F(RenderViewHostManagerTest,
                       SwapProcessWithRelNoreferrerAndTargetBlank) {
  // Start two servers with different sites.
  ASSERT_TRUE(test_server()->Start());
  net::TestServer https_server(
      net::TestServer::TYPE_HTTPS,
      FilePath(FILE_PATH_LITERAL("chrome/test/data")));
  ASSERT_TRUE(https_server.Start());

  // Load a page with links that open in a new window.
  std::string replacement_path;
  ASSERT_TRUE(GetFilePathWithHostAndPortReplacement(
      "files/click-noreferrer-links.html",
      https_server.host_port_pair(),
      &replacement_path));
  ui_test_utils::NavigateToURL(browser(),
                               test_server()->GetURL(replacement_path));

  // Get the original SiteInstance for later comparison.
  scoped_refptr<SiteInstance> orig_site_instance(
      browser()->GetSelectedTabContents()->GetSiteInstance());
  EXPECT_TRUE(orig_site_instance != NULL);

  // Test clicking a rel=noreferrer + target=blank link.
  bool success = false;
  EXPECT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractBool(
      browser()->GetSelectedTabContents()->render_view_host(), L"",
      L"window.domAutomationController.send(clickNoRefTargetBlankLink());",
      &success));
  EXPECT_TRUE(success);

  // Wait for the tab to open.
  if (browser()->tab_count() < 2)
    ui_test_utils::WaitForNewTab(browser());

  // Opens in new tab.
  EXPECT_EQ(2, browser()->tab_count());
  EXPECT_EQ(1, browser()->selected_index());
  EXPECT_EQ("/files/title2.html",
            browser()->GetSelectedTabContents()->GetURL().path());

  // Wait for the cross-site transition in the new tab to finish.
  ui_test_utils::WaitForLoadStop(browser()->GetSelectedTabContents());
  EXPECT_FALSE(browser()->GetSelectedTabContents()->render_manager()->
                   pending_render_view_host());

  // Should have a new SiteInstance.
  scoped_refptr<SiteInstance> noref_blank_site_instance(
      browser()->GetSelectedTabContents()->GetSiteInstance());
  EXPECT_NE(orig_site_instance, noref_blank_site_instance);
}

// Test for crbug.com/24447.  Following a cross-site link with just
// target=_blank should not create a new SiteInstance.
IN_PROC_BROWSER_TEST_F(RenderViewHostManagerTest,
                       DontSwapProcessWithOnlyTargetBlank) {
  // Start two servers with different sites.
  ASSERT_TRUE(test_server()->Start());
  net::TestServer https_server(
      net::TestServer::TYPE_HTTPS,
      FilePath(FILE_PATH_LITERAL("chrome/test/data")));
  ASSERT_TRUE(https_server.Start());

  // Load a page with links that open in a new window.
  std::string replacement_path;
  ASSERT_TRUE(GetFilePathWithHostAndPortReplacement(
      "files/click-noreferrer-links.html",
      https_server.host_port_pair(),
      &replacement_path));
  ui_test_utils::NavigateToURL(browser(),
                               test_server()->GetURL(replacement_path));

  // Get the original SiteInstance for later comparison.
  scoped_refptr<SiteInstance> orig_site_instance(
      browser()->GetSelectedTabContents()->GetSiteInstance());
  EXPECT_TRUE(orig_site_instance != NULL);

  // Test clicking a target=blank link.
  bool success = false;
  EXPECT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractBool(
      browser()->GetSelectedTabContents()->render_view_host(), L"",
      L"window.domAutomationController.send(clickTargetBlankLink());",
      &success));
  EXPECT_TRUE(success);

  // Wait for the tab to open.
  if (browser()->tab_count() < 2)
    ui_test_utils::WaitForNewTab(browser());

  // Opens in new tab.
  EXPECT_EQ(2, browser()->tab_count());
  EXPECT_EQ(1, browser()->selected_index());

  // Wait for the cross-site transition in the new tab to finish.
  ui_test_utils::WaitForLoadStop(browser()->GetSelectedTabContents());
  EXPECT_EQ("/files/title2.html",
            browser()->GetSelectedTabContents()->GetURL().path());

  // Should have the same SiteInstance.
  scoped_refptr<SiteInstance> blank_site_instance(
      browser()->GetSelectedTabContents()->GetSiteInstance());
  EXPECT_EQ(orig_site_instance, blank_site_instance);
}

// Test for crbug.com/24447.  Following a cross-site link with rel=noreferrer
// and no target=_blank should not create a new SiteInstance.
IN_PROC_BROWSER_TEST_F(RenderViewHostManagerTest,
                       DontSwapProcessWithOnlyRelNoreferrer) {
  // Start two servers with different sites.
  ASSERT_TRUE(test_server()->Start());
  net::TestServer https_server(
      net::TestServer::TYPE_HTTPS,
      FilePath(FILE_PATH_LITERAL("chrome/test/data")));
  ASSERT_TRUE(https_server.Start());

  // Load a page with links that open in a new window.
  std::string replacement_path;
  ASSERT_TRUE(GetFilePathWithHostAndPortReplacement(
      "files/click-noreferrer-links.html",
      https_server.host_port_pair(),
      &replacement_path));
  ui_test_utils::NavigateToURL(browser(),
                               test_server()->GetURL(replacement_path));

  // Get the original SiteInstance for later comparison.
  scoped_refptr<SiteInstance> orig_site_instance(
      browser()->GetSelectedTabContents()->GetSiteInstance());
  EXPECT_TRUE(orig_site_instance != NULL);

  // Test clicking a rel=noreferrer link.
  bool success = false;
  EXPECT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractBool(
      browser()->GetSelectedTabContents()->render_view_host(), L"",
      L"window.domAutomationController.send(clickNoRefLink());",
      &success));
  EXPECT_TRUE(success);

  // Wait for the cross-site transition in the current tab to finish.
  ui_test_utils::WaitForLoadStop(browser()->GetSelectedTabContents());

  // Opens in same tab.
  EXPECT_EQ(1, browser()->tab_count());
  EXPECT_EQ(0, browser()->selected_index());
  EXPECT_EQ("/files/title2.html",
            browser()->GetSelectedTabContents()->GetURL().path());

  // Should have the same SiteInstance.
  scoped_refptr<SiteInstance> noref_site_instance(
      browser()->GetSelectedTabContents()->GetSiteInstance());
  EXPECT_EQ(orig_site_instance, noref_site_instance);
}

// Test for crbug.com/14505. This tests that chrome:// urls are still functional
// after download of a file while viewing another chrome://.
// Hangs flakily in Win, http://crbug.com/45040, and started hanging on Linux,
// Mac and ChromeOS, http://crbug.com/77762.
IN_PROC_BROWSER_TEST_F(RenderViewHostManagerTest,
                       DISABLED_ChromeURLAfterDownload) {
  GURL downloads_url("chrome://downloads");
  GURL extensions_url("chrome://extensions");
  FilePath zip_download;
  ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &zip_download));
  zip_download = zip_download.AppendASCII("zip").AppendASCII("test.zip");
  GURL zip_url = net::FilePathToFileURL(zip_download);

  ui_test_utils::NavigateToURL(browser(), downloads_url);
  ui_test_utils::NavigateToURL(browser(), zip_url);
  ui_test_utils::WaitForDownloadCount(
      browser()->profile()->GetDownloadManager(), 1);
  ui_test_utils::NavigateToURL(browser(), extensions_url);

  TabContents *contents = browser()->GetSelectedTabContents();
  ASSERT_TRUE(contents);
  bool webui_responded = false;
  EXPECT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractBool(
      contents->render_view_host(),
      L"",
      L"window.domAutomationController.send(window.webui_responded_);",
      &webui_responded));
  EXPECT_TRUE(webui_responded);
}

class BrowserClosedObserver : public NotificationObserver {
 public:
  explicit BrowserClosedObserver(Browser* browser) {
    registrar_.Add(this, NotificationType::BROWSER_CLOSED,
        Source<Browser>(browser));
    ui_test_utils::RunMessageLoop();
  }

  // NotificationObserver
  virtual void Observe(NotificationType type,
                       const NotificationSource& source,
                       const NotificationDetails& details) {
    switch (type.value) {
      case NotificationType::BROWSER_CLOSED:
        MessageLoopForUI::current()->Quit();
        break;
      default:
        NOTREACHED();
        break;
    }
  }

 private:
  NotificationRegistrar registrar_;
};

// Test for crbug.com/12745. This tests that if a download is initiated from
// a chrome:// page that has registered and onunload handler, the browser
// will be able to close.
// TODO(rafaelw): The fix for 12745 has now also been reverted. Another fix
// must be found before this can be re-enabled.
IN_PROC_BROWSER_TEST_F(RenderViewHostManagerTest,
                       DISABLED_BrowserCloseAfterDownload) {
  GURL downloads_url("chrome://downloads");
  FilePath zip_download;
  ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &zip_download));
  zip_download = zip_download.AppendASCII("zip").AppendASCII("test.zip");
  ASSERT_TRUE(file_util::PathExists(zip_download));
  GURL zip_url = net::FilePathToFileURL(zip_download);

  ui_test_utils::NavigateToURL(browser(), downloads_url);
  TabContents *contents = browser()->GetSelectedTabContents();
  ASSERT_TRUE(contents);
  bool result = false;
  EXPECT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractBool(
      contents->render_view_host(),
      L"",
      L"window.onunload = function() { var do_nothing = 0; }; "
      L"window.domAutomationController.send(true);",
      &result));
  EXPECT_TRUE(result);
  ui_test_utils::NavigateToURL(browser(), zip_url);

  ui_test_utils::WaitForDownloadCount(
    browser()->profile()->GetDownloadManager(), 1);

  browser()->CloseWindow();
  BrowserClosedObserver wait_for_close(browser());
}

// Test for crbug.com/76666.  A cross-site navigation that fails with a 204
// error should not make us ignore future renderer-initiated navigations.
IN_PROC_BROWSER_TEST_F(RenderViewHostManagerTest, ClickLinkAfter204Error) {
  // Start two servers with different sites.
  ASSERT_TRUE(test_server()->Start());
  net::TestServer https_server(
      net::TestServer::TYPE_HTTPS,
      FilePath(FILE_PATH_LITERAL("chrome/test/data")));
  ASSERT_TRUE(https_server.Start());

  // Load a page with links that open in a new window.
  // The links will point to the HTTPS server.
  std::string replacement_path;
  ASSERT_TRUE(GetFilePathWithHostAndPortReplacement(
      "files/click-noreferrer-links.html",
      https_server.host_port_pair(),
      &replacement_path));
  ui_test_utils::NavigateToURL(browser(),
                               test_server()->GetURL(replacement_path));

  // Get the original SiteInstance for later comparison.
  scoped_refptr<SiteInstance> orig_site_instance(
      browser()->GetSelectedTabContents()->GetSiteInstance());
  EXPECT_TRUE(orig_site_instance != NULL);

  // Load a cross-site page that fails with a 204 error.
  ui_test_utils::NavigateToURL(browser(), https_server.GetURL("nocontent"));

  // We should still be looking at the normal page.
  scoped_refptr<SiteInstance> post_nav_site_instance(
      browser()->GetSelectedTabContents()->GetSiteInstance());
  EXPECT_EQ(orig_site_instance, post_nav_site_instance);
  EXPECT_EQ("/files/click-noreferrer-links.html",
            browser()->GetSelectedTabContents()->GetURL().path());

  // Renderer-initiated navigations should work.
  bool success = false;
  EXPECT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractBool(
      browser()->GetSelectedTabContents()->render_view_host(), L"",
      L"window.domAutomationController.send(clickNoRefLink());",
      &success));
  EXPECT_TRUE(success);

  // Wait for the cross-site transition in the current tab to finish.
  ui_test_utils::WaitForLoadStop(browser()->GetSelectedTabContents());

  // Opens in same tab.
  EXPECT_EQ(1, browser()->tab_count());
  EXPECT_EQ(0, browser()->selected_index());
  EXPECT_EQ("/files/title2.html",
            browser()->GetSelectedTabContents()->GetURL().path());

  // Should have the same SiteInstance.
  scoped_refptr<SiteInstance> noref_site_instance(
      browser()->GetSelectedTabContents()->GetSiteInstance());
  EXPECT_EQ(orig_site_instance, noref_site_instance);
}
<commit_msg>Add log statements to ChromeURLAfterDownload to see where exactly its timing out. I'll revert this after it builds.<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 "base/file_util.h"
#include "base/memory/ref_counted.h"
#include "base/path_service.h"
#include "chrome/browser/download/download_manager.h"
#include "chrome/browser/extensions/extension_error_reporter.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"
#include "content/browser/site_instance.h"
#include "content/browser/tab_contents/tab_contents.h"
#include "content/common/notification_details.h"
#include "content/common/notification_observer.h"
#include "content/common/notification_registrar.h"
#include "content/common/notification_type.h"
#include "net/base/net_util.h"
#include "net/test/test_server.h"

class RenderViewHostManagerTest : public InProcessBrowserTest {
 public:
  RenderViewHostManagerTest() {
    EnableDOMAutomation();
  }

  static bool GetFilePathWithHostAndPortReplacement(
      const std::string& original_file_path,
      const net::HostPortPair& host_port_pair,
      std::string* replacement_path) {
    std::vector<net::TestServer::StringPair> replacement_text;
    replacement_text.push_back(
        make_pair("REPLACE_WITH_HOST_AND_PORT", host_port_pair.ToString()));
    return net::TestServer::GetFilePathWithReplacements(
        original_file_path, replacement_text, replacement_path);
  }
};

// Test for crbug.com/24447.  Following a cross-site link with rel=noreferrer
// and target=_blank should create a new SiteInstance.
IN_PROC_BROWSER_TEST_F(RenderViewHostManagerTest,
                       SwapProcessWithRelNoreferrerAndTargetBlank) {
  // Start two servers with different sites.
  ASSERT_TRUE(test_server()->Start());
  net::TestServer https_server(
      net::TestServer::TYPE_HTTPS,
      FilePath(FILE_PATH_LITERAL("chrome/test/data")));
  ASSERT_TRUE(https_server.Start());

  // Load a page with links that open in a new window.
  std::string replacement_path;
  ASSERT_TRUE(GetFilePathWithHostAndPortReplacement(
      "files/click-noreferrer-links.html",
      https_server.host_port_pair(),
      &replacement_path));
  ui_test_utils::NavigateToURL(browser(),
                               test_server()->GetURL(replacement_path));

  // Get the original SiteInstance for later comparison.
  scoped_refptr<SiteInstance> orig_site_instance(
      browser()->GetSelectedTabContents()->GetSiteInstance());
  EXPECT_TRUE(orig_site_instance != NULL);

  // Test clicking a rel=noreferrer + target=blank link.
  bool success = false;
  EXPECT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractBool(
      browser()->GetSelectedTabContents()->render_view_host(), L"",
      L"window.domAutomationController.send(clickNoRefTargetBlankLink());",
      &success));
  EXPECT_TRUE(success);

  // Wait for the tab to open.
  if (browser()->tab_count() < 2)
    ui_test_utils::WaitForNewTab(browser());

  // Opens in new tab.
  EXPECT_EQ(2, browser()->tab_count());
  EXPECT_EQ(1, browser()->selected_index());
  EXPECT_EQ("/files/title2.html",
            browser()->GetSelectedTabContents()->GetURL().path());

  // Wait for the cross-site transition in the new tab to finish.
  ui_test_utils::WaitForLoadStop(browser()->GetSelectedTabContents());
  EXPECT_FALSE(browser()->GetSelectedTabContents()->render_manager()->
                   pending_render_view_host());

  // Should have a new SiteInstance.
  scoped_refptr<SiteInstance> noref_blank_site_instance(
      browser()->GetSelectedTabContents()->GetSiteInstance());
  EXPECT_NE(orig_site_instance, noref_blank_site_instance);
}

// Test for crbug.com/24447.  Following a cross-site link with just
// target=_blank should not create a new SiteInstance.
IN_PROC_BROWSER_TEST_F(RenderViewHostManagerTest,
                       DontSwapProcessWithOnlyTargetBlank) {
  // Start two servers with different sites.
  ASSERT_TRUE(test_server()->Start());
  net::TestServer https_server(
      net::TestServer::TYPE_HTTPS,
      FilePath(FILE_PATH_LITERAL("chrome/test/data")));
  ASSERT_TRUE(https_server.Start());

  // Load a page with links that open in a new window.
  std::string replacement_path;
  ASSERT_TRUE(GetFilePathWithHostAndPortReplacement(
      "files/click-noreferrer-links.html",
      https_server.host_port_pair(),
      &replacement_path));
  ui_test_utils::NavigateToURL(browser(),
                               test_server()->GetURL(replacement_path));

  // Get the original SiteInstance for later comparison.
  scoped_refptr<SiteInstance> orig_site_instance(
      browser()->GetSelectedTabContents()->GetSiteInstance());
  EXPECT_TRUE(orig_site_instance != NULL);

  // Test clicking a target=blank link.
  bool success = false;
  EXPECT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractBool(
      browser()->GetSelectedTabContents()->render_view_host(), L"",
      L"window.domAutomationController.send(clickTargetBlankLink());",
      &success));
  EXPECT_TRUE(success);

  // Wait for the tab to open.
  if (browser()->tab_count() < 2)
    ui_test_utils::WaitForNewTab(browser());

  // Opens in new tab.
  EXPECT_EQ(2, browser()->tab_count());
  EXPECT_EQ(1, browser()->selected_index());

  // Wait for the cross-site transition in the new tab to finish.
  ui_test_utils::WaitForLoadStop(browser()->GetSelectedTabContents());
  EXPECT_EQ("/files/title2.html",
            browser()->GetSelectedTabContents()->GetURL().path());

  // Should have the same SiteInstance.
  scoped_refptr<SiteInstance> blank_site_instance(
      browser()->GetSelectedTabContents()->GetSiteInstance());
  EXPECT_EQ(orig_site_instance, blank_site_instance);
}

// Test for crbug.com/24447.  Following a cross-site link with rel=noreferrer
// and no target=_blank should not create a new SiteInstance.
IN_PROC_BROWSER_TEST_F(RenderViewHostManagerTest,
                       DontSwapProcessWithOnlyRelNoreferrer) {
  // Start two servers with different sites.
  ASSERT_TRUE(test_server()->Start());
  net::TestServer https_server(
      net::TestServer::TYPE_HTTPS,
      FilePath(FILE_PATH_LITERAL("chrome/test/data")));
  ASSERT_TRUE(https_server.Start());

  // Load a page with links that open in a new window.
  std::string replacement_path;
  ASSERT_TRUE(GetFilePathWithHostAndPortReplacement(
      "files/click-noreferrer-links.html",
      https_server.host_port_pair(),
      &replacement_path));
  ui_test_utils::NavigateToURL(browser(),
                               test_server()->GetURL(replacement_path));

  // Get the original SiteInstance for later comparison.
  scoped_refptr<SiteInstance> orig_site_instance(
      browser()->GetSelectedTabContents()->GetSiteInstance());
  EXPECT_TRUE(orig_site_instance != NULL);

  // Test clicking a rel=noreferrer link.
  bool success = false;
  EXPECT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractBool(
      browser()->GetSelectedTabContents()->render_view_host(), L"",
      L"window.domAutomationController.send(clickNoRefLink());",
      &success));
  EXPECT_TRUE(success);

  // Wait for the cross-site transition in the current tab to finish.
  ui_test_utils::WaitForLoadStop(browser()->GetSelectedTabContents());

  // Opens in same tab.
  EXPECT_EQ(1, browser()->tab_count());
  EXPECT_EQ(0, browser()->selected_index());
  EXPECT_EQ("/files/title2.html",
            browser()->GetSelectedTabContents()->GetURL().path());

  // Should have the same SiteInstance.
  scoped_refptr<SiteInstance> noref_site_instance(
      browser()->GetSelectedTabContents()->GetSiteInstance());
  EXPECT_EQ(orig_site_instance, noref_site_instance);
}

// Test for crbug.com/14505. This tests that chrome:// urls are still functional
// after download of a file while viewing another chrome://.
IN_PROC_BROWSER_TEST_F(RenderViewHostManagerTest,
                       ChromeURLAfterDownload) {
  GURL downloads_url("chrome://downloads");
  GURL extensions_url("chrome://extensions");
  FilePath zip_download;
  ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &zip_download));
  zip_download = zip_download.AppendASCII("zip").AppendASCII("test.zip");
  GURL zip_url = net::FilePathToFileURL(zip_download);

  LOG(INFO) << "Navigating to chrome URL.";
  ui_test_utils::NavigateToURL(browser(), downloads_url);
  LOG(INFO) << "Navigating to zip URL.";
  ui_test_utils::NavigateToURL(browser(), zip_url);
  LOG(INFO) << "Waiting for the zip download to complete.";
  ui_test_utils::WaitForDownloadCount(
      browser()->profile()->GetDownloadManager(), 1);
  LOG(INFO) << "Download complete. Navigating to the extensions URL.";
  ui_test_utils::NavigateToURL(browser(), extensions_url);

  TabContents *contents = browser()->GetSelectedTabContents();
  ASSERT_TRUE(contents);
  bool webui_responded = false;
  LOG(INFO) << "Executing javascript.";
  EXPECT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractBool(
      contents->render_view_host(),
      L"",
      L"window.domAutomationController.send(window.webui_responded_);",
      &webui_responded));
  LOG(INFO) << "Javascript executed.";
  EXPECT_TRUE(webui_responded);
}

class BrowserClosedObserver : public NotificationObserver {
 public:
  explicit BrowserClosedObserver(Browser* browser) {
    registrar_.Add(this, NotificationType::BROWSER_CLOSED,
        Source<Browser>(browser));
    ui_test_utils::RunMessageLoop();
  }

  // NotificationObserver
  virtual void Observe(NotificationType type,
                       const NotificationSource& source,
                       const NotificationDetails& details) {
    switch (type.value) {
      case NotificationType::BROWSER_CLOSED:
        MessageLoopForUI::current()->Quit();
        break;
      default:
        NOTREACHED();
        break;
    }
  }

 private:
  NotificationRegistrar registrar_;
};

// Test for crbug.com/12745. This tests that if a download is initiated from
// a chrome:// page that has registered and onunload handler, the browser
// will be able to close.
// TODO(rafaelw): The fix for 12745 has now also been reverted. Another fix
// must be found before this can be re-enabled.
IN_PROC_BROWSER_TEST_F(RenderViewHostManagerTest,
                       DISABLED_BrowserCloseAfterDownload) {
  GURL downloads_url("chrome://downloads");
  FilePath zip_download;
  ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &zip_download));
  zip_download = zip_download.AppendASCII("zip").AppendASCII("test.zip");
  ASSERT_TRUE(file_util::PathExists(zip_download));
  GURL zip_url = net::FilePathToFileURL(zip_download);

  ui_test_utils::NavigateToURL(browser(), downloads_url);
  TabContents *contents = browser()->GetSelectedTabContents();
  ASSERT_TRUE(contents);
  bool result = false;
  EXPECT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractBool(
      contents->render_view_host(),
      L"",
      L"window.onunload = function() { var do_nothing = 0; }; "
      L"window.domAutomationController.send(true);",
      &result));
  EXPECT_TRUE(result);
  ui_test_utils::NavigateToURL(browser(), zip_url);

  ui_test_utils::WaitForDownloadCount(
    browser()->profile()->GetDownloadManager(), 1);

  browser()->CloseWindow();
  BrowserClosedObserver wait_for_close(browser());
}

// Test for crbug.com/76666.  A cross-site navigation that fails with a 204
// error should not make us ignore future renderer-initiated navigations.
IN_PROC_BROWSER_TEST_F(RenderViewHostManagerTest, ClickLinkAfter204Error) {
  // Start two servers with different sites.
  ASSERT_TRUE(test_server()->Start());
  net::TestServer https_server(
      net::TestServer::TYPE_HTTPS,
      FilePath(FILE_PATH_LITERAL("chrome/test/data")));
  ASSERT_TRUE(https_server.Start());

  // Load a page with links that open in a new window.
  // The links will point to the HTTPS server.
  std::string replacement_path;
  ASSERT_TRUE(GetFilePathWithHostAndPortReplacement(
      "files/click-noreferrer-links.html",
      https_server.host_port_pair(),
      &replacement_path));
  ui_test_utils::NavigateToURL(browser(),
                               test_server()->GetURL(replacement_path));

  // Get the original SiteInstance for later comparison.
  scoped_refptr<SiteInstance> orig_site_instance(
      browser()->GetSelectedTabContents()->GetSiteInstance());
  EXPECT_TRUE(orig_site_instance != NULL);

  // Load a cross-site page that fails with a 204 error.
  ui_test_utils::NavigateToURL(browser(), https_server.GetURL("nocontent"));

  // We should still be looking at the normal page.
  scoped_refptr<SiteInstance> post_nav_site_instance(
      browser()->GetSelectedTabContents()->GetSiteInstance());
  EXPECT_EQ(orig_site_instance, post_nav_site_instance);
  EXPECT_EQ("/files/click-noreferrer-links.html",
            browser()->GetSelectedTabContents()->GetURL().path());

  // Renderer-initiated navigations should work.
  bool success = false;
  EXPECT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractBool(
      browser()->GetSelectedTabContents()->render_view_host(), L"",
      L"window.domAutomationController.send(clickNoRefLink());",
      &success));
  EXPECT_TRUE(success);

  // Wait for the cross-site transition in the current tab to finish.
  ui_test_utils::WaitForLoadStop(browser()->GetSelectedTabContents());

  // Opens in same tab.
  EXPECT_EQ(1, browser()->tab_count());
  EXPECT_EQ(0, browser()->selected_index());
  EXPECT_EQ("/files/title2.html",
            browser()->GetSelectedTabContents()->GetURL().path());

  // Should have the same SiteInstance.
  scoped_refptr<SiteInstance> noref_site_instance(
      browser()->GetSelectedTabContents()->GetSiteInstance());
  EXPECT_EQ(orig_site_instance, noref_site_instance);
}
<|endoftext|>


<commit_before>/*
   Copyright 2014 Brain Research Institute, Melbourne, Australia

   Written by Robert E. Smith, 2015.

   This file is part of MRtrix.

   MRtrix is free software: you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation, either version 3 of the License, or
   (at your option) any later version.

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

   You should have received a copy of the GNU General Public License
   along with MRtrix.  If not, see <http://www.gnu.org/licenses/>.

*/

#include "gui/mrview/tool/connectome.h"

#include "file/path.h"
#include "gui/dialog/file.h"
#include "image/buffer.h"
#include "image/header.h"
#include "image/loop.h"
#include "image/transform.h"

namespace MR
{
  namespace GUI
  {
    namespace MRView
    {
      namespace Tool
      {

        Connectome::Connectome (Window& main_window, Dock* parent) :
          Base (main_window, parent) {

            VBoxLayout* main_box = new VBoxLayout (this);

            HBoxLayout* layout = new HBoxLayout;
            layout->setContentsMargins (0, 0, 0, 0);
            layout->setSpacing (0);

            image_button = new QPushButton (this);
            image_button->setToolTip (tr ("Open parcellation image"));
            // TODO New icons
            // TODO Have the icons always there, but add the opened file name as text
            //image_button->setIcon (QIcon (":/open.svg"));
            connect (image_button, SIGNAL (clicked()), this, SLOT (image_open_slot ()));
            layout->addWidget (image_button, 1);

            lut_button = new QPushButton (this);
            lut_button->setToolTip (tr ("Open lookup table file"));
            //button->setIcon (QIcon (":/close.svg"));
            lut_button->setEnabled (false);
            connect (lut_button, SIGNAL (clicked()), this, SLOT (lut_open_slot ()));
            layout->addWidget (lut_button, 1);

            config_button = new QPushButton (this);
            config_button->setToolTip (tr ("Open connectome config file"));
            //config_button->setIcon (QIcon (":/close.svg"));
            config_button->setEnabled (false);
            connect (config_button, SIGNAL (clicked()), this, SLOT (config_open_slot ()));
            layout->addWidget (config_button, 1);

            hide_all_button = new QPushButton (this);
            hide_all_button->setToolTip (tr ("Hide all connectome visualisation"));
            hide_all_button->setIcon (QIcon (":/hide.svg"));
            hide_all_button->setCheckable (true);
            connect (hide_all_button, SIGNAL (clicked()), this, SLOT (hide_all_slot ()));
            layout->addWidget (hide_all_button, 1);

            main_box->addLayout (layout, 0);

            main_box->addStretch ();
            setMinimumSize (main_box->minimumSize());
        }

        Connectome::~Connectome () {}

        //void Connectome::draw (const Projection& transform, bool is_3D, int axis, int slice)
        void Connectome::draw (const Projection&, bool, int, int)
        {

        }

        //void Connectome::drawOverlays (const Projection& transform)
        void Connectome::drawOverlays (const Projection&)
        {
          if (hide_all_button->isChecked()) return;

        }

        //bool Connectome::process_batch_command (const std::string& cmd, const std::string& args)
        bool Connectome::process_batch_command (const std::string&, const std::string&)
        {
          return false;
        }

        void Connectome::image_open_slot()
        {
          const std::string path = Dialog::File::get_image (this, "Select connectome parcellation image");

          if (path.empty())
            return;

          // TODO If a new parcellation image is opened, all other data should be invalidated
          clear_all();

          // TODO Read in the image file, do the necessary conversions e.g. to mesh,
          //   store the number of nodes,
          initialise (path);

          image_button->setText (QString::fromStdString (Path::basename (path)));
        }

        void Connectome::lut_open_slot()
        {
          // TODO This may be difficult; don't necessarily know the format of the lookup table
          // Ideally also want to make use of the existing functions for importing these
        }
        void Connectome::config_open_slot()
        {

        }

        void Connectome::hide_all_slot()
        {
          window.updateGL();
        }

        Connectome::Node_mesh::Node_mesh (const Mesh::Mesh& in) :
            count (in.triangles.size()),
            vertex_buffer (0),
            vertex_array_object (0),
            index_buffer (0)
        {
          std::vector<float> vertices;
          vertices.reserve (3 * in.num_vertices());
          for (size_t v = 0; v != in.num_vertices(); ++v) {
            for (size_t axis = 0; axis != 3; ++axis)
              vertices.push_back (in.vert(v)[axis]);
          }
          gl::GenBuffers (1, &vertex_buffer);
          gl::BindBuffer (GL_ARRAY_BUFFER, vertex_buffer);
          gl::BufferData (GL_ARRAY_BUFFER, vertices.size() * sizeof (float), &vertices[0], GL_STATIC_DRAW);

          gl::GenVertexArrays (1, &vertex_array_object);
          gl::BindVertexArray (vertex_array_object);
          gl::EnableVertexAttribArray (0);
          gl::VertexAttribPointer (0, 3, gl::FLOAT, gl::FALSE_, 0, (void*)(0));

          std::vector<unsigned int> indices;
          indices.reserve (3 * in.num_triangles());
          for (size_t i = 0; i != in.num_vertices(); ++i) {
            for (size_t v = 0; v != 3; ++v)
              indices.push_back (in.tri(i)[v]);
          }
          gl::GenBuffers (1, &index_buffer);
          gl::BindBuffer (GL_ELEMENT_ARRAY_BUFFER, index_buffer);
          gl::BufferData (GL_ELEMENT_ARRAY_BUFFER, indices.size() * sizeof (unsigned int), &indices[0], GL_STATIC_DRAW);
        }

        Connectome::Node_mesh::~Node_mesh ()
        {
          gl::DeleteBuffers (1, &vertex_buffer);
          gl::DeleteVertexArrays (1, &vertex_array_object);
          gl::DeleteBuffers (1, &index_buffer);
        }

        void Connectome::Node_mesh::render()
        {
          gl::BindVertexArray (vertex_array_object);
          gl::BindBuffer (index_buffer);
          gl::DrawElements (gl::TRIANGLES, count, GL_UNSIGNED_INT, (void*)0);
        }

        void Connectome::clear_all()
        {
          image_button ->setText ("");
          lut_button   ->setText ("");
          config_button->setText ("");
          num_nodes = 0;
          lookup.clear();
          node_map.clear();
        }

        void Connectome::initialise (const std::string& path)
        {
          MR::Image::Header H (path);
          if (!H.datatype().is_integer())
            throw Exception ("Input parcellation image must have an integer datatype");
          MR::Image::Buffer<node_t> buffer (path);
          auto voxel = buffer.voxel();
          MR::Image::Transform transform (H);
          std::vector<size_t> node_volumes;
          MR::Image::LoopInOrder loop (voxel, "Importing parcellation image... ");
          for (loop.start (voxel); loop.ok(); loop.next (voxel)) {
            const node_t node = voxel.value();
            if (node) {
              if (node >= num_nodes) {
                num_nodes = node;
                centres_of_mass.resize (num_nodes+1, Point<float> (0.0f, 0.0f, 0.0f));
                node_volumes.resize (num_nodes+1, 0);
              }
              centres_of_mass[node] += transform.voxel2scanner (voxel);
              node_volumes[node]++;
            }
          }
          for (node_t n = 1; n != num_nodes; ++n)
            centres_of_mass[n] *= (1.0f / float(node_volumes[n]));
        }

      }
    }
  }
}

<commit_msg>mrview connectome tool: Fix compilation<commit_after>/*
   Copyright 2014 Brain Research Institute, Melbourne, Australia

   Written by Robert E. Smith, 2015.

   This file is part of MRtrix.

   MRtrix is free software: you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation, either version 3 of the License, or
   (at your option) any later version.

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

   You should have received a copy of the GNU General Public License
   along with MRtrix.  If not, see <http://www.gnu.org/licenses/>.

*/

#include "gui/mrview/tool/connectome.h"

#include "file/path.h"
#include "gui/dialog/file.h"
#include "image/buffer.h"
#include "image/header.h"
#include "image/loop.h"
#include "image/transform.h"

namespace MR
{
  namespace GUI
  {
    namespace MRView
    {
      namespace Tool
      {

        Connectome::Connectome (Window& main_window, Dock* parent) :
          Base (main_window, parent) {

            VBoxLayout* main_box = new VBoxLayout (this);

            HBoxLayout* layout = new HBoxLayout;
            layout->setContentsMargins (0, 0, 0, 0);
            layout->setSpacing (0);

            image_button = new QPushButton (this);
            image_button->setToolTip (tr ("Open parcellation image"));
            // TODO New icons
            // TODO Have the icons always there, but add the opened file name as text
            //image_button->setIcon (QIcon (":/open.svg"));
            connect (image_button, SIGNAL (clicked()), this, SLOT (image_open_slot ()));
            layout->addWidget (image_button, 1);

            lut_button = new QPushButton (this);
            lut_button->setToolTip (tr ("Open lookup table file"));
            //button->setIcon (QIcon (":/close.svg"));
            lut_button->setEnabled (false);
            connect (lut_button, SIGNAL (clicked()), this, SLOT (lut_open_slot ()));
            layout->addWidget (lut_button, 1);

            config_button = new QPushButton (this);
            config_button->setToolTip (tr ("Open connectome config file"));
            //config_button->setIcon (QIcon (":/close.svg"));
            config_button->setEnabled (false);
            connect (config_button, SIGNAL (clicked()), this, SLOT (config_open_slot ()));
            layout->addWidget (config_button, 1);

            hide_all_button = new QPushButton (this);
            hide_all_button->setToolTip (tr ("Hide all connectome visualisation"));
            hide_all_button->setIcon (QIcon (":/hide.svg"));
            hide_all_button->setCheckable (true);
            connect (hide_all_button, SIGNAL (clicked()), this, SLOT (hide_all_slot ()));
            layout->addWidget (hide_all_button, 1);

            main_box->addLayout (layout, 0);

            main_box->addStretch ();
            setMinimumSize (main_box->minimumSize());
        }

        Connectome::~Connectome () {}

        //void Connectome::draw (const Projection& transform, bool is_3D, int axis, int slice)
        void Connectome::draw (const Projection&, bool, int, int)
        {

        }

        //void Connectome::drawOverlays (const Projection& transform)
        void Connectome::drawOverlays (const Projection&)
        {
          if (hide_all_button->isChecked()) return;

        }

        //bool Connectome::process_batch_command (const std::string& cmd, const std::string& args)
        bool Connectome::process_batch_command (const std::string&, const std::string&)
        {
          return false;
        }

        void Connectome::image_open_slot()
        {
          const std::string path = Dialog::File::get_image (this, "Select connectome parcellation image");

          if (path.empty())
            return;

          // TODO If a new parcellation image is opened, all other data should be invalidated
          clear_all();

          // TODO Read in the image file, do the necessary conversions e.g. to mesh,
          //   store the number of nodes,
          initialise (path);

          image_button->setText (QString::fromStdString (Path::basename (path)));
        }

        void Connectome::lut_open_slot()
        {
          // TODO This may be difficult; don't necessarily know the format of the lookup table
          // Ideally also want to make use of the existing functions for importing these
        }
        void Connectome::config_open_slot()
        {

        }

        void Connectome::hide_all_slot()
        {
          window.updateGL();
        }

        Connectome::Node_mesh::Node_mesh (const Mesh::Mesh& in) :
            count (in.num_triangles()),
            vertex_buffer (0),
            vertex_array_object (0),
            index_buffer (0)
        {
          std::vector<float> vertices;
          vertices.reserve (3 * in.num_vertices());
          for (size_t v = 0; v != in.num_vertices(); ++v) {
            for (size_t axis = 0; axis != 3; ++axis)
              vertices.push_back (in.vert(v)[axis]);
          }
          gl::GenBuffers (1, &vertex_buffer);
          gl::BindBuffer (GL_ARRAY_BUFFER, vertex_buffer);
          gl::BufferData (GL_ARRAY_BUFFER, vertices.size() * sizeof (float), &vertices[0], GL_STATIC_DRAW);

          gl::GenVertexArrays (1, &vertex_array_object);
          gl::BindVertexArray (vertex_array_object);
          gl::EnableVertexAttribArray (0);
          gl::VertexAttribPointer (0, 3, gl::FLOAT, gl::FALSE_, 0, (void*)(0));

          std::vector<unsigned int> indices;
          indices.reserve (3 * in.num_triangles());
          for (size_t i = 0; i != in.num_vertices(); ++i) {
            for (size_t v = 0; v != 3; ++v)
              indices.push_back (in.tri(i)[v]);
          }
          gl::GenBuffers (1, &index_buffer);
          gl::BindBuffer (GL_ELEMENT_ARRAY_BUFFER, index_buffer);
          gl::BufferData (GL_ELEMENT_ARRAY_BUFFER, indices.size() * sizeof (unsigned int), &indices[0], GL_STATIC_DRAW);
        }

        Connectome::Node_mesh::~Node_mesh ()
        {
          gl::DeleteBuffers (1, &vertex_buffer);
          gl::DeleteVertexArrays (1, &vertex_array_object);
          gl::DeleteBuffers (1, &index_buffer);
        }

        void Connectome::Node_mesh::render()
        {
          gl::BindVertexArray (vertex_array_object);
          gl::BindBuffer (GL_ELEMENT_ARRAY_BUFFER, index_buffer);
          gl::DrawElements (gl::TRIANGLES, count, GL_UNSIGNED_INT, (void*)0);
        }

        void Connectome::clear_all()
        {
          image_button ->setText ("");
          lut_button   ->setText ("");
          config_button->setText ("");
          num_nodes = 0;
          lookup.clear();
          node_map.clear();
        }

        void Connectome::initialise (const std::string& path)
        {
          MR::Image::Header H (path);
          if (!H.datatype().is_integer())
            throw Exception ("Input parcellation image must have an integer datatype");
          MR::Image::Buffer<node_t> buffer (path);
          auto voxel = buffer.voxel();
          MR::Image::Transform transform (H);
          std::vector<size_t> node_volumes;
          MR::Image::LoopInOrder loop (voxel, "Importing parcellation image... ");
          for (loop.start (voxel); loop.ok(); loop.next (voxel)) {
            const node_t node = voxel.value();
            if (node) {
              if (node >= num_nodes) {
                num_nodes = node;
                centres_of_mass.resize (num_nodes+1, Point<float> (0.0f, 0.0f, 0.0f));
                node_volumes.resize (num_nodes+1, 0);
              }
              centres_of_mass[node] += transform.voxel2scanner (voxel);
              node_volumes[node]++;
            }
          }
          for (node_t n = 1; n != num_nodes; ++n)
            centres_of_mass[n] *= (1.0f / float(node_volumes[n]));
        }

      }
    }
  }
}

<|endoftext|>


<commit_before>#include "sl_evaluator_training_set.h"

#include <algorithm>
#include <vector>
#include <thread>
#include <mutex>

#include "sl_evaluator.h"

namespace penciloid
{
namespace slitherlink
{
std::vector<double> EvaluatorTrainingSet::ComputeDifficultyAll(EvaluatorParameter param, int n_threads)
{
	std::vector<std::pair<Problem*, int> > entries;
	std::vector<double> score_result;

	for (int i = 0; i < problem_set_.size(); ++i) {
		score_result.push_back(-1.0);
		if (evaluability_[i] != kUnevaluable) {
			printf("%d ", i);
			entries.push_back({ &(problem_set_[i]), i });
		}
	}
	puts("");

	std::sort(entries.begin(), entries.end(), [](const std::pair<Problem*, int> &e1, const std::pair<Problem*, int> &e2) {
		int size_e1 = static_cast<int>(e1.first->height()) * static_cast<int>(e1.first->width());
		int size_e2 = static_cast<int>(e2.first->height()) * static_cast<int>(e2.first->width());
		return size_e1 > size_e2;
	});

	std::mutex mtx; int index = 0;
	auto worker = [&param, &entries, &mtx, &index, &score_result]() {
		for (;;) {
			mtx.lock();
			int current_index = index++;
			mtx.unlock();
			if (current_index >= entries.size()) break;

			Evaluator e(*(entries[current_index].first));
			e.SetParameter(param);
			double score = e.Evaluate();

			mtx.lock();
			score_result[entries[current_index].second] = score;
			mtx.unlock();
		}
	};

	std::vector<std::thread> workers(n_threads);
	for (int i = 0; i < n_threads; ++i) {
		workers[i] = std::thread(worker);
	}
	for (int i = 0; i < n_threads; ++i) workers[i].join();

	for (int i = 0; i < problem_set_.size(); ++i) {
		if (score_result[i] < 0) evaluability_[i] = kUnevaluable;
		else evaluability_[i] = kEvaluable;
	}
	return score_result;
}
}
}<commit_msg>Slitherlink: remove unnecessary outputs<commit_after>#include "sl_evaluator_training_set.h"

#include <algorithm>
#include <vector>
#include <thread>
#include <mutex>

#include "sl_evaluator.h"

namespace penciloid
{
namespace slitherlink
{
std::vector<double> EvaluatorTrainingSet::ComputeDifficultyAll(EvaluatorParameter param, int n_threads)
{
	std::vector<std::pair<Problem*, int> > entries;
	std::vector<double> score_result;

	for (int i = 0; i < problem_set_.size(); ++i) {
		score_result.push_back(-1.0);
		if (evaluability_[i] != kUnevaluable) {
			entries.push_back({ &(problem_set_[i]), i });
		}
	}

	std::sort(entries.begin(), entries.end(), [](const std::pair<Problem*, int> &e1, const std::pair<Problem*, int> &e2) {
		int size_e1 = static_cast<int>(e1.first->height()) * static_cast<int>(e1.first->width());
		int size_e2 = static_cast<int>(e2.first->height()) * static_cast<int>(e2.first->width());
		return size_e1 > size_e2;
	});

	std::mutex mtx; int index = 0;
	auto worker = [&param, &entries, &mtx, &index, &score_result]() {
		for (;;) {
			mtx.lock();
			int current_index = index++;
			mtx.unlock();
			if (current_index >= entries.size()) break;

			Evaluator e(*(entries[current_index].first));
			e.SetParameter(param);
			double score = e.Evaluate();

			mtx.lock();
			score_result[entries[current_index].second] = score;
			mtx.unlock();
		}
	};

	std::vector<std::thread> workers(n_threads);
	for (int i = 0; i < n_threads; ++i) {
		workers[i] = std::thread(worker);
	}
	for (int i = 0; i < n_threads; ++i) workers[i].join();

	for (int i = 0; i < problem_set_.size(); ++i) {
		if (score_result[i] < 0) evaluability_[i] = kUnevaluable;
		else evaluability_[i] = kEvaluable;
	}
	return score_result;
}
}
}<|endoftext|>


<commit_before>/*++
Copyright (c) 2012 Microsoft Corporation

Module Name:

    smt_strategic_solver.h

Abstract:

    Create a strategic solver with tactic for all main logics
    used in SMT.

Author:

    Leonardo (leonardo) 2012-02-19

Notes:

--*/
#include"cmd_context.h"
#include"ni_solver.h"
#include"strategic_solver.h"
#include"qfbv_tactic.h"
#include"qflia_tactic.h"
#include"qfnia_tactic.h"
#include"qfnra_tactic.h"
#include"qfuf_tactic.h"
#include"qflra_tactic.h"
#include"quant_tactics.h"
#include"qfauflia_tactic.h"
#include"qfaufbv_tactic.h"
#include"qfufbv_tactic.h"
#include"qfidl_tactic.h"
#include"default_tactic.h"
#include"ufbv_tactic.h"
#include"qffpa_tactic.h"
#include"default_solver.h"

MK_SIMPLE_TACTIC_FACTORY(qfuf_fct, mk_qfuf_tactic(m, p));
MK_SIMPLE_TACTIC_FACTORY(qfidl_fct, mk_qfidl_tactic(m, p));
MK_SIMPLE_TACTIC_FACTORY(qfauflia_fct, mk_qfauflia_tactic(m, p));
MK_SIMPLE_TACTIC_FACTORY(auflia_fct, mk_auflia_tactic(m, p));
MK_SIMPLE_TACTIC_FACTORY(auflira_fct, mk_auflira_tactic(m, p));
MK_SIMPLE_TACTIC_FACTORY(aufnira_fct, mk_aufnira_tactic(m, p));
MK_SIMPLE_TACTIC_FACTORY(ufnia_fct, mk_ufnia_tactic(m, p));
MK_SIMPLE_TACTIC_FACTORY(uflra_fct, mk_uflra_tactic(m, p));
MK_SIMPLE_TACTIC_FACTORY(lra_fct, mk_lra_tactic(m, p));
MK_SIMPLE_TACTIC_FACTORY(qfbv_fct, mk_qfbv_tactic(m, p));
MK_SIMPLE_TACTIC_FACTORY(default_fct, mk_default_tactic(m, p));
MK_SIMPLE_TACTIC_FACTORY(qfaufbv_fct, mk_qfaufbv_tactic(m, p));
MK_SIMPLE_TACTIC_FACTORY(qflra_fct, mk_qflra_tactic(m, p));
MK_SIMPLE_TACTIC_FACTORY(qflia_fct, mk_qflia_tactic(m, p));
MK_SIMPLE_TACTIC_FACTORY(qfufbv_fct, mk_qfufbv_tactic(m, p));
MK_SIMPLE_TACTIC_FACTORY(qfnia_fct, mk_qfnia_tactic(m, p));
MK_SIMPLE_TACTIC_FACTORY(qfnra_fct, mk_qfnra_tactic(m, p));
MK_SIMPLE_TACTIC_FACTORY(qffpa_fct, mk_qffpa_tactic(m, p));
MK_SIMPLE_TACTIC_FACTORY(ufbv_fct, mk_ufbv_tactic(m, p));

static void init(strategic_solver * s) {
    s->set_default_tactic(alloc(default_fct));
    s->set_tactic_for(symbol("QF_UF"),     alloc(qfuf_fct));
    s->set_tactic_for(symbol("QF_BV"),     alloc(qfbv_fct));
    s->set_tactic_for(symbol("QF_IDL"),    alloc(qfidl_fct));
    s->set_tactic_for(symbol("QF_LIA"),    alloc(qflia_fct));
    s->set_tactic_for(symbol("QF_LRA"),    alloc(qflra_fct));
    s->set_tactic_for(symbol("QF_NIA"),    alloc(qfnia_fct));
    s->set_tactic_for(symbol("QF_NRA"),    alloc(qfnra_fct));
    s->set_tactic_for(symbol("QF_AUFLIA"), alloc(qfauflia_fct));
    s->set_tactic_for(symbol("QF_AUFBV"),  alloc(qfaufbv_fct));
    s->set_tactic_for(symbol("QF_ABV"),    alloc(qfaufbv_fct));
    s->set_tactic_for(symbol("QF_UFBV"),   alloc(qfufbv_fct));
    s->set_tactic_for(symbol("AUFLIA"),    alloc(auflia_fct));
    s->set_tactic_for(symbol("AUFLIRA"),   alloc(auflira_fct));
    s->set_tactic_for(symbol("AUFNIRA"),   alloc(aufnira_fct));
    s->set_tactic_for(symbol("UFNIA"),     alloc(ufnia_fct));
    s->set_tactic_for(symbol("UFLRA"),     alloc(uflra_fct));
    s->set_tactic_for(symbol("LRA"),       alloc(lra_fct));
    s->set_tactic_for(symbol("UFBV"),      alloc(ufbv_fct));
    s->set_tactic_for(symbol("BV"),        alloc(ufbv_fct));
	s->set_tactic_for(symbol("QF_FPA"),    alloc(qffpa_fct));
}

solver * mk_smt_strategic_solver(cmd_context & ctx) {
    strategic_solver * s = alloc(strategic_solver_cmd, ctx);
    s->set_inc_solver(mk_quasi_incremental_smt_solver(ctx));
    init(s);
    return s;
}

solver * mk_smt_strategic_solver(bool force_tactic) {
    strategic_solver * s = alloc(strategic_solver_api);
    s->force_tactic(force_tactic);
    s->set_inc_solver(mk_default_solver());
    init(s);
    return s;
}
<commit_msg>n/a<commit_after>/*++
Copyright (c) 2012 Microsoft Corporation

Module Name:

    smt_strategic_solver.h

Abstract:

    Create a strategic solver with tactic for all main logics
    used in SMT.

Author:

    Leonardo (leonardo) 2012-02-19

Notes:

--*/
#include"cmd_context.h"
#include"ni_solver.h"
#include"strategic_solver.h"
#include"qfbv_tactic.h"
#include"qflia_tactic.h"
#include"qfnia_tactic.h"
#include"qfnra_tactic.h"
#include"qfuf_tactic.h"
#include"qflra_tactic.h"
#include"quant_tactics.h"
#include"qfauflia_tactic.h"
#include"qfaufbv_tactic.h"
#include"qfufbv_tactic.h"
#include"qfidl_tactic.h"
#include"default_tactic.h"
#include"ufbv_tactic.h"
#include"qffpa_tactic.h"
#include"default_solver.h"

MK_SIMPLE_TACTIC_FACTORY(qfuf_fct, mk_qfuf_tactic(m, p));
MK_SIMPLE_TACTIC_FACTORY(qfidl_fct, mk_qfidl_tactic(m, p));
MK_SIMPLE_TACTIC_FACTORY(qfauflia_fct, mk_qfauflia_tactic(m, p));
MK_SIMPLE_TACTIC_FACTORY(auflia_fct, mk_auflia_tactic(m, p));
MK_SIMPLE_TACTIC_FACTORY(auflira_fct, mk_auflira_tactic(m, p));
MK_SIMPLE_TACTIC_FACTORY(aufnira_fct, mk_aufnira_tactic(m, p));
MK_SIMPLE_TACTIC_FACTORY(ufnia_fct, mk_ufnia_tactic(m, p));
MK_SIMPLE_TACTIC_FACTORY(uflra_fct, mk_uflra_tactic(m, p));
MK_SIMPLE_TACTIC_FACTORY(lra_fct, mk_lra_tactic(m, p));
MK_SIMPLE_TACTIC_FACTORY(qfbv_fct, mk_qfbv_tactic(m, p));
MK_SIMPLE_TACTIC_FACTORY(default_fct, mk_default_tactic(m, p));
MK_SIMPLE_TACTIC_FACTORY(qfaufbv_fct, mk_qfaufbv_tactic(m, p));
MK_SIMPLE_TACTIC_FACTORY(qflra_fct, mk_qflra_tactic(m, p));
MK_SIMPLE_TACTIC_FACTORY(qflia_fct, mk_qflia_tactic(m, p));
MK_SIMPLE_TACTIC_FACTORY(qfufbv_fct, mk_qfufbv_tactic(m, p));
MK_SIMPLE_TACTIC_FACTORY(qfnia_fct, mk_qfnia_tactic(m, p));
MK_SIMPLE_TACTIC_FACTORY(qfnra_fct, mk_qfnra_tactic(m, p));
MK_SIMPLE_TACTIC_FACTORY(qffpa_fct, mk_qffpa_tactic(m, p));
MK_SIMPLE_TACTIC_FACTORY(ufbv_fct, mk_ufbv_tactic(m, p));

static void init(strategic_solver * s) {
    s->set_default_tactic(alloc(default_fct));
    s->set_tactic_for(symbol("QF_UF"),     alloc(qfuf_fct));
    s->set_tactic_for(symbol("QF_BV"),     alloc(qfbv_fct));
    s->set_tactic_for(symbol("QF_IDL"),    alloc(qfidl_fct));
    s->set_tactic_for(symbol("QF_LIA"),    alloc(qflia_fct));
    s->set_tactic_for(symbol("QF_LRA"),    alloc(qflra_fct));
    s->set_tactic_for(symbol("QF_NIA"),    alloc(qfnia_fct));
    s->set_tactic_for(symbol("QF_NRA"),    alloc(qfnra_fct));
    s->set_tactic_for(symbol("QF_AUFLIA"), alloc(qfauflia_fct));
    s->set_tactic_for(symbol("QF_AUFBV"),  alloc(qfaufbv_fct));
    s->set_tactic_for(symbol("QF_ABV"),    alloc(qfaufbv_fct));
    s->set_tactic_for(symbol("QF_UFBV"),   alloc(qfufbv_fct));
    s->set_tactic_for(symbol("AUFLIA"),    alloc(auflia_fct));
    s->set_tactic_for(symbol("AUFLIRA"),   alloc(auflira_fct));
    s->set_tactic_for(symbol("AUFNIRA"),   alloc(aufnira_fct));
    s->set_tactic_for(symbol("UFNIA"),     alloc(ufnia_fct));
    s->set_tactic_for(symbol("UFLRA"),     alloc(uflra_fct));
    s->set_tactic_for(symbol("LRA"),       alloc(lra_fct));
    s->set_tactic_for(symbol("UFBV"),      alloc(ufbv_fct));
    s->set_tactic_for(symbol("BV"),        alloc(ufbv_fct));
    s->set_tactic_for(symbol("QF_FPA"),    alloc(qffpa_fct));
}

solver * mk_smt_strategic_solver(cmd_context & ctx) {
    strategic_solver * s = alloc(strategic_solver_cmd, ctx);
    s->set_inc_solver(mk_quasi_incremental_smt_solver(ctx));
    init(s);
    return s;
}

solver * mk_smt_strategic_solver(bool force_tactic) {
    strategic_solver * s = alloc(strategic_solver_api);
    s->force_tactic(force_tactic);
    s->set_inc_solver(mk_default_solver());
    init(s);
    return s;
}
<|endoftext|>


<commit_before>
#include "swganh/connection/connection_service.h"

#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/lexical_cast.hpp>
#include <glog/logging.h>

#include "anh/crc.h"
#include "anh/event_dispatcher/basic_event.h"
#include "anh/event_dispatcher/event_dispatcher_interface.h"
#include "anh/network/soe/packet.h"
#include "anh/network/soe/server.h"
#include "anh/plugin/plugin_manager.h"
#include "anh/service/service_directory_interface.h"
#include "anh/service/service_manager.h"

#include "swganh/app/swganh_kernel.h"

#include "swganh/connection/ping_server.h"
#include "swganh/connection/connection_client.h"
#include "swganh/connection/providers/mysql_session_provider.h"

#include "swganh/object/object.h"
#include "swganh/object/player/player.h"

#include "swganh/messages/logout_message.h"

using namespace anh::app;
using namespace anh::event_dispatcher;
using namespace anh::network;
using namespace anh::service;
using namespace swganh::base;
using namespace swganh::character;
using namespace swganh::connection;
using namespace swganh::login;
using namespace swganh::messages;
using namespace swganh::simulation;

using namespace std;

using boost::asio::ip::udp;

ConnectionService::ConnectionService(
        string listen_address,
        uint16_t listen_port,
        uint16_t ping_port,
        KernelInterface* kernel)
    : BaseService(kernel)
#pragma warning(push)
#pragma warning(disable: 4355)
    , SwgMessageRouter([=] (const boost::asio::ip::udp::endpoint& endpoint) {
        return GetClientFromEndpoint(endpoint);
      })
#pragma warning(pop)
    , ping_server_(nullptr)
    , listen_address_(listen_address)
    , listen_port_(listen_port)
    , soe_server_(nullptr)
{
    soe_server_.reset(new soe::Server(
        kernel->GetIoService(),
        bind(&ConnectionService::RouteMessage, this, placeholders::_1)));
    soe_server_->event_dispatcher(kernel->GetEventDispatcher());

    session_provider_ = kernel->GetPluginManager()->CreateObject<providers::SessionProviderInterface>("ConnectionService::SessionProvider");
    if (!session_provider_)
    {
        session_provider_ = make_shared<providers::MysqlSessionProvider>(kernel->GetDatabaseManager());
    }
}

ServiceDescription ConnectionService::GetServiceDescription() {
    ServiceDescription service_description(
        "ANH Connection Service",
        "connection",
        "0.1",
        listen_address(),
        0,
        listen_port(),
        ping_port_);

    return service_description;
}

void ConnectionService::subscribe() {
    auto event_dispatcher = kernel()->GetEventDispatcher();

    RegisterMessageHandler<ClientIdMsg>(
        bind(&ConnectionService::HandleClientIdMsg_, this, placeholders::_1, placeholders::_2), false);

    RegisterMessageHandler<CmdSceneReady>(
        bind(&ConnectionService::HandleCmdSceneReady_, this, placeholders::_1, placeholders::_2));

    event_dispatcher->subscribe("NetworkSessionRemoved", [this] (shared_ptr<EventInterface> incoming_event) -> bool {
        auto session_removed = std::static_pointer_cast<anh::event_dispatcher::BasicEvent<anh::network::soe::SessionData>>(incoming_event);

        // Message was triggered from our server so process it.
        if (session_removed->session->server() == server().get()) {
            RemoveClient_(session_removed->session);
        }

        return true;
    });
}

void ConnectionService::onStart() {
    ping_server_ = make_shared<PingServer>(kernel()->GetIoService(), ping_port_);
    soe_server_->Start(listen_port_);

    character_service_ = std::static_pointer_cast<CharacterService>(kernel()->GetServiceManager()->GetService("CharacterService"));
    login_service_ = std::static_pointer_cast<swganh::login::LoginService>(kernel()->GetServiceManager()->GetService("LoginService"));
    simulation_service_ = std::static_pointer_cast<swganh::simulation::SimulationService>(kernel()->GetServiceManager()->GetService("SimulationService"));
}

void ConnectionService::onStop() {
    soe_server_->Shutdown();
    clients_.clear();
}

const string& ConnectionService::listen_address() {
    return listen_address_;
}

uint16_t ConnectionService::listen_port() {
    return listen_port_;
}

ConnectionService::ClientMap& ConnectionService::clients() {
    return clients_;
}

std::unique_ptr<anh::network::soe::Server>& ConnectionService::server() {
    return soe_server_;
}

shared_ptr<CharacterService> ConnectionService::character_service() {
    return character_service_.lock();
}

shared_ptr<LoginService> ConnectionService::login_service() {
    return login_service_.lock();
}

shared_ptr<ConnectionClient> ConnectionService::GetClientFromEndpoint(
        const udp::endpoint& remote_endpoint)
{
    shared_ptr<ConnectionClient> client = nullptr;

    ClientMap::accessor a;

    if (clients_.find(a, remote_endpoint)) {
        client = a->second;
    }

    return client;
}

void ConnectionService::AddClient_(
    uint64_t player_id,
    std::shared_ptr<ConnectionClient> client)
{
    ClientMap& client_map = clients();

    auto find_it = std::find_if(
        client_map.begin(),
        client_map.end(),
        [client, player_id] (ClientMap::value_type& conn_client)
    {
        return conn_client.second->GetPlayerId() == player_id;
    });

    if (find_it != client_map.end()) {
        LogoutMessage message;
        (*find_it).second->Send(message);

        client_map.erase(find_it->first);
    }

    DLOG(WARNING) << "Adding connection client";

    ClientMap::accessor a;
    client_map.insert(a, client->GetSession()->remote_endpoint());
    a->second = client;

    DLOG(WARNING) << "Connection service currently has ("<< client_map.size() << ") clients";
}

void ConnectionService::RemoveClient_(std::shared_ptr<anh::network::soe::Session> session) {
    auto client = GetClientFromEndpoint(session->remote_endpoint());

    auto client_map = clients();

    if (client) {

        auto controller = client->GetController();
        if (controller)
        {
			// player is always + 1 from the creature
			auto simulation_service = simulation_service_.lock();
			auto player = simulation_service->LoadObjectById<swganh::object::player::Player>(controller->GetObject()->GetObjectId() + 1);
			player->AddStatusFlag(swganh::object::player::LD);

			// set a timer to 5 minutes to destroy the object, unless logged back in.
			auto deadline_timer = make_shared<boost::asio::deadline_timer>(kernel()->GetIoService(), boost::posix_time::seconds(30));
			deadline_timer->async_wait(boost::bind(&ConnectionService::RemoveClientTimerHandler_, this, boost::asio::placeholders::error, deadline_timer, 10, controller));
        }

        DLOG(WARNING) << "Removing disconnected client";
        client_map.erase(session->remote_endpoint());
		DLOG(WARNING) << "Removing Session";
		session_provider_->EndGameSession(client->GetPlayerId());
    }

    DLOG(WARNING) << "Connection service currently has ("<< client_map.size() << ") clients";
}
void ConnectionService::RemoveClientTimerHandler_(const boost::system::error_code& e, shared_ptr<boost::asio::deadline_timer> timer, int delay_in_secs, shared_ptr<swganh::object::ObjectController> controller)
{
	if (controller)
	{
		// destroy if they haven't reconnected
		if (controller->GetRemoteClient()->GetSession() == nullptr || !controller->GetRemoteClient()->GetSession()->connected())
		{
			auto object_id = controller->GetObject()->GetObjectId();
			DLOG(WARNING) << "Destroying Object " << object_id << " after " << delay_in_secs << " seconds.";
			auto simulation_service = simulation_service_.lock();
			simulation_service->RemoveObjectById(object_id);
		}
	}
}
void ConnectionService::HandleCmdSceneReady_(std::shared_ptr<ConnectionClient> client, const CmdSceneReady& message) {
    DLOG(WARNING) << "Handling CmdSceneReady";

    client->Send(CmdSceneReady());
}

void ConnectionService::HandleClientIdMsg_(std::shared_ptr<ConnectionClient> client, const ClientIdMsg& message) {
    DLOG(WARNING) << "Handling ClientIdMsg";

    // get session key from login service
    uint32_t account_id = login_service()->GetAccountBySessionKey(message.session_hash);

    // authorized
    if (! account_id) {
        DLOG(WARNING) << "Account_id not found from session key, unauthorized access.";
        return;
    }

    // gets player from account
    uint64_t player_id = session_provider_->GetPlayerId(account_id);

    // authorized
    if (! player_id) {
        DLOG(WARNING) << "No player found for the requested account, unauthorized access.";
        return;
    }

    // creates a new session and stores it for later use
    if (!session_provider_->CreateGameSession(player_id, client->GetSession()->connection_id())) {
        DLOG(WARNING) << "Player Not Inserted into Session Map because No Game Session Created!";
    }

    client->Connect(account_id, player_id);

    AddClient_(player_id, client);

    ClientPermissionsMessage client_permissions;
    client_permissions.galaxy_available = kernel()->GetServiceDirectory()->galaxy().status();
    client_permissions.available_character_slots = character_service()->GetMaxCharacters(account_id);
    // @TODO: Replace with configurable value
    client_permissions.unlimited_characters = 0;

    client->Send(client_permissions);
}
<commit_msg>Gets the existing object instead of loading a second instance<commit_after>
#include "swganh/connection/connection_service.h"

#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/lexical_cast.hpp>
#include <glog/logging.h>

#include "anh/crc.h"
#include "anh/event_dispatcher/basic_event.h"
#include "anh/event_dispatcher/event_dispatcher_interface.h"
#include "anh/network/soe/packet.h"
#include "anh/network/soe/server.h"
#include "anh/plugin/plugin_manager.h"
#include "anh/service/service_directory_interface.h"
#include "anh/service/service_manager.h"

#include "swganh/app/swganh_kernel.h"

#include "swganh/connection/ping_server.h"
#include "swganh/connection/connection_client.h"
#include "swganh/connection/providers/mysql_session_provider.h"

#include "swganh/object/object.h"
#include "swganh/object/player/player.h"

#include "swganh/messages/logout_message.h"

using namespace anh::app;
using namespace anh::event_dispatcher;
using namespace anh::network;
using namespace anh::service;
using namespace swganh::base;
using namespace swganh::character;
using namespace swganh::connection;
using namespace swganh::login;
using namespace swganh::messages;
using namespace swganh::simulation;

using namespace std;

using boost::asio::ip::udp;

ConnectionService::ConnectionService(
        string listen_address,
        uint16_t listen_port,
        uint16_t ping_port,
        KernelInterface* kernel)
    : BaseService(kernel)
#pragma warning(push)
#pragma warning(disable: 4355)
    , SwgMessageRouter([=] (const boost::asio::ip::udp::endpoint& endpoint) {
        return GetClientFromEndpoint(endpoint);
      })
#pragma warning(pop)
    , ping_server_(nullptr)
    , listen_address_(listen_address)
    , listen_port_(listen_port)
    , soe_server_(nullptr)
{
    soe_server_.reset(new soe::Server(
        kernel->GetIoService(),
        bind(&ConnectionService::RouteMessage, this, placeholders::_1)));
    soe_server_->event_dispatcher(kernel->GetEventDispatcher());

    session_provider_ = kernel->GetPluginManager()->CreateObject<providers::SessionProviderInterface>("ConnectionService::SessionProvider");
    if (!session_provider_)
    {
        session_provider_ = make_shared<providers::MysqlSessionProvider>(kernel->GetDatabaseManager());
    }
}

ServiceDescription ConnectionService::GetServiceDescription() {
    ServiceDescription service_description(
        "ANH Connection Service",
        "connection",
        "0.1",
        listen_address(),
        0,
        listen_port(),
        ping_port_);

    return service_description;
}

void ConnectionService::subscribe() {
    auto event_dispatcher = kernel()->GetEventDispatcher();

    RegisterMessageHandler<ClientIdMsg>(
        bind(&ConnectionService::HandleClientIdMsg_, this, placeholders::_1, placeholders::_2), false);

    RegisterMessageHandler<CmdSceneReady>(
        bind(&ConnectionService::HandleCmdSceneReady_, this, placeholders::_1, placeholders::_2));

    event_dispatcher->subscribe("NetworkSessionRemoved", [this] (shared_ptr<EventInterface> incoming_event) -> bool {
        auto session_removed = std::static_pointer_cast<anh::event_dispatcher::BasicEvent<anh::network::soe::SessionData>>(incoming_event);

        // Message was triggered from our server so process it.
        if (session_removed->session->server() == server().get()) {
            RemoveClient_(session_removed->session);
        }

        return true;
    });
}

void ConnectionService::onStart() {
    ping_server_ = make_shared<PingServer>(kernel()->GetIoService(), ping_port_);
    soe_server_->Start(listen_port_);

    character_service_ = std::static_pointer_cast<CharacterService>(kernel()->GetServiceManager()->GetService("CharacterService"));
    login_service_ = std::static_pointer_cast<swganh::login::LoginService>(kernel()->GetServiceManager()->GetService("LoginService"));
    simulation_service_ = std::static_pointer_cast<swganh::simulation::SimulationService>(kernel()->GetServiceManager()->GetService("SimulationService"));
}

void ConnectionService::onStop() {
    soe_server_->Shutdown();
    clients_.clear();
}

const string& ConnectionService::listen_address() {
    return listen_address_;
}

uint16_t ConnectionService::listen_port() {
    return listen_port_;
}

ConnectionService::ClientMap& ConnectionService::clients() {
    return clients_;
}

std::unique_ptr<anh::network::soe::Server>& ConnectionService::server() {
    return soe_server_;
}

shared_ptr<CharacterService> ConnectionService::character_service() {
    return character_service_.lock();
}

shared_ptr<LoginService> ConnectionService::login_service() {
    return login_service_.lock();
}

shared_ptr<ConnectionClient> ConnectionService::GetClientFromEndpoint(
        const udp::endpoint& remote_endpoint)
{
    shared_ptr<ConnectionClient> client = nullptr;

    ClientMap::accessor a;

    if (clients_.find(a, remote_endpoint)) {
        client = a->second;
    }

    return client;
}

void ConnectionService::AddClient_(
    uint64_t player_id,
    std::shared_ptr<ConnectionClient> client)
{
    ClientMap& client_map = clients();

    auto find_it = std::find_if(
        client_map.begin(),
        client_map.end(),
        [client, player_id] (ClientMap::value_type& conn_client)
    {
        return conn_client.second->GetPlayerId() == player_id;
    });

    if (find_it != client_map.end()) {
        LogoutMessage message;
        (*find_it).second->Send(message);

        client_map.erase(find_it->first);
    }

    DLOG(WARNING) << "Adding connection client";

    ClientMap::accessor a;
    client_map.insert(a, client->GetSession()->remote_endpoint());
    a->second = client;

    DLOG(WARNING) << "Connection service currently has ("<< client_map.size() << ") clients";
}

void ConnectionService::RemoveClient_(std::shared_ptr<anh::network::soe::Session> session) {
    auto client = GetClientFromEndpoint(session->remote_endpoint());

    auto client_map = clients();

    if (client) {

        auto controller = client->GetController();
        if (controller)
        {
			// player is always + 1 from the creature
			auto simulation_service = simulation_service_.lock();
            auto player = simulation_service->GetObjectById<swganh::object::player::Player>(controller->GetObject()->GetObjectId() + 1);
			player->AddStatusFlag(swganh::object::player::LD);

			// set a timer to 5 minutes to destroy the object, unless logged back in.
			auto deadline_timer = make_shared<boost::asio::deadline_timer>(kernel()->GetIoService(), boost::posix_time::seconds(30));
			deadline_timer->async_wait(boost::bind(&ConnectionService::RemoveClientTimerHandler_, this, boost::asio::placeholders::error, deadline_timer, 10, controller));
        }

        DLOG(WARNING) << "Removing disconnected client";
        client_map.erase(session->remote_endpoint());
		DLOG(WARNING) << "Removing Session";
		session_provider_->EndGameSession(client->GetPlayerId());
    }

    DLOG(WARNING) << "Connection service currently has ("<< client_map.size() << ") clients";
}
void ConnectionService::RemoveClientTimerHandler_(const boost::system::error_code& e, shared_ptr<boost::asio::deadline_timer> timer, int delay_in_secs, shared_ptr<swganh::object::ObjectController> controller)
{
	if (controller)
	{
		// destroy if they haven't reconnected
		if (controller->GetRemoteClient()->GetSession() == nullptr || !controller->GetRemoteClient()->GetSession()->connected())
		{
			auto object_id = controller->GetObject()->GetObjectId();
			DLOG(WARNING) << "Destroying Object " << object_id << " after " << delay_in_secs << " seconds.";
			auto simulation_service = simulation_service_.lock();
			simulation_service->RemoveObjectById(object_id);
		}
	}
}
void ConnectionService::HandleCmdSceneReady_(std::shared_ptr<ConnectionClient> client, const CmdSceneReady& message) {
    DLOG(WARNING) << "Handling CmdSceneReady";

    client->Send(CmdSceneReady());
}

void ConnectionService::HandleClientIdMsg_(std::shared_ptr<ConnectionClient> client, const ClientIdMsg& message) {
    DLOG(WARNING) << "Handling ClientIdMsg";

    // get session key from login service
    uint32_t account_id = login_service()->GetAccountBySessionKey(message.session_hash);

    // authorized
    if (! account_id) {
        DLOG(WARNING) << "Account_id not found from session key, unauthorized access.";
        return;
    }

    // gets player from account
    uint64_t player_id = session_provider_->GetPlayerId(account_id);

    // authorized
    if (! player_id) {
        DLOG(WARNING) << "No player found for the requested account, unauthorized access.";
        return;
    }

    // creates a new session and stores it for later use
    if (!session_provider_->CreateGameSession(player_id, client->GetSession()->connection_id())) {
        DLOG(WARNING) << "Player Not Inserted into Session Map because No Game Session Created!";
    }

    client->Connect(account_id, player_id);

    AddClient_(player_id, client);

    ClientPermissionsMessage client_permissions;
    client_permissions.galaxy_available = kernel()->GetServiceDirectory()->galaxy().status();
    client_permissions.available_character_slots = character_service()->GetMaxCharacters(account_id);
    // @TODO: Replace with configurable value
    client_permissions.unlimited_characters = 0;

    client->Send(client_permissions);
}
<|endoftext|>