<commit_before>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/perv/p9_sbe_tracearray.C $ */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2016,2019                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* Licensed under the Apache License, Version 2.0 (the "License");        */
/* you may not use this file except in compliance with the License.       */
/* You may obtain a copy of the License at                                */
/*                                                                        */
/*     http://www.apache.org/licenses/LICENSE-2.0                         */
/*                                                                        */
/* Unless required by applicable law or agreed to in writing, software    */
/* distributed under the License is distributed on an "AS IS" BASIS,      */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        */
/* implied. See the License for the specific language governing           */
/* permissions and limitations under the License.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
/// @file  p9_sbe_tracearray.C
///
/// @brief Collect contents of specified trace array via SCOM.
///
/// Collects contents of specified trace array via SCOM.  Optionally
/// manages chiplet domain trace engine state (start/stop/reset) around
/// trace array data collection.  Trace array data can be collected only
/// when its controlling chiplet trace engine is stopped.
///
/// Request number of Trace array entries will be packed into data buffer from
/// oldest->youngest entry.
///
/// Calling code is expected to pass the proper target type based on the
/// desired trace resource; a convenience function is provided to find out
/// the expected target type for a given trace resource.
//------------------------------------------------------------------------------
// *HWP HW Owner        : Joachim Fenkes <fenkes@de.ibm.com>
// *HWP HW Backup Owner : Joe McGill <jmcgill@us.ibm.com>
// *HWP FW Owner        : Shakeeb Pasha<shakeebbk@in.ibm.com>
// *HWP Team            : Perv
// *HWP Level           : 1
// *HWP Consumed by     : SBE
//------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------
// Includes
//-----------------------------------------------------------------------------------
#include <p9_sbe_tracearray.H>

//-----------------------------------------------------------------------------------
// Function definitions
//-----------------------------------------------------------------------------------
fapi2::ReturnCode p9_sbe_tracearray(
    const fapi2::Target<P9_SBE_TRACEARRAY_TARGET_TYPES>& i_target,
    const proc_gettracearray_args& i_args,
    uint64_t* o_ta_data,
    const uint32_t i_num_rows
)
{
    FAPI_INF("Start");
    FAPI_INF("End");
    return fapi2::current_err;
}
<commit_msg>Trace Array on SBE L2<commit_after>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/perv/p9_sbe_tracearray.C $ */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2016,2019                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* Licensed under the Apache License, Version 2.0 (the "License");        */
/* you may not use this file except in compliance with the License.       */
/* You may obtain a copy of the License at                                */
/*                                                                        */
/*     http://www.apache.org/licenses/LICENSE-2.0                         */
/*                                                                        */
/* Unless required by applicable law or agreed to in writing, software    */
/* distributed under the License is distributed on an "AS IS" BASIS,      */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        */
/* implied. See the License for the specific language governing           */
/* permissions and limitations under the License.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
/// @file  p9_sbe_tracearray.C
///
/// @brief Collect contents of specified trace array via SCOM.
///
/// Collects contents of specified trace array via SCOM.  Optionally
/// manages chiplet domain trace engine state (start/stop/reset) around
/// trace array data collection.  Trace array data can be collected only
/// when its controlling chiplet trace engine is stopped.
///
/// Request number of Trace array entries will be packed into data buffer from
/// oldest->youngest entry.
///
/// Calling code is expected to pass the proper target type based on the
/// desired trace resource; a convenience function is provided to find out
/// the expected target type for a given trace resource.
//------------------------------------------------------------------------------
// *HWP HW Owner        : Joachim Fenkes <fenkes@de.ibm.com>
// *HWP HW Backup Owner : Joe McGill <jmcgill@us.ibm.com>
// *HWP FW Owner        : Shakeeb Pasha<shakeebbk@in.ibm.com>
// *HWP Team            : Perv
// *HWP Level           : 1
// *HWP Consumed by     : SBE
//------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------
// Includes
//-----------------------------------------------------------------------------------
#include <p9_sbe_tracearray.H>

#include <p9_mc_scom_addresses.H>
#include <p9_misc_scom_addresses.H>
#include <p9_obus_scom_addresses.H>
#include <p9_perv_scom_addresses.H>
#include <p9_perv_scom_addresses_fld.H>
#include <p9_quad_scom_addresses.H>
#include <p9_xbus_scom_addresses.H>

p9_tracearray_bus_id NO_TB = (p9_tracearray_bus_id)0;

//------------------------------------------------------------------------------
// Constant definitions
//------------------------------------------------------------------------------

// offset to store high/low data within a given entry
const uint32_t HI_BIT_OFFSET = 0;
const uint32_t LO_BIT_OFFSET = 64;

const uint32_t DEBUG_TRACE_CONTROL_OFS = PERV_DEBUG_TRACE_CONTROL - PERV_DBG_MODE_REG;

const uint32_t DEBUG_TRACE_CONTROL_START = 0;
const uint32_t DEBUG_TRACE_CONTROL_STOP  = 1;
const uint32_t DEBUG_TRACE_CONTROL_RESET = 2;

const uint32_t TRACE_HI_DATA_OFS         =
    PERV_TP_TPCHIP_TRA0_TR0_TRACE_HI_DATA_REG - PERV_TP_TPCHIP_TRA0_TR0_TRACE_HI_DATA_REG;
const uint32_t TRACE_LO_DATA_OFS         =
    PERV_TP_TPCHIP_TRA0_TR0_TRACE_LO_DATA_REG - PERV_TP_TPCHIP_TRA0_TR0_TRACE_HI_DATA_REG;
const uint32_t TRACE_TRCTRL_CONFIG_OFS   =
    PERV_TP_TPCHIP_TRA0_TR0_TRACE_TRCTRL_CONFIG - PERV_TP_TPCHIP_TRA0_TR0_TRACE_HI_DATA_REG;

const uint32_t EX_L21_SCOM_OFFSET        = EQ_TPLC21_TR0_TRACE_HI_DATA_REG - EQ_TPLC20_TR0_TRACE_HI_DATA_REG;
const uint32_t EX_L31_SCOM_OFFSET        = EQ_L3TRA1_TR0_TRACE_HI_DATA_REG - EQ_L3TRA0_TR0_TRACE_HI_DATA_REG;

const uint32_t TRACE_LO_DATA_RUNNING     = PERV_1_TPCHIP_TRA0_TR0_TRACE_LO_DATA_REG_RUNNING;
const uint32_t TRCTRL_MUX0_SEL           = 14;
const uint32_t TRCTRL_MUX0_SEL_LEN       = 2;

const uint32_t TRACE_MUX_POSITIONS       = 1 << TRCTRL_MUX0_SEL_LEN;

const uint32_t TA_BASE_SCOM_MULTIPLIER = 0x00000040;
const uint32_t TA_EX_OFFSET_MULTIPLIER = 0x00000040;
const uint32_t TA_DEBUG_BASE_SCOM      = 0x000107C0;
const uint32_t TA_TRACE_BASE_SCOM      = 0x00010400;
//------------------------------------------------------------------------------
// Table of known trace arrays
//------------------------------------------------------------------------------

struct ta_def
{
    /* One entry per mux setting; value of 0 means N/A */
    p9_tracearray_bus_id bus_ids[TRACE_MUX_POSITIONS];
    const uint8_t chiplet;
    const uint8_t base_multiplier;
    const uint8_t ex_multiplier;
};

static const ta_def ta_defs[] =
{
    /* PERV */
    { { PROC_TB_PIB, PROC_TB_OCC, PROC_TB_TOD },                       0x01,    0x00, 0x00},
    { { PROC_TB_SBE, PROC_TB_PIB_ALT },                                0x01,    0x01, 0x00},
    /* N0 */
    { { PROC_TB_PBIOE0 },                                              0x02,    0x00, 0x00},
    { { PROC_TB_PBIOE1 },                                              0x02,    0x01, 0x00},
    { { PROC_TB_CXA0, PROC_TB_NX },                                    0x02,    0x02, 0x00},
    /* N1 */
    { { PROC_TB_PB6    },                                              0x03,      0x00, 0x00},
    { { PROC_TB_PB7    },                                              0x03,      0x01, 0x00},
    { { PROC_TB_PB8    },                                              0x03,      0x02, 0x00},
    { { PROC_TB_PB9    },                                              0x03,      0x03, 0x00},
    { { PROC_TB_PB10   },                                              0x03,      0x04, 0x00},
    { { PROC_TB_PB11   },                                              0x03,      0x05, 0x00},
    { { PROC_TB_MCD0, PROC_TB_MCD1, PROC_TB_VAS },                     0x03,      0x06, 0x00},
    { { PROC_TB_MCS2, PROC_TB_MCS3, PROC_TB_PB13 },                    0x03,      0x07, 0x00},
    { { PROC_TB_PBIO0  },                                              0x03,      0x08, 0x00},
    { { PROC_TB_PBIO1  },                                              0x03,      0x09, 0x00},
    /* N2 */
    { { PROC_TB_CXA1, PROC_TB_IOPSI },                                 0x04,      0x00, 0x00},
    { { PROC_TB_PCIS0, PROC_TB_PCIS1, PROC_TB_PCIS2 },                 0x04,      0x01, 0x00},
    /* N3 */
    { { PROC_TB_PB0    },                                              0x05,      0x00, 0x00},
    { { PROC_TB_PB1    },                                              0x05,      0x01, 0x00},
    { { PROC_TB_PB2    },                                              0x05,      0x02, 0x00},
    { { PROC_TB_PB3    },                                              0x05,      0x03, 0x00},
    { { PROC_TB_PB4    },                                              0x05,      0x04, 0x00},
    { { PROC_TB_PB5    },                                              0x05,      0x05, 0x00},
    { { PROC_TB_INT, PROC_TB_NPU1, PROC_TB_NMMU1 },                    0x05,      0x06, 0x00},
    { { PROC_TB_MCS0, PROC_TB_MCS1, PROC_TB_PB12 },                    0x05,      0x07, 0x00},
    { { PROC_TB_BRIDGE },                                              0x05,      0x08, 0x00},
    { { PROC_TB_NPU0   },                                              0x05,      0x0A, 0x00},
    { { PROC_TB_NMMU0  },                                              0x05,      0x0B, 0x00},
    /* XBUS */
    { { PROC_TB_PBIOX0, PROC_TB_IOX0 },                                0x06,  0x00, 0x00},
    { { PROC_TB_PBIOX1, PROC_TB_IOX1 },                                0x06,  0x01, 0x00},
    { { PROC_TB_PBIOX2, PROC_TB_IOX2 },                                0x06,  0x03, 0x00},
    /* PCIx */
    { { PROC_TB_PCI0X, PROC_TB_PCI00 },                                0x0D,      0x00, 0x00},
    { { PROC_TB_PCI1X, PROC_TB_PCI11, PROC_TB_PCI12 },                 0x0E,      0x00, 0x00},
    { { PROC_TB_PCI2X, PROC_TB_PCI23, PROC_TB_PCI24, PROC_TB_PCI25 },  0x0F,      0x00, 0x00},
    /* OBUS */
    { { PROC_TB_PBIOOA, PROC_TB_IOO },                                 0x09, 0x00, 0x00},
    /* MC */
    { { PROC_TB_MCA0   },                                              0x07,      0x20, 0x00},
    { { PROC_TB_MCA1   },                                              0x07,      0x21, 0x00},
    { { PROC_TB_IOMC0, PROC_TB_IOMC1, PROC_TB_IOMC2, PROC_TB_IOMC3  }, 0x07,      0x00, 0x00},
    /* EX */
    { { PROC_TB_L20, NO_TB, NO_TB, PROC_TB_SKIT10 },                   0x10,      0x94, 0x0C},
    { { PROC_TB_L21, NO_TB, NO_TB, PROC_TB_SKIT11 },                   0x10,      0x95, 0x0C},
    { { PROC_TB_L30, PROC_TB_NCU0, PROC_TB_CME, PROC_TB_EQPB },        0x10,      0x00, 0x02},
    { { PROC_TB_L31, PROC_TB_NCU1, PROC_TB_IVRM, PROC_TB_SKEWADJ },    0x10,      0x01, 0x02},
    /* CORE */
    { { PROC_TB_CORE0  },                                              0x20,         0x01, 0x00},
    { { PROC_TB_CORE1  },                                              0x20,         0x02, 0x00},
};

#define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0]))

class TraceArrayFinder
{
    public:
        uint32_t mux_sel;
        uint32_t debug_scom_base;
        uint32_t trace_scom_base;
        uint32_t ex_odd_scom_offset;

        TraceArrayFinder(p9_tracearray_bus_id i_trace_bus) :
            mux_sel(0), debug_scom_base(0),
            trace_scom_base(0), ex_odd_scom_offset(0)
        {
            for(auto& l_ta_def : ta_defs)
            {
                for(size_t sel = 0; sel < TRACE_MUX_POSITIONS; sel++)
                {
                    if(l_ta_def.bus_ids[sel] == i_trace_bus)
                    {
                        fapi2::buffer<uint32_t> l_buffer;
                        l_buffer.insert<0, 8>(l_ta_def.chiplet);
                        debug_scom_base = l_buffer | TA_DEBUG_BASE_SCOM;

                        trace_scom_base = l_buffer |
                                          (TA_TRACE_BASE_SCOM +
                                           TA_BASE_SCOM_MULTIPLIER *
                                           l_ta_def.base_multiplier);

                        // Special handling Core
                        if(l_ta_def.chiplet == 0x20)
                        {
                            trace_scom_base &= 0x00FFFFFF;
                        }

                        ex_odd_scom_offset = TA_EX_OFFSET_MULTIPLIER *
                                             l_ta_def.ex_multiplier;

                        mux_sel = sel;
                        return;
                    }
                }
            }
        }
};

//-----------------------------------------------------------------------------
// Function definitions
//-----------------------------------------------------------------------------
fapi2::ReturnCode p9_sbe_tracearray(
    const fapi2::Target<P9_SBE_TRACEARRAY_TARGET_TYPES>& i_target,
    const p9_sbe_tracearray_args& i_args,
    uint64_t* o_ta_data,
    const uint32_t i_cur_row,
    const uint32_t i_num_rows
)
{
    fapi2::Target < P9_SBE_TRACEARRAY_TARGET_TYPES |
    fapi2::TARGET_TYPE_EQ > target = i_target;
    FAPI_INF("Start");
    const TraceArrayFinder l_ta_finder(i_args.trace_bus);

    fapi2::TargetType arg_type = i_target.getType();
    fapi2::TargetType ta_type =
        p9_sbe_tracearray_target_type(i_args.trace_bus);

    const uint32_t DEBUG_TRACE_CONTROL = l_ta_finder.debug_scom_base +
                                         DEBUG_TRACE_CONTROL_OFS;
    const uint32_t TRACE_SCOM_BASE     = l_ta_finder.trace_scom_base;
    const uint32_t TRACE_SCOM_OFFSET   = l_ta_finder.ex_odd_scom_offset;

    if ((arg_type & ta_type) == 0)
    {
        FAPI_ERR("Specified trace array requires target type 0x%X,"
                 "but the supplied target is of type 0x%X", ta_type, arg_type);
        return fapi2::RC_PROC_GETTRACEARRAY_INVALID_TARGET;
    }

    /* Nimbus DD1 core traces can't be read out via SCOM.
     * Check an EC feature to see if that's fixed. */
    if (ta_type == fapi2::TARGET_TYPE_CORE)
    {
        uint8_t l_core_trace_scomable = 0;

        fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP> proc_target =
            i_target.getParent<fapi2::TARGET_TYPE_PROC_CHIP>();
        FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CHIP_EC_FEATURE_CORE_TRACE_SCOMABLE,
                               proc_target, l_core_trace_scomable),
                 "Failed to query chip EC feature"
                 "ATTR_CHIP_EC_FEATURE_CORE_TRACE_SCOMABLE");

        if (!l_core_trace_scomable)
        {
            FAPI_ERR("Core arrays cannot be dumped in this chip EC;"
                     "please use fastarray instead.");
            return fapi2::RC_PROC_GETTRACEARRAY_CORE_NOT_DUMPABLE;
        }
    }

    /* For convenience, we link Cache trace arrays to the virtual EX chiplets.
     * Transform back to EQ chiplet. */
    if (ta_type == fapi2::TARGET_TYPE_EX)
    {
        target = i_target.getParent<fapi2::TARGET_TYPE_EQ>();
    }

    /* Check that the trace mux is set up as expected */
    if (!i_args.ignore_mux_setting)
    {
        fapi2::buffer<uint64_t> buf;
        FAPI_TRY(fapi2::getScom(target,
                                TRACE_SCOM_BASE + TRACE_SCOM_OFFSET + TRACE_TRCTRL_CONFIG_OFS,
                                buf),
                 "Failed to read current trace mux setting");
        uint32_t cur_sel = 0;
        buf.extractToRight<TRCTRL_MUX0_SEL, TRCTRL_MUX0_SEL_LEN>(cur_sel);

        if (cur_sel != l_ta_finder.mux_sel)
        {
            FAPI_ERR("Primary trace mux is set to %d,"
                     " but %d is needed for requested trace bus",
                     cur_sel, l_ta_finder.mux_sel);
            return fapi2::RC_PROC_GETTRACEARRAY_TRACE_MUX_INCORRECT;
        }
    }

    /* If control is requested along with dump, pre dump condition
     * should run only once.
     * */
    if (i_args.stop_pre_dump && (!i_args.collect_dump || (i_cur_row == 0)))
    {
        FAPI_DBG("Stopping trace arrays");
        fapi2::buffer<uint64_t> buf;
        buf.flush<0>().setBit<DEBUG_TRACE_CONTROL_STOP>();
        FAPI_TRY(fapi2::putScom(target, DEBUG_TRACE_CONTROL, buf),
                 "Failed to stop chiplet domain trace arrays");
    }

    if (i_args.collect_dump)
    {
        fapi2::buffer<uint64_t> buf;

        /* Start with the low data register because that's where the
         * "trace running" bit is. */
        for (uint32_t i = 0; i < i_num_rows; i++)
        {
            FAPI_TRY(fapi2::getScom(target,
                                    TRACE_SCOM_BASE + TRACE_SCOM_OFFSET + TRACE_LO_DATA_OFS,
                                    buf),
                     "Failed to read trace array low data register,"
                     " iteration %d", i);

            /* The "trace running" bit is our best indicator of whether
             * the array is currently running.
             * If it is, the read won't have incremented the address,
             * so it's okay to bail out. */
            if (buf.getBit<TRACE_LO_DATA_RUNNING>())
            {
                FAPI_ERR("Trace array is still running -- "
                         " If you think you stopped it, maybe the controlling "
                         "debug macro is slaved to another debug macro?");
                return fapi2::RC_PROC_GETTRACEARRAY_TRACE_RUNNING;
            }

            *((uint64_t*)o_ta_data + (2 * i + 1)) = buf;
        }

        /*
         * Run empty scoms to move the address pointer of trace array control
         * logic, till it reaches the same row again, as the trace array is
         * a circular buffer
         */
        for (uint32_t i = 0; i < (P9_TRACEARRAY_NUM_ROWS - i_num_rows); i++)
        {
            FAPI_TRY(fapi2::getScom(target,
                                    TRACE_SCOM_BASE + TRACE_SCOM_OFFSET + TRACE_LO_DATA_OFS,
                                    buf),
                     "Failed to read trace array low data register, iteration %d", i);
        }

        /* Then dump the high data */
        for (uint32_t i = 0; i < i_num_rows; i++)
        {
            FAPI_TRY(fapi2::getScom(target,
                                    TRACE_SCOM_BASE + TRACE_SCOM_OFFSET + TRACE_HI_DATA_OFS, buf),
                     "Failed to read trace array high data register, iteration %d", i);
            *((uint64_t*)o_ta_data + (2 * i + 0)) = buf;
        }
    }

    /* If control is requested along with dump, post dump condition should run
     * only after all the P9_TRACEARRAY_NUM_ROWS rows are read.
     * */
    if (i_args.reset_post_dump &&
        (!i_args.collect_dump || (i_cur_row >= P9_TRACEARRAY_NUM_ROWS)))
    {
        FAPI_DBG("Resetting trace arrays");
        fapi2::buffer<uint64_t> buf;
        buf.flush<0>().setBit<DEBUG_TRACE_CONTROL_RESET>();
        FAPI_TRY(fapi2::putScom(target, DEBUG_TRACE_CONTROL, buf),
                 "Failed to reset chiplet domain trace arrays");
    }

    if (i_args.restart_post_dump &&
        (!i_args.collect_dump || (i_cur_row >= P9_TRACEARRAY_NUM_ROWS)))
    {
        FAPI_DBG("Starting trace arrays");
        fapi2::buffer<uint64_t> buf;
        buf.flush<0>().setBit<DEBUG_TRACE_CONTROL_START>();
        FAPI_TRY(fapi2::putScom(target, DEBUG_TRACE_CONTROL, buf),
                 "Failed to restart chiplet domain trace arrays");
    }

    // mark HWP exit
    FAPI_INF("Success");
    return fapi2::FAPI2_RC_SUCCESS;

fapi_try_exit:
    return fapi2::current_err;

}
<|endoftext|>


<commit_before>/* Copyright (c) 2014 Quanta Research Cambridge, Inc
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included
 * in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 */

#include <stdio.h>
#include <netdb.h>

#include "sock_utils.h"

#include "EchoRequest.h"
#include "EchoIndication.h"

EchoRequestProxy *echoRequestProxy;
EchoIndicationProxy *sIndicationProxy;
static int daemon_trace ;//= 1;

class EchoIndication : public EchoIndicationWrapper
{
public:
    void heard(uint32_t v) {
        if (daemon_trace)
        fprintf(stderr, "daemon: %p heard an echo: %d\n", sIndicationProxy, v);
        sIndicationProxy->heard(v);
    }
    void heard2(uint32_t a, uint32_t b) {
        if (daemon_trace)
        fprintf(stderr, "daemon: %p heard an echo2: %d %d\n", sIndicationProxy, a, b);
        sIndicationProxy->heard2(a, b);
    }
    EchoIndication(unsigned int id, PortalItemFunctions *item, void *param) : EchoIndicationWrapper(id, item, param) {}
};

class EchoRequest : public EchoRequestWrapper
{
public:
    void say ( const uint32_t v ) {
        if (daemon_trace)
        fprintf(stderr, "daemon[%s:%d] proxy %p\n", __FUNCTION__, __LINE__, echoRequestProxy);
        echoRequestProxy->say(v);
    }
    void say2 ( const uint32_t a, const uint32_t b ) {
        if (daemon_trace)
        fprintf(stderr, "daemon[%s:%d] proxy %p\n", __FUNCTION__, __LINE__, echoRequestProxy);
        echoRequestProxy->say2(a, b);
    }
    void setLeds ( const uint32_t v ) {
        fprintf(stderr, "daemon[%s:%d] proxy %p\n", __FUNCTION__, __LINE__, echoRequestProxy);
        echoRequestProxy->setLeds(v);
        sleep(1);
        exit(1);
    }
    EchoRequest(unsigned int id, PortalItemFunctions *item, void *param) : EchoRequestWrapper(id, item, param, &EchoRequestJson_handleMessage, 1000) {}
};

int main(int argc, const char **argv)
{
    PortalSocketParam param;
//#define USE_UNIX_SOCKET
#ifdef USE_UNIX_SOCKET
#define PARAM NULL
#else
#define PARAM &param
#endif

    EchoIndication *echoIndication = new EchoIndication(IfcNames_EchoIndication, NULL, NULL);
    echoRequestProxy = new EchoRequestProxy(IfcNames_EchoRequest);
    int rc = getaddrinfo("127.0.0.1", "5000", NULL, &param.addr);
    sIndicationProxy = new EchoIndicationProxy(IfcNames_EchoIndication, &socketfuncResp, PARAM, &EchoIndicationJsonProxyReq, 1000);
    rc = getaddrinfo("127.0.0.1", "5001", NULL, &param.addr);
    EchoRequest *sRequest = new EchoRequest(IfcNames_EchoRequest, &socketfuncResp, PARAM);

    printf("[%s:%d] daemon sleeping...\n", __FUNCTION__, __LINE__);
    while(1)
        sleep(100);
    return 0;
}
<commit_msg>echowebsocket daemon.cpp uses websocketfuncResp<commit_after>/* Copyright (c) 2014 Quanta Research Cambridge, Inc
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included
 * in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 */

#include <stdio.h>
#include <netdb.h>

#include "sock_utils.h"

#include "EchoRequest.h"
#include "EchoIndication.h"

EchoRequestProxy *echoRequestProxy;
EchoIndicationProxy *sIndicationProxy;
static int daemon_trace ;//= 1;

class EchoIndication : public EchoIndicationWrapper
{
public:
    void heard(uint32_t v) {
        if (daemon_trace)
        fprintf(stderr, "daemon: %p heard an echo: %d\n", sIndicationProxy, v);
        sIndicationProxy->heard(v);
    }
    void heard2(uint32_t a, uint32_t b) {
        if (daemon_trace)
        fprintf(stderr, "daemon: %p heard an echo2: %d %d\n", sIndicationProxy, a, b);
        sIndicationProxy->heard2(a, b);
    }
    EchoIndication(unsigned int id, PortalItemFunctions *item, void *param) : EchoIndicationWrapper(id, item, param) {}
};

class EchoRequest : public EchoRequestWrapper
{
public:
    void say ( const uint32_t v ) {
        if (daemon_trace)
        fprintf(stderr, "daemon[%s:%d] proxy %p\n", __FUNCTION__, __LINE__, echoRequestProxy);
        echoRequestProxy->say(v);
    }
    void say2 ( const uint32_t a, const uint32_t b ) {
        if (daemon_trace)
        fprintf(stderr, "daemon[%s:%d] proxy %p\n", __FUNCTION__, __LINE__, echoRequestProxy);
        echoRequestProxy->say2(a, b);
    }
    void setLeds ( const uint32_t v ) {
        fprintf(stderr, "daemon[%s:%d] proxy %p\n", __FUNCTION__, __LINE__, echoRequestProxy);
        echoRequestProxy->setLeds(v);
        sleep(1);
        exit(1);
    }
    EchoRequest(unsigned int id, PortalItemFunctions *item, void *param) : EchoRequestWrapper(id, item, param, &EchoRequestJson_handleMessage, 1000) {}
};

int main(int argc, const char **argv)
{
    PortalSocketParam param;
//#define USE_UNIX_SOCKET
#ifdef USE_UNIX_SOCKET
#define PARAM NULL
#else
#define PARAM &param
#endif

    EchoIndication *echoIndication = new EchoIndication(IfcNames_EchoIndication, NULL, NULL);
    echoRequestProxy = new EchoRequestProxy(IfcNames_EchoRequest);
    int rc = getaddrinfo("127.0.0.1", "5000", NULL, &param.addr);
    sIndicationProxy = new EchoIndicationProxy(IfcNames_EchoIndication, &websocketfuncResp, PARAM, &EchoIndicationJsonProxyReq, 1000);
    rc = getaddrinfo("127.0.0.1", "5001", NULL, &param.addr);
    EchoRequest *sRequest = new EchoRequest(IfcNames_EchoRequest, &websocketfuncResp, PARAM);

    printf("[%s:%d] daemon sleeping...\n", __FUNCTION__, __LINE__);
    while(1)
        sleep(100);
    return 0;
}
<|endoftext|>


<commit_before><commit_msg>Replaced player AI weight with ship gadgetLevel+1 rather than rank+1, as player reports were that AI were too great in numbers.<commit_after><|endoftext|>


<commit_before>#include <Script/ScriptExtensions.hpp>
#include <Script/SFML/Extensions.hpp>

#include <angelscript.h>
#include <cassert>

void MessageCallback(const asSMessageInfo *msg, void* /*param*/)
{
    const char *type = "ERR ";
    if (msg->type == asMSGTYPE_WARNING)
        type = "WARN";
    else if (msg->type == asMSGTYPE_INFORMATION)
        type = "INFO";

    printf("%s (%d, %d) : %s : %s\n", msg->section, msg->row, msg->col, type, msg->message);
}

int main(int argc, char** argv)
{
    asIScriptEngine* engine = asCreateScriptEngine(ANGELSCRIPT_VERSION);

    engine->SetMessageCallback(asFUNCTION(MessageCallback), nullptr, asCALL_CDECL);

    // Make certain that the scripts registered correctly
    assert(Script::ScriptExtensions::RegisteredCommonExtensions());
    assert(Script::SFML::RegisteredExtensions());

    // Register the extensions into the engine
    Script::ScriptExtensions::RegisterAll(engine);

    ///\TODO: Game class

    engine->Release();
    return 0;
}
<commit_msg>Let's add an exception callback for the scripts<commit_after>#include <Script/ScriptExtensions.hpp>
#include <Script/SFML/Extensions.hpp>

#include <angelscript.h>

#include <iostream>
#include <cassert>

void MessageCallback(const asSMessageInfo *msg, void* /*param*/)
{
    const char *type = "ERR ";
    if (msg->type == asMSGTYPE_WARNING)
        type = "WARN";
    else if (msg->type == asMSGTYPE_INFORMATION)
        type = "INFO";

    printf("%s (%d, %d) : %s : %s\n", msg->section, msg->row, msg->col, type, msg->message);
}

void ExceptionCallback(asIScriptContext *ctx, void* /*param*/)
{
    std::cout << "!! Script Exception occured !!\n" << std::endl;

    const asIScriptFunction *function = ctx->GetExceptionFunction();
    if (function->GetModule())
        std::cout << function->GetModuleName();
    else
        std::cout << function->GetScriptSectionName();
    int col = 0;
    std::cout << ":" << ctx->GetExceptionLineNumber(&col) << ":" << col << " in " << function->GetDeclaration() << ":" << std::endl;

    std::cout << ctx->GetExceptionString() << std::endl;

    asUINT callStackSize = ctx->GetCallstackSize();
    if (callStackSize > 1)
    {
        std::cout << "--- call stack ---" << std::endl;
        for (asUINT n = 1; n < callStackSize; n++)
        {
            function = ctx->GetFunction(n);
            if (function)
            {
                if (function->GetFuncType() == asFUNC_SCRIPT)
                {
                    if (function->GetModule())
                        std::cout << function->GetModuleName();
                    else
                        std::cout << function->GetScriptSectionName();
                    int col = 0;
                    std::cout << ":" << ctx->GetLineNumber(n, &col) << ":" << col << " in " << function->GetDeclaration() << std::endl;
                }
                else
                {
                    // The context is being reused by the application for a nested call
                    std::cout << "{...application...}: " << function->GetDeclaration() << std::endl;
                }
            }
            else
            {
                // The context is being reused by the script engine for a nested call
                std::cout << "{...script engine...}" << std::endl;
            }
        }
    }

    std::cout << std::endl;
}

asIScriptContext* getContext(asIScriptEngine* eng, void*)
{
    auto* ctx = eng->CreateContext();
    ctx->SetExceptionCallback(asFUNCTION(ExceptionCallback), nullptr, asCALL_CDECL);

    return ctx;
}

void returnContext(asIScriptEngine* eng, asIScriptContext* ctx, void*)
{
    ctx->Release();
}

int main(int argc, char** argv)
{
    asIScriptEngine* engine = asCreateScriptEngine(ANGELSCRIPT_VERSION);

    engine->SetMessageCallback(asFUNCTION(MessageCallback), nullptr, asCALL_CDECL);
    engine->SetContextCallbacks(getContext, returnContext);

    // Make certain that the scripts registered correctly
    assert(Script::ScriptExtensions::RegisteredCommonExtensions());
    assert(Script::SFML::RegisteredExtensions());

    // Register the extensions into the engine
    Script::ScriptExtensions::RegisterAll(engine);

    ///\TODO: Game class

    engine->Release();
    return 0;
}
<|endoftext|>


<commit_before>#include <iostream>          /* std::cout        */
#include <algorithm>         /* std::max         */
#include "print_utils.h"     /* print_table_row  */
#include "rand_generator.h"  /* init_rand()      */
using namespace std;

const int number_of_iterations    =   10;
const int number_of_items_in_iter =   20; /* input vector sz */
const int max_item_value          =   10;
const int max_sum                 =  100; /* expected sum    */

/* DP Bottom-Up Memoization approach to calculate Subset Sum *
 * Can handle Duplicates and 0 in set.                       */
bool subset_sum(const std::vector<int>& set, const int sum,
                bool print_dp_table=false, bool print_backtrace=false)
{
   int n = set.size();
   bool result = false;
    /* Row is the constraint to solve (in this case sum)     *
     * Column is input values (in this case set[])           */
   std::vector<std::vector<bool>> dp(sum+1, vector<bool> (n+1, false));
   /* First row, pre-initialize lookup row for (sum-set[i])  */
   for(int j = 0; j <= n; j++)    dp[0][j] = true;
   /* First column, pre-init for empty set[], except row 0   */
   for(int i = 1; i <= sum; i++)  dp[i][0] = false;

   /* Calculate all dp indexes with Dynamic Programming      */
   for   (int s = 1; s <= sum; s++) {
      for(int j = 1; j <= n; j++) {
         int set_idx = j-1;
         if(set[set_idx] > s) /* Skip out of bounds subset   */
            dp[s][j] = dp[s][j-1];
         else
            dp[s][j] = dp[s][j-1] || dp[s-set[set_idx]][j-1];
      }
   }

   /* Final ans - Can we reach sum from any of the numbers ? */
   if(dp[sum][n]) result = true;

   /* Check if we should print DP Table or Result Backtrace  */
   if(print_dp_table) {
      print_table_row<int>("input-values", set);

      /* Print the DP Matrix                                 */
      printf("Rows = Sums and Columns = n\n");
      for (int j = 0; j <= n; j++) {
         if(j == 0)  printf("--- | --- ");
         else	     printf("%3d ",set[j-1]);
      }
      printf("\n--------------------------------------------\n");
      for (int i = 0; i <= sum; i++) {
         if(i == 0)  printf("--- | ");
         else        printf("%3d | ", i);
         for (int j = 0; j <= n; j++)
            printf ("%3d ", (dp[i][j] == true) ? 1 : 0);
         printf("\n");
      }
   }
   /* Check if we should print the result backtrace          */
   if(result && print_backtrace) {
      cout << "Numbers:";
      /* Start from last row, find out which column was first*
       * set in the DP table. This is O(n lg n) algorithm    */
      for(int i = sum; i > 0;) {
         auto it = std::lower_bound(dp[i].begin(), dp[i].end(), true);
         if(*it == true) {
            int idx = it - dp[i].begin() - 1;
            i -= set[idx];
            cout << set[idx] << ",";
         }
      }
      cout << endl;
   }
   return result;
}

/* Can handle duplicates and negative numbers                */
bool subset_sum_brute(const std::vector<int>& set, int n, int sum)
{
   int idx = n-1;         /* idx is 0 based                  */
   if(sum == 0)           return true;
   if(n == 0 && sum != 0) return false;
   /* Skip out of bounds subset                              */
   if(set[idx] > sum)
      return subset_sum_brute(set, n-1, sum);
   /* 2 cases in dynamic programming:                        *
    * a) Don't include last element in calculating sum       *
    * b) Include last element in calculating sum             */
   return ( subset_sum_brute(set, n-1, sum) ||
            subset_sum_brute(set, n-1, sum - set[idx]) );
}

/* Given set size, generate elements randomly and then call  *
 * Subset sum Brute and DP algorithms                        */
bool subsetsum_tester(size_t set_size, int sum, int &cnt)
{
   std::vector<int> val(set_size);

   /* Generate vector contents randomly                      */
   fill_vector_rand(val, 0, max_item_value);

   auto dp_res    = subset_sum(val, sum);
   auto brute_res = subset_sum_brute(val, val.size(), sum);

   if(dp_res != brute_res) {
      cout << "Error: Subset failed for given input "
           << "DP = " << dp_res << " Brute = " << brute_res << endl;
      cout << "Below is the DP table result:"  << endl;
      subset_sum(val, sum, true, true);
      return false;
   }
   if(dp_res == true) cnt++;
   return true;
}

int main()
{
   int cnt = 0; /* Number of successful Subsetsum runs       */
   cout << "Running " << number_of_iterations << " iterations "
        << "each with " << number_of_items_in_iter << " items "
        << "and with max_sum=" << max_sum          << endl;
   init_rand();
   for(int i = 1; i <= number_of_iterations; i++)
      if(subsetsum_tester(number_of_items_in_iter, max_sum, cnt) == false)
         return -1;

   cout << "Info: All Subset sum test-cases completed successfully "
        << cnt << " subsets had subset's with sum " << max_sum << endl;
   return 0;
}
<commit_msg>DP: Add problem statement to subset sum 07/22/2016<commit_after>#include <iostream>          /* std::cout        */
#include <algorithm>         /* std::max         */
#include "print_utils.h"     /* print_table_row  */
#include "rand_generator.h"  /* init_rand()      */
using namespace std;

/* Given a set of integers & a target sum, find out if there *
 * is a subset whose sum equals to the target sum.           */

const int number_of_iterations    =   10;
const int number_of_items_in_iter =   20; /* input vector sz */
const int max_item_value          =   10;
const int max_sum                 =  100; /* expected sum    */

/* DP Bottom-Up Memoization approach to calculate Subset Sum *
 * Can handle Duplicates and 0 in set.                       */
bool subset_sum(const std::vector<int>& set, const int sum,
                bool print_dp_table=false, bool print_backtrace=false)
{
   int n = set.size();
   bool result = false;
    /* Row is the constraint to solve (in this case sum)     *
     * Column is input values (in this case set[])           */
   std::vector<std::vector<bool>> dp(sum+1, vector<bool> (n+1, false));
   /* First row, pre-initialize lookup row for (sum-set[i])  */
   for(int j = 0; j <= n; j++)    dp[0][j] = true;
   /* First column, pre-init for empty set[], except row 0   */
   for(int i = 1; i <= sum; i++)  dp[i][0] = false;

   /* Calculate all dp indexes with Dynamic Programming      */
   for   (int s = 1; s <= sum; s++) {
      for(int j = 1; j <= n; j++) {
         int set_idx = j-1;
         if(set[set_idx] > s) /* Skip out of bounds subset   */
            dp[s][j] = dp[s][j-1];
         else
            dp[s][j] = dp[s][j-1] || dp[s-set[set_idx]][j-1];
      }
   }

   /* Final ans - Can we reach sum from any of the numbers ? */
   if(dp[sum][n]) result = true;

   /* Check if we should print DP Table or Result Backtrace  */
   if(print_dp_table) {
      print_table_row<int>("input-values", set);

      /* Print the DP Matrix                                 */
      printf("Rows = Sums and Columns = n\n");
      for (int j = 0; j <= n; j++) {
         if(j == 0)  printf("--- | --- ");
         else	     printf("%3d ",set[j-1]);
      }
      printf("\n--------------------------------------------\n");
      for (int i = 0; i <= sum; i++) {
         if(i == 0)  printf("--- | ");
         else        printf("%3d | ", i);
         for (int j = 0; j <= n; j++)
            printf ("%3d ", (dp[i][j] == true) ? 1 : 0);
         printf("\n");
      }
   }
   /* Check if we should print the result backtrace          */
   if(result && print_backtrace) {
      cout << "Numbers:";
      /* Start from last row, find out which column was first*
       * set in the DP table. This is O(n lg n) algorithm    */
      for(int i = sum; i > 0;) {
         auto it = std::lower_bound(dp[i].begin(), dp[i].end(), true);
         if(*it == true) {
            int idx = it - dp[i].begin() - 1;
            i -= set[idx];
            cout << set[idx] << ",";
         }
      }
      cout << endl;
   }
   return result;
}

/* Can handle duplicates and negative numbers                */
bool subset_sum_brute(const std::vector<int>& set, int n, int sum)
{
   int idx = n-1;         /* idx is 0 based                  */
   if(sum == 0)           return true;
   if(n == 0 && sum != 0) return false;
   /* Skip out of bounds subset                              */
   if(set[idx] > sum)
      return subset_sum_brute(set, n-1, sum);
   /* 2 cases in dynamic programming:                        *
    * a) Don't include last element in calculating sum       *
    * b) Include last element in calculating sum             */
   return ( subset_sum_brute(set, n-1, sum) ||
            subset_sum_brute(set, n-1, sum - set[idx]) );
}

/* Given set size, generate elements randomly and then call  *
 * Subset sum Brute and DP algorithms                        */
bool subsetsum_tester(size_t set_size, int sum, int &cnt)
{
   std::vector<int> val(set_size);

   /* Generate vector contents randomly                      */
   fill_vector_rand(val, 0, max_item_value);

   auto dp_res    = subset_sum(val, sum);
   auto brute_res = subset_sum_brute(val, val.size(), sum);

   if(dp_res != brute_res) {
      cout << "Error: Subset failed for given input "
           << "DP = " << dp_res << " Brute = " << brute_res << endl;
      cout << "Below is the DP table result:"  << endl;
      subset_sum(val, sum, true, true);
      return false;
   }
   if(dp_res == true) cnt++;
   return true;
}

int main()
{
   int cnt = 0; /* Number of successful Subsetsum runs       */
   cout << "Running " << number_of_iterations << " iterations "
        << "each with " << number_of_items_in_iter << " items "
        << "and with max_sum=" << max_sum          << endl;
   init_rand();
   for(int i = 1; i <= number_of_iterations; i++)
      if(subsetsum_tester(number_of_items_in_iter, max_sum, cnt) == false)
         return -1;

   cout << "Info: All Subset sum test-cases completed successfully "
        << cnt << " subsets had subset's with sum " << max_sum << endl;
   return 0;
}
<|endoftext|>


<commit_before>// Copyright 2014 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 <algorithm>

#include "base/bind.h"
#include "base/debug/profiler.h"
#include "base/memory/weak_ptr.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/stringprintf.h"
#include "mojo/application/application_runner_chromium.h"
#include "mojo/public/c/system/main.h"
#include "mojo/public/cpp/application/application_delegate.h"
#include "mojo/public/cpp/application/application_impl.h"
#include "mojo/services/window_manager/public/interfaces/window_manager.mojom.h"
#include "net/base/net_errors.h"
#include "net/server/http_server.h"
#include "net/server/http_server_request_info.h"
#include "net/socket/tcp_server_socket.h"
#include "services/tracing/tracing.mojom.h"
#include "sky/tools/debugger/trace_collector.h"

namespace sky {
namespace debugger {
namespace {

const size_t kMinSendBufferSize = 1024 * 1024;
}

class SkyDebugger : public mojo::ApplicationDelegate,
                    public net::HttpServer::Delegate {
 public:
  SkyDebugger() : is_tracing_(false), weak_ptr_factory_(this) {}
  virtual ~SkyDebugger() {}

 private:
  // Overridden from mojo::ApplicationDelegate:
  virtual void Initialize(mojo::ApplicationImpl* app) override {
    app->ConnectToService("mojo:tracing", &tracing_);
    // Format: --args-for="app_url command_port"
    if (app->args().size() < 2) {
      LOG(ERROR) << "--args-for required to specify command_port";
      mojo::ApplicationImpl::Terminate();
      return;
    }

    base::StringToUint(app->args()[1], &command_port_);

    scoped_ptr<net::ServerSocket> server_socket(
        new net::TCPServerSocket(NULL, net::NetLog::Source()));
    int result =
        server_socket->ListenWithAddressAndPort("0.0.0.0", command_port_, 1);
    if (result != net::OK) {
      LOG(ERROR) << "Failed to bind to port " << command_port_
                 << " skydb commands will not work.";
      mojo::ApplicationImpl::Terminate();
      return;
    }
    web_server_.reset(new net::HttpServer(server_socket.Pass(), this));

    app->ConnectToService("mojo:window_manager", &window_manager_);
  }

  virtual bool ConfigureIncomingConnection(
      mojo::ApplicationConnection* connection) override {
    return true;
  }

  // net::HttpServer::Delegate
  void OnConnect(int connection_id) override {}

  void OnClose(int connection_id) override {}

  void OnHttpRequest(int connection_id,
                     const net::HttpServerRequestInfo& info) override {
    // FIXME: We should use use a fancier lookup system more like what
    // services/http_server/http_server.cc does with AddHandler.
    if (info.path == "/reload")
      Load(connection_id, url_);
    else if (info.path == "/quit")
      Quit(connection_id);
    else if (info.path == "/load")
      Load(connection_id, info.data);
    else if (info.path == "/start_profiling")
      StartProfiling(connection_id);
    else if (info.path == "/stop_profiling")
      StopProfiling(connection_id);
    else if (info.path == "/start_tracing")
      StartTracing(connection_id);
    else if (info.path == "/stop_tracing")
      StopTracing(connection_id);
    else
      Help(info.path, connection_id);
  }

  void OnWebSocketRequest(int connection_id,
                          const net::HttpServerRequestInfo& info) override {
    Error(connection_id, "OnWebSocketRequest not implemented");
  }

  void OnWebSocketMessage(int connection_id, const std::string& data) override {
    Error(connection_id, "OnWebSocketMessage not implemented");
  }

  void Error(int connection_id, std::string message) {
    web_server_->Send500(connection_id, message);
  }

  void Respond(int connection_id, std::string response) {
    // When sending tracing data back over the wire to the client, we can blow
    // through the default send buffer size.
    web_server_->SetSendBufferSize(
        connection_id, std::max(kMinSendBufferSize, response.length()));
    web_server_->Send200(connection_id, response, "text/plain");
  }

  void Help(std::string path, int connection_id) {
    std::string help = base::StringPrintf(
        "Sky Debugger running on port %d\n"
        "Supported URLs:\n"
        "/reload           -- Reload the current page\n"
        "/quit             -- Quit\n"
        "/load             -- Load a new URL, url in POST body.\n",
        command_port_);
    if (path != "/")
      help = "Unknown path: " + path + "\n\n" + help;
    Respond(connection_id, help);
  }

  void Load(int connection_id, std::string url) {
    url_ = url;
    Reload();
    std::string response = std::string("Loaded ") + url + "\n";
    Respond(connection_id, response);
  }

  void Reload() {
    // SimpleWindowManager will wire up necessary services on our behalf.
    window_manager_->Embed(url_, nullptr, nullptr);
  }

  void Quit(int connection_id) {
    // TODO(eseidel): We should orderly shutdown once mojo can.
    exit(0);
  }

  void StartTracing(int connection_id) {
    if (is_tracing_) {
      Error(connection_id, "Already tracing. Use stop_tracing to stop.\n");
      return;
    }

    is_tracing_ = true;
    mojo::DataPipe pipe;
    tracing_->Start(pipe.producer_handle.Pass(), mojo::String("*"));
    trace_collector_.reset(new TraceCollector(pipe.consumer_handle.Pass()));
    Respond(connection_id, "Starting trace (type 'stop_tracing' to stop)\n");
  }

  void StopTracing(int connection_id) {
    if (!is_tracing_) {
      Error(connection_id, "Not tracing yet. Use start_tracing to start.\n");
      return;
    }

    is_tracing_ = false;
    tracing_->StopAndFlush();
    trace_collector_->GetTrace(base::Bind(
        &SkyDebugger::OnTraceAvailable, base::Unretained(this), connection_id));
  }

  void OnTraceAvailable(int connection_id, std::string trace) {
    trace_collector_.reset();
    Respond(connection_id, trace);
  }

  void StartProfiling(int connection_id) {
#if !defined(NDEBUG) || !defined(ENABLE_PROFILING)
    Error(connection_id,
          "Profiling requires is_debug=false and enable_profiling=true");
    return;
#else
    base::debug::StartProfiling("sky_viewer.pprof");
    Respond(connection_id, "Starting profiling (stop with 'stop_profiling')");
#endif
  }

  void StopProfiling(int connection_id) {
    if (!base::debug::BeingProfiled()) {
      Error(connection_id, "Profiling not started");
      return;
    }
    base::debug::StopProfiling();
    Respond(connection_id, "Stopped profiling");
  }

  bool is_tracing_;
  mojo::WindowManagerPtr window_manager_;
  tracing::TraceCoordinatorPtr tracing_;
  std::string url_;
  base::WeakPtrFactory<SkyDebugger> weak_ptr_factory_;
  scoped_ptr<net::HttpServer> web_server_;
  uint32_t command_port_;

  scoped_ptr<TraceCollector> trace_collector_;

  DISALLOW_COPY_AND_ASSIGN(SkyDebugger);
};

}  // namespace debugger
}  // namespace sky

MojoResult MojoMain(MojoHandle shell_handle) {
  mojo::ApplicationRunnerChromium runner(new sky::debugger::SkyDebugger);
  runner.set_message_loop_type(base::MessageLoop::TYPE_IO);
  return runner.Run(shell_handle);
}
<commit_msg>Drop weak_ptr_factory in SkyDebugger.<commit_after>// Copyright 2014 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 <algorithm>

#include "base/bind.h"
#include "base/debug/profiler.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/stringprintf.h"
#include "mojo/application/application_runner_chromium.h"
#include "mojo/public/c/system/main.h"
#include "mojo/public/cpp/application/application_delegate.h"
#include "mojo/public/cpp/application/application_impl.h"
#include "mojo/services/window_manager/public/interfaces/window_manager.mojom.h"
#include "net/base/net_errors.h"
#include "net/server/http_server.h"
#include "net/server/http_server_request_info.h"
#include "net/socket/tcp_server_socket.h"
#include "services/tracing/tracing.mojom.h"
#include "sky/tools/debugger/trace_collector.h"

namespace sky {
namespace debugger {
namespace {

const size_t kMinSendBufferSize = 1024 * 1024;
}

class SkyDebugger : public mojo::ApplicationDelegate,
                    public net::HttpServer::Delegate {
 public:
  SkyDebugger() : is_tracing_(false) {}
  virtual ~SkyDebugger() {}

 private:
  // Overridden from mojo::ApplicationDelegate:
  virtual void Initialize(mojo::ApplicationImpl* app) override {
    app->ConnectToService("mojo:tracing", &tracing_);
    // Format: --args-for="app_url command_port"
    if (app->args().size() < 2) {
      LOG(ERROR) << "--args-for required to specify command_port";
      mojo::ApplicationImpl::Terminate();
      return;
    }

    base::StringToUint(app->args()[1], &command_port_);

    scoped_ptr<net::ServerSocket> server_socket(
        new net::TCPServerSocket(NULL, net::NetLog::Source()));
    int result =
        server_socket->ListenWithAddressAndPort("0.0.0.0", command_port_, 1);
    if (result != net::OK) {
      LOG(ERROR) << "Failed to bind to port " << command_port_
                 << " skydb commands will not work.";
      mojo::ApplicationImpl::Terminate();
      return;
    }
    web_server_.reset(new net::HttpServer(server_socket.Pass(), this));

    app->ConnectToService("mojo:window_manager", &window_manager_);
  }

  virtual bool ConfigureIncomingConnection(
      mojo::ApplicationConnection* connection) override {
    return true;
  }

  // net::HttpServer::Delegate
  void OnConnect(int connection_id) override {}

  void OnClose(int connection_id) override {}

  void OnHttpRequest(int connection_id,
                     const net::HttpServerRequestInfo& info) override {
    // FIXME: We should use use a fancier lookup system more like what
    // services/http_server/http_server.cc does with AddHandler.
    if (info.path == "/reload")
      Load(connection_id, url_);
    else if (info.path == "/quit")
      Quit(connection_id);
    else if (info.path == "/load")
      Load(connection_id, info.data);
    else if (info.path == "/start_profiling")
      StartProfiling(connection_id);
    else if (info.path == "/stop_profiling")
      StopProfiling(connection_id);
    else if (info.path == "/start_tracing")
      StartTracing(connection_id);
    else if (info.path == "/stop_tracing")
      StopTracing(connection_id);
    else
      Help(info.path, connection_id);
  }

  void OnWebSocketRequest(int connection_id,
                          const net::HttpServerRequestInfo& info) override {
    Error(connection_id, "OnWebSocketRequest not implemented");
  }

  void OnWebSocketMessage(int connection_id, const std::string& data) override {
    Error(connection_id, "OnWebSocketMessage not implemented");
  }

  void Error(int connection_id, std::string message) {
    web_server_->Send500(connection_id, message);
  }

  void Respond(int connection_id, std::string response) {
    // When sending tracing data back over the wire to the client, we can blow
    // through the default send buffer size.
    web_server_->SetSendBufferSize(
        connection_id, std::max(kMinSendBufferSize, response.length()));
    web_server_->Send200(connection_id, response, "text/plain");
  }

  void Help(std::string path, int connection_id) {
    std::string help = base::StringPrintf(
        "Sky Debugger running on port %d\n"
        "Supported URLs:\n"
        "/reload           -- Reload the current page\n"
        "/quit             -- Quit\n"
        "/load             -- Load a new URL, url in POST body.\n",
        command_port_);
    if (path != "/")
      help = "Unknown path: " + path + "\n\n" + help;
    Respond(connection_id, help);
  }

  void Load(int connection_id, std::string url) {
    url_ = url;
    Reload();
    std::string response = std::string("Loaded ") + url + "\n";
    Respond(connection_id, response);
  }

  void Reload() {
    // SimpleWindowManager will wire up necessary services on our behalf.
    window_manager_->Embed(url_, nullptr, nullptr);
  }

  void Quit(int connection_id) {
    // TODO(eseidel): We should orderly shutdown once mojo can.
    exit(0);
  }

  void StartTracing(int connection_id) {
    if (is_tracing_) {
      Error(connection_id, "Already tracing. Use stop_tracing to stop.\n");
      return;
    }

    is_tracing_ = true;
    mojo::DataPipe pipe;
    tracing_->Start(pipe.producer_handle.Pass(), mojo::String("*"));
    trace_collector_.reset(new TraceCollector(pipe.consumer_handle.Pass()));
    Respond(connection_id, "Starting trace (type 'stop_tracing' to stop)\n");
  }

  void StopTracing(int connection_id) {
    if (!is_tracing_) {
      Error(connection_id, "Not tracing yet. Use start_tracing to start.\n");
      return;
    }

    is_tracing_ = false;
    tracing_->StopAndFlush();
    trace_collector_->GetTrace(base::Bind(
        &SkyDebugger::OnTraceAvailable, base::Unretained(this), connection_id));
  }

  void OnTraceAvailable(int connection_id, std::string trace) {
    trace_collector_.reset();
    Respond(connection_id, trace);
  }

  void StartProfiling(int connection_id) {
#if !defined(NDEBUG) || !defined(ENABLE_PROFILING)
    Error(connection_id,
          "Profiling requires is_debug=false and enable_profiling=true");
    return;
#else
    base::debug::StartProfiling("sky_viewer.pprof");
    Respond(connection_id, "Starting profiling (stop with 'stop_profiling')");
#endif
  }

  void StopProfiling(int connection_id) {
    if (!base::debug::BeingProfiled()) {
      Error(connection_id, "Profiling not started");
      return;
    }
    base::debug::StopProfiling();
    Respond(connection_id, "Stopped profiling");
  }

  bool is_tracing_;
  mojo::WindowManagerPtr window_manager_;
  tracing::TraceCoordinatorPtr tracing_;
  std::string url_;
  scoped_ptr<net::HttpServer> web_server_;
  uint32_t command_port_;

  scoped_ptr<TraceCollector> trace_collector_;

  DISALLOW_COPY_AND_ASSIGN(SkyDebugger);
};

}  // namespace debugger
}  // namespace sky

MojoResult MojoMain(MojoHandle shell_handle) {
  mojo::ApplicationRunnerChromium runner(new sky::debugger::SkyDebugger);
  runner.set_message_loop_type(base::MessageLoop::TYPE_IO);
  return runner.Run(shell_handle);
}
<|endoftext|>


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

#include "chrome/browser/chromeos/compact_location_bar_host.h"

#include <algorithm>

#include "app/l10n_util.h"
#include "app/slide_animation.h"
#include "base/keyboard_codes.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/chromeos/compact_location_bar_view.h"
#include "chrome/browser/find_bar_controller.h"
#include "chrome/browser/renderer_host/render_view_host.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/browser/tab_contents/tab_contents_view.h"
#include "chrome/browser/view_ids.h"
#include "chrome/browser/views/bookmark_bar_view.h"
#include "chrome/browser/views/find_bar_view.h"
#include "chrome/browser/views/frame/browser_view.h"
#include "chrome/browser/views/tabs/tab.h"
#include "chrome/browser/views/tabs/tab_strip.h"
#include "chrome/browser/views/toolbar_star_toggle.h"
#include "views/controls/scrollbar/native_scroll_bar.h"
#include "views/focus/external_focus_tracker.h"
#include "views/focus/view_storage.h"
#include "views/widget/root_view.h"
#include "views/widget/widget.h"

namespace chromeos {
const int kDefaultLocationBarWidth = 300;
const int kHideTimeoutInSeconds = 2;

// An mouse event observer to detect a mouse click on
// BrowserView's content area and hide the location bar.
class MouseObserver : public MessageLoopForUI::Observer {
 public:
  MouseObserver(CompactLocationBarHost* host, ::BrowserView* view)
      : host_(host),
        browser_view_(view) {
    top_level_window_ = browser_view_->GetWidget()->GetNativeView()->window;
  }

  // MessageLoopForUI::Observer overrides.
  virtual void WillProcessEvent(GdkEvent* event) {}
  virtual void DidProcessEvent(GdkEvent* event) {
    // Hide the location bar iff the mouse is pressed on the
    // BrowserView's content area.
    if (top_level_window_ == gdk_window_get_toplevel(event->any.window) &&
        event->type == GDK_BUTTON_PRESS &&
        HitContentArea(event)) {
      host_->Hide(true);
    }
  }

 private:
  // Tests if the event occured on the content area, using
  // root window's coordinates.
  bool HitContentArea(GdkEvent* event) {
    gfx::Point p(event->button.x_root, event->button.y_root);
    // First, exclude the location bar as it's shown on top of
    // content area.
    if (HitOnScreen(host_->GetClbView(), p)) {
      return false;
    }
    // Treat the bookmark as a content area when it in detached mode.
    if (browser_view_->GetBookmarkBarView()->IsDetached() &&
        browser_view_->IsBookmarkBarVisible() &&
        HitOnScreen(browser_view_->GetBookmarkBarView(), p)) {
      return true;
    }
    if (HitOnScreen(browser_view_->GetContentsView(),
                    p)) {
      return true;
    }
    return false;
  }

  // Tests if |p| in the root window's coordinate is within the |view|'s bound.
  bool HitOnScreen(const views::View* view, const gfx::Point& p) {
    gfx::Point origin(0, 0);
    views::View::ConvertPointToScreen(view, &origin);
    gfx::Rect new_bounds(origin, view->size());
    return new_bounds.Contains(p);
  }

  CompactLocationBarHost* host_;
  ::BrowserView* browser_view_;
  GdkWindow* top_level_window_;

  DISALLOW_COPY_AND_ASSIGN(MouseObserver);
};

////////////////////////////////////////////////////////////////////////////////
// CompactLocationBarHost, public:

CompactLocationBarHost::CompactLocationBarHost(::BrowserView* browser_view)
    : DropdownBarHost(browser_view),
      current_tab_index_(-1) {
  auto_hide_timer_.reset(new base::OneShotTimer<CompactLocationBarHost>());
  mouse_observer_.reset(new MouseObserver(this, browser_view));
  Init(new CompactLocationBarView(this));
}

CompactLocationBarHost::~CompactLocationBarHost() {
  browser_view()->browser()->tabstrip_model()->RemoveObserver(this);
  MessageLoopForUI::current()->RemoveObserver(mouse_observer_.get());
}

void CompactLocationBarHost::StartAutoHideTimer() {
  if (!host()->IsVisible())
    return;
  if (auto_hide_timer_->IsRunning()) {
    // Restart the timer.
    auto_hide_timer_->Reset();
  } else {
    auto_hide_timer_->Start(base::TimeDelta::FromSeconds(kHideTimeoutInSeconds),
                            this, &CompactLocationBarHost::HideCallback);
  }
}

////////////////////////////////////////////////////////////////////////////////
// CompactLocationBarHost, views::AcceleratorTarget implementation:

bool CompactLocationBarHost::AcceleratorPressed(
    const views::Accelerator& accelerator) {
  Hide(true);
  return false;
}

////////////////////////////////////////////////////////////////////////////////
// CompactLocationBarHost, views::DropdownBarHost implementation:

gfx::Rect CompactLocationBarHost::GetDialogPosition(
    gfx::Rect avoid_overlapping_rect) {
  DCHECK_GE(current_tab_index_, 0);
  gfx::Rect new_pos = GetBoundsUnderTab(current_tab_index_);

  if (animation_offset() > 0)
    new_pos.Offset(0, std::min(0, -animation_offset()));
  return new_pos;
}

void CompactLocationBarHost::SetDialogPosition(const gfx::Rect& new_pos,
                                               bool no_redraw) {
  if (new_pos.IsEmpty())
    return;

  // Make sure the window edges are clipped to just the visible region. We need
  // to do this before changing position, so that when we animate the closure
  // of it it doesn't look like the window crumbles into the toolbar.
  UpdateWindowEdges(new_pos);

  // TODO(oshima): Animate the window clipping like find-bar.
  SetWidgetPositionNative(new_pos, no_redraw);
}

////////////////////////////////////////////////////////////////////////////////
// CompactLocationBarHost, views::TabStripModelObserver implementation:

void CompactLocationBarHost::TabInsertedAt(TabContents* contents,
                                           int index,
                                           bool foreground) {
  Hide(false);
  // TODO(oshima): Consult UX team if we should show the location bar.
}

void CompactLocationBarHost::TabClosingAt(TabContents* contents, int index) {
  if (IsCurrentTabIndex(index)) {
    Hide(false);
  } else {
    // TODO(oshima): We need to relocate the compact navigation bar here,
    // but the tabstrip does not have the ideal location yet
    // because the tabs are animating at this time. Need to investigate
    // the best way to handle this case.
  }
}

void CompactLocationBarHost::TabSelectedAt(TabContents* old_contents,
                                           TabContents* new_contents,
                                           int index,
                                           bool user_gesture) {
  if (user_gesture) {
    // Show the compact location bar only when a user selected the tab.
    Update(index, false);
  } else {
    Hide(false);
  }
}

void CompactLocationBarHost::TabMoved(TabContents* contents,
                                      int from_index,
                                      int to_index) {
  Update(to_index, false);
}

void CompactLocationBarHost::TabChangedAt(TabContents* contents, int index,
                                          TabChangeType change_type) {
  if (IsCurrentTabIndex(index) && IsVisible()) {
    GetClbView()->Update(contents);
  }
}

////////////////////////////////////////////////////////////////////////////////
// CompactLocationBarHost public:

gfx::Rect CompactLocationBarHost::GetBoundsUnderTab(int index) const {
  // Get the position of the left-bottom corner of the tab on the
  // widget.  The widget of the tab is same as the widget of the
  // BrowserView which is the parent of the host.
  TabStrip* tabstrip = browser_view()->tabstrip()->AsTabStrip();
  gfx::Rect bounds = tabstrip->GetIdealBounds(index);
  gfx::Rect navbar_bounds(gfx::Point(bounds.x(), bounds.height()),
                          view()->GetPreferredSize());

  // For RTL case x() defines tab right corner.
  if (l10n_util::GetTextDirection() == l10n_util::RIGHT_TO_LEFT) {
    navbar_bounds.set_x(navbar_bounds.x() + bounds.width());
  }
  navbar_bounds.set_x(navbar_bounds.x() + tabstrip->x());
  navbar_bounds.set_y(navbar_bounds.y() + tabstrip->y());

  // The compact location bar must be smaller than browser_width.
  int width = std::min(browser_view()->width(),
                       view()->GetPreferredSize().width());

  // Try to center around the tab.
  navbar_bounds.set_x(browser_view()->MirroredXCoordinateInsideView(
      navbar_bounds.x()) - ((width - bounds.width()) / 2));

  if (browser_view()->IsBookmarkBarVisible() &&
      !browser_view()->GetBookmarkBarView()->IsDetached()) {
    // Adjust the location to create the illusion that the compact location bar
    // is a part of boolmark bar.
    // TODO(oshima): compact location bar does not have right background
    // image yet, so -2 is tentative. Fix this once UI is settled.
    navbar_bounds.set_y(
        browser_view()->GetBookmarkBarView()->bounds().bottom() - 2);
  }
  return navbar_bounds.AdjustToFit(browser_view()->bounds());
}

void CompactLocationBarHost::Update(int index, bool animate_x) {
  DCHECK_GE(index, 0);
  if (IsCurrentTabIndex(index) && IsVisible()) {
    return;
  }
  current_tab_index_ = index;
  // Don't aminate if the bar is already shown.
  bool animate = !animation()->IsShowing();
  Hide(false);
  GetClbView()->Update(browser_view()->browser()->GetSelectedTabContents());
  GetClbView()->SetFocusAndSelection();
  Show(animate && animate_x);
}

void CompactLocationBarHost::CancelAutoHideTimer() {
  auto_hide_timer_->Stop();
}

void CompactLocationBarHost::SetEnabled(bool enabled) {
  if (enabled) {
    browser_view()->browser()->tabstrip_model()->AddObserver(this);
  } else {
    browser_view()->browser()->tabstrip_model()->RemoveObserver(this);
  }
}

ToolbarStarToggle* CompactLocationBarHost::GetStarButton() {
  return GetClbView()->star_button();
}

void CompactLocationBarHost::Show(bool a) {
  MessageLoopForUI::current()->AddObserver(mouse_observer_.get());
  DropdownBarHost::Show(a);
}

void CompactLocationBarHost::Hide(bool a) {
  MessageLoopForUI::current()->RemoveObserver(mouse_observer_.get());
  DropdownBarHost::Hide(a);
}

////////////////////////////////////////////////////////////////////////////////
// CompactLocationBarHost private:

CompactLocationBarView* CompactLocationBarHost::GetClbView() {
  return static_cast<CompactLocationBarView*>(view());
}

bool CompactLocationBarHost::IsCurrentTabIndex(int index) {
  return current_tab_index_ == index;
}

}  // namespace chromeos
<commit_msg>Fix a crash when a moust observer got a mouse event on a wnidow that has already been destroyed.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/chromeos/compact_location_bar_host.h"

#include <algorithm>

#include "app/l10n_util.h"
#include "app/slide_animation.h"
#include "base/keyboard_codes.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/chromeos/compact_location_bar_view.h"
#include "chrome/browser/find_bar_controller.h"
#include "chrome/browser/renderer_host/render_view_host.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/browser/tab_contents/tab_contents_view.h"
#include "chrome/browser/view_ids.h"
#include "chrome/browser/views/bookmark_bar_view.h"
#include "chrome/browser/views/find_bar_view.h"
#include "chrome/browser/views/frame/browser_view.h"
#include "chrome/browser/views/tabs/tab.h"
#include "chrome/browser/views/tabs/tab_strip.h"
#include "chrome/browser/views/toolbar_star_toggle.h"
#include "views/controls/scrollbar/native_scroll_bar.h"
#include "views/focus/external_focus_tracker.h"
#include "views/focus/view_storage.h"
#include "views/widget/root_view.h"
#include "views/widget/widget.h"

namespace chromeos {
const int kDefaultLocationBarWidth = 300;
const int kHideTimeoutInSeconds = 2;

// An mouse event observer to detect a mouse click on
// BrowserView's content area and hide the location bar.
class MouseObserver : public MessageLoopForUI::Observer {
 public:
  MouseObserver(CompactLocationBarHost* host, ::BrowserView* view)
      : host_(host),
        browser_view_(view) {
    top_level_window_ = browser_view_->GetWidget()->GetNativeView()->window;
  }

  // MessageLoopForUI::Observer overrides.
  virtual void WillProcessEvent(GdkEvent* event) {}
  virtual void DidProcessEvent(GdkEvent* event) {
    // Hide the location bar iff the mouse is pressed on the
    // BrowserView's content area.
    if (event->type == GDK_BUTTON_PRESS &&
        GDK_IS_WINDOW(event->any.window) &&
        top_level_window_ == gdk_window_get_toplevel(event->any.window) &&
        HitContentArea(event)) {
      host_->Hide(true);
    }
  }

 private:
  // Tests if the event occured on the content area, using
  // root window's coordinates.
  bool HitContentArea(GdkEvent* event) {
    gfx::Point p(event->button.x_root, event->button.y_root);
    // First, exclude the location bar as it's shown on top of
    // content area.
    if (HitOnScreen(host_->GetClbView(), p)) {
      return false;
    }
    // Treat the bookmark as a content area when it in detached mode.
    if (browser_view_->GetBookmarkBarView()->IsDetached() &&
        browser_view_->IsBookmarkBarVisible() &&
        HitOnScreen(browser_view_->GetBookmarkBarView(), p)) {
      return true;
    }
    if (HitOnScreen(browser_view_->GetContentsView(),
                    p)) {
      return true;
    }
    return false;
  }

  // Tests if |p| in the root window's coordinate is within the |view|'s bound.
  bool HitOnScreen(const views::View* view, const gfx::Point& p) {
    gfx::Point origin(0, 0);
    views::View::ConvertPointToScreen(view, &origin);
    gfx::Rect new_bounds(origin, view->size());
    return new_bounds.Contains(p);
  }

  CompactLocationBarHost* host_;
  ::BrowserView* browser_view_;
  GdkWindow* top_level_window_;

  DISALLOW_COPY_AND_ASSIGN(MouseObserver);
};

////////////////////////////////////////////////////////////////////////////////
// CompactLocationBarHost, public:

CompactLocationBarHost::CompactLocationBarHost(::BrowserView* browser_view)
    : DropdownBarHost(browser_view),
      current_tab_index_(-1) {
  auto_hide_timer_.reset(new base::OneShotTimer<CompactLocationBarHost>());
  mouse_observer_.reset(new MouseObserver(this, browser_view));
  Init(new CompactLocationBarView(this));
}

CompactLocationBarHost::~CompactLocationBarHost() {
  browser_view()->browser()->tabstrip_model()->RemoveObserver(this);
  MessageLoopForUI::current()->RemoveObserver(mouse_observer_.get());
}

void CompactLocationBarHost::StartAutoHideTimer() {
  if (!host()->IsVisible())
    return;
  if (auto_hide_timer_->IsRunning()) {
    // Restart the timer.
    auto_hide_timer_->Reset();
  } else {
    auto_hide_timer_->Start(base::TimeDelta::FromSeconds(kHideTimeoutInSeconds),
                            this, &CompactLocationBarHost::HideCallback);
  }
}

////////////////////////////////////////////////////////////////////////////////
// CompactLocationBarHost, views::AcceleratorTarget implementation:

bool CompactLocationBarHost::AcceleratorPressed(
    const views::Accelerator& accelerator) {
  Hide(true);
  return false;
}

////////////////////////////////////////////////////////////////////////////////
// CompactLocationBarHost, views::DropdownBarHost implementation:

gfx::Rect CompactLocationBarHost::GetDialogPosition(
    gfx::Rect avoid_overlapping_rect) {
  DCHECK_GE(current_tab_index_, 0);
  gfx::Rect new_pos = GetBoundsUnderTab(current_tab_index_);

  if (animation_offset() > 0)
    new_pos.Offset(0, std::min(0, -animation_offset()));
  return new_pos;
}

void CompactLocationBarHost::SetDialogPosition(const gfx::Rect& new_pos,
                                               bool no_redraw) {
  if (new_pos.IsEmpty())
    return;

  // Make sure the window edges are clipped to just the visible region. We need
  // to do this before changing position, so that when we animate the closure
  // of it it doesn't look like the window crumbles into the toolbar.
  UpdateWindowEdges(new_pos);

  // TODO(oshima): Animate the window clipping like find-bar.
  SetWidgetPositionNative(new_pos, no_redraw);
}

////////////////////////////////////////////////////////////////////////////////
// CompactLocationBarHost, views::TabStripModelObserver implementation:

void CompactLocationBarHost::TabInsertedAt(TabContents* contents,
                                           int index,
                                           bool foreground) {
  Hide(false);
  // TODO(oshima): Consult UX team if we should show the location bar.
}

void CompactLocationBarHost::TabClosingAt(TabContents* contents, int index) {
  if (IsCurrentTabIndex(index)) {
    Hide(false);
  } else {
    // TODO(oshima): We need to relocate the compact navigation bar here,
    // but the tabstrip does not have the ideal location yet
    // because the tabs are animating at this time. Need to investigate
    // the best way to handle this case.
  }
}

void CompactLocationBarHost::TabSelectedAt(TabContents* old_contents,
                                           TabContents* new_contents,
                                           int index,
                                           bool user_gesture) {
  if (user_gesture) {
    // Show the compact location bar only when a user selected the tab.
    Update(index, false);
  } else {
    Hide(false);
  }
}

void CompactLocationBarHost::TabMoved(TabContents* contents,
                                      int from_index,
                                      int to_index) {
  Update(to_index, false);
}

void CompactLocationBarHost::TabChangedAt(TabContents* contents, int index,
                                          TabChangeType change_type) {
  if (IsCurrentTabIndex(index) && IsVisible()) {
    GetClbView()->Update(contents);
  }
}

////////////////////////////////////////////////////////////////////////////////
// CompactLocationBarHost public:

gfx::Rect CompactLocationBarHost::GetBoundsUnderTab(int index) const {
  // Get the position of the left-bottom corner of the tab on the
  // widget.  The widget of the tab is same as the widget of the
  // BrowserView which is the parent of the host.
  TabStrip* tabstrip = browser_view()->tabstrip()->AsTabStrip();
  gfx::Rect bounds = tabstrip->GetIdealBounds(index);
  gfx::Rect navbar_bounds(gfx::Point(bounds.x(), bounds.height()),
                          view()->GetPreferredSize());

  // For RTL case x() defines tab right corner.
  if (l10n_util::GetTextDirection() == l10n_util::RIGHT_TO_LEFT) {
    navbar_bounds.set_x(navbar_bounds.x() + bounds.width());
  }
  navbar_bounds.set_x(navbar_bounds.x() + tabstrip->x());
  navbar_bounds.set_y(navbar_bounds.y() + tabstrip->y());

  // The compact location bar must be smaller than browser_width.
  int width = std::min(browser_view()->width(),
                       view()->GetPreferredSize().width());

  // Try to center around the tab.
  navbar_bounds.set_x(browser_view()->MirroredXCoordinateInsideView(
      navbar_bounds.x()) - ((width - bounds.width()) / 2));

  if (browser_view()->IsBookmarkBarVisible() &&
      !browser_view()->GetBookmarkBarView()->IsDetached()) {
    // Adjust the location to create the illusion that the compact location bar
    // is a part of boolmark bar.
    // TODO(oshima): compact location bar does not have right background
    // image yet, so -2 is tentative. Fix this once UI is settled.
    navbar_bounds.set_y(
        browser_view()->GetBookmarkBarView()->bounds().bottom() - 2);
  }
  return navbar_bounds.AdjustToFit(browser_view()->bounds());
}

void CompactLocationBarHost::Update(int index, bool animate_x) {
  DCHECK_GE(index, 0);
  if (IsCurrentTabIndex(index) && IsVisible()) {
    return;
  }
  current_tab_index_ = index;
  // Don't aminate if the bar is already shown.
  bool animate = !animation()->IsShowing();
  Hide(false);
  GetClbView()->Update(browser_view()->browser()->GetSelectedTabContents());
  GetClbView()->SetFocusAndSelection();
  Show(animate && animate_x);
}

void CompactLocationBarHost::CancelAutoHideTimer() {
  auto_hide_timer_->Stop();
}

void CompactLocationBarHost::SetEnabled(bool enabled) {
  if (enabled) {
    browser_view()->browser()->tabstrip_model()->AddObserver(this);
  } else {
    browser_view()->browser()->tabstrip_model()->RemoveObserver(this);
  }
}

ToolbarStarToggle* CompactLocationBarHost::GetStarButton() {
  return GetClbView()->star_button();
}

void CompactLocationBarHost::Show(bool a) {
  MessageLoopForUI::current()->AddObserver(mouse_observer_.get());
  DropdownBarHost::Show(a);
}

void CompactLocationBarHost::Hide(bool a) {
  MessageLoopForUI::current()->RemoveObserver(mouse_observer_.get());
  DropdownBarHost::Hide(a);
}

////////////////////////////////////////////////////////////////////////////////
// CompactLocationBarHost private:

CompactLocationBarView* CompactLocationBarHost::GetClbView() {
  return static_cast<CompactLocationBarView*>(view());
}

bool CompactLocationBarHost::IsCurrentTabIndex(int index) {
  return current_tab_index_ == index;
}

}  // namespace chromeos
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2010-2014, Delft University of Technology
 * Copyright (c) 2010-2014, K. Kumar (me@kartikkumar.com)
 * All rights reserved.
 * See http://bit.ly/12SHPLR for license details.
 */

#include <cstdlib>
#include <iostream>
#include <string>

#include <boost/algorithm/string/predicate.hpp>

#include <Assist/InputOutput/basicInputOutput.h>

#include <Tudat/InputOutput/dictionaryTools.h>
#include <Tudat/InputOutput/fieldType.h>
#include <Tudat/InputOutput/separatedParser.h>
#include <Tudat/InputOutput/parsedDataVectorUtilities.h>

#include "Stomi/ApplicationModes/randomWalkDatabaseGenerator.h"
#include "Stomi/ApplicationModes/randomWalkSimulator.h"
#include "Stomi/ApplicationModes/testParticleDatabaseGenerator.h"
#include "Stomi/ApplicationModes/testParticleSimulator.h"
#include "Stomi/InputOutput/dictionaries.h"

//! Execute Stomi.
int main( const int numberOfInputs, const char* inputArguments[ ] )
{
    ///////////////////////////////////////////////////////////////////////////

    // Declare using-statements.
    using std::cout;
    using std::endl;
    using std::string;

    using boost::iequals;

    using namespace assist::input_output;

    using namespace tudat::input_output;
    using namespace tudat::input_output::dictionary;
    using namespace tudat::input_output::field_types::general;
    using namespace tudat::input_output::parsed_data_vector_utilities;

    using namespace stomi::application_modes;
    using namespace stomi::input_output;

    ///////////////////////////////////////////////////////////////////////////

    ///////////////////////////////////////////////////////////////////////////

    // Set up input deck.

    // Check number of input parameters is correct (the numberOfInputs variable includes the
    // application itself, so one is subtracted from this number).
    checkNumberOfInputArguments( numberOfInputs - 1 );

    // Read and filter input stream (this can't be declared const because the parser's parse
    // function is not const-correct at the moment).
    string filteredInput = readAndFilterInputFile( inputArguments[ 1 ] );

    // Declare a separated parser.
    SeparatedParser parser( string( ": " ), 2, parameterName, parameterValue );

    // Parse filtered data.
    const ParsedDataVectorPtr parsedData = parser.parse( filteredInput );

    // Get general parameters dictionary.
    DictionaryPointer dictionary = getGeneralParametersDictionary( );

    // Extract application mode.
    const string applicationMode = extractParameterValue< string >(
                parsedData->begin( ), parsedData->end( ), findEntry( dictionary, "MODE" ) );

    const string databasePath = extractParameterValue< string >(
                parsedData->begin( ), parsedData->end( ),
                findEntry( dictionary, "DATABASEPATH" ) );

    ///////////////////////////////////////////////////////////////////////////

    ///////////////////////////////////////////////////////////////////////////

    // Call selected application mode.
    cout << endl;
    cout << "Application mode                                          ";

    if ( iequals( applicationMode, "TPDB" ) )
    {
        cout << "TEST PARTICLE DATABASE GENERATOR" << endl;
        executeTestParticleDatabaseGenerator( databasePath, parsedData );
    }

    else if ( iequals( applicationMode, "TPSIM" ) )
    {
        cout << "TEST PARTICLE SIMULATOR" << endl;
        executeTestParticleSimulator( databasePath, parsedData );
    }

    else if ( iequals( applicationMode, "RWDB" ) )
    {
        cout << "RANDOM WALK DATABASE GENERATOR" << endl;
        executeRandomWalkDatabaseGenerator( databasePath, parsedData );
    }

    else if ( iequals( applicationMode, "RWSIM" ) )
    {
        cout << "RANDOM WALK SIMULATOR" << endl;
        executeRandomWalkSimulator( databasePath, parsedData );
    }

    cout << endl;

    ///////////////////////////////////////////////////////////////////////////

    ///////////////////////////////////////////////////////////////////////////

    // If program is successfully completed, return 0.
    return EXIT_SUCCESS;

    ///////////////////////////////////////////////////////////////////////////
}

/*
 *    TODO:
 *      - encapsulate code in try-catch blocks to capture exceptions.
 *      - execute verification of existing data against input parameters provided to ensure
 *        consistency of inputs and possibly warn user.
 *      - expand code to enable interactive interface for user to provide inputs and select
 *        options (capture command line user input).
 */
<commit_msg>Update Stomi application to throw error if application mode is not recognized. Add header printed to console when Stomi is executed.<commit_after>/*
 * Copyright (c) 2010-2014, Delft University of Technology
 * Copyright (c) 2010-2014, K. Kumar (me@kartikkumar.com)
 * All rights reserved.
 * See http://bit.ly/12SHPLR for license details.
 */

#include <cstdlib>
#include <iostream>
#include <stdexcept>
#include <string>

#include <boost/algorithm/string/predicate.hpp>

#include <Assist/InputOutput/basicInputOutput.h>

#include <Tudat/InputOutput/dictionaryTools.h>
#include <Tudat/InputOutput/fieldType.h>
#include <Tudat/InputOutput/separatedParser.h>
#include <Tudat/InputOutput/parsedDataVectorUtilities.h>

#include "Stomi/ApplicationModes/randomWalkDatabaseGenerator.h"
#include "Stomi/ApplicationModes/randomWalkSimulator.h"
#include "Stomi/ApplicationModes/testParticleDatabaseGenerator.h"
#include "Stomi/ApplicationModes/testParticleSimulator.h"
#include "Stomi/InputOutput/dictionaries.h"

//! Execute Stomi.
int main( const int numberOfInputs, const char* inputArguments[ ] )
{
    ///////////////////////////////////////////////////////////////////////////

    // Declare using-statements.
    using std::cout;
    using std::endl;
    using std::runtime_error;
    using std::string;

    using boost::iequals;

    using namespace assist::input_output;

    using namespace tudat::input_output;
    using namespace tudat::input_output::dictionary;
    using namespace tudat::input_output::field_types::general;
    using namespace tudat::input_output::parsed_data_vector_utilities;

    using namespace stomi::application_modes;
    using namespace stomi::input_output;

    ///////////////////////////////////////////////////////////////////////////

    ///////////////////////////////////////////////////////////////////////////

    // Set up input deck.

    // Check number of input parameters is correct (the numberOfInputs variable includes the
    // application itself, so one is subtracted from this number).
    checkNumberOfInputArguments( numberOfInputs - 1 );

    // Read and filter input stream (this can't be declared const because the parser's parse
    // function is not const-correct at the moment).
    string filteredInput = readAndFilterInputFile( inputArguments[ 1 ] );

    // Declare a separated parser.
    SeparatedParser parser( string( ": " ), 2, parameterName, parameterValue );

    // Parse filtered data.
    const ParsedDataVectorPtr parsedData = parser.parse( filteredInput );

    // Get general parameters dictionary.
    DictionaryPointer dictionary = getGeneralParametersDictionary( );

    // Extract application mode.
    const string applicationMode = extractParameterValue< string >(
                parsedData->begin( ), parsedData->end( ), findEntry( dictionary, "MODE" ) );

    const string databasePath = extractParameterValue< string >(
                parsedData->begin( ), parsedData->end( ),
                findEntry( dictionary, "DATABASEPATH" ) );

    ///////////////////////////////////////////////////////////////////////////

    ///////////////////////////////////////////////////////////////////////////

    // Call selected application mode.
    cout << endl;
    cout << "----------------------------------------------------------" << endl;
    cout << endl;
    cout << "                          STOMI                           " << endl;
    cout << "                          2.0.0                           " << endl;
    cout << endl;
    cout << " Copyright (c) 2010-2014, Delft University of Technology  " << endl;
    cout << " Copyright (c) 2010-2014, K. Kumar (me@kartikkumar.com)   " << endl;
    cout << endl;
    cout << "----------------------------------------------------------" << endl;

    cout << endl;
    cout << "Application mode                                          ";

    if ( iequals( applicationMode, "TPDB" ) )
    {
        cout << "TEST PARTICLE DATABASE GENERATOR" << endl;
        executeTestParticleDatabaseGenerator( databasePath, parsedData );
    }

    else if ( iequals( applicationMode, "TPSIM" ) )
    {
        cout << "TEST PARTICLE SIMULATOR" << endl;
        executeTestParticleSimulator( databasePath, parsedData );
    }

    else if ( iequals( applicationMode, "RWDB" ) )
    {
        cout << "RANDOM WALK DATABASE GENERATOR" << endl;
        executeRandomWalkDatabaseGenerator( databasePath, parsedData );
    }

    else if ( iequals( applicationMode, "RWSIM" ) )
    {
        cout << "RANDOM WALK SIMULATOR" << endl;
        executeRandomWalkSimulator( databasePath, parsedData );
    }

    else
    {
        throw runtime_error( "ERROR: Application mode not recognized!" );
    }

    cout << endl;

    ///////////////////////////////////////////////////////////////////////////

    ///////////////////////////////////////////////////////////////////////////

    // If program is successfully completed, return 0.
    return EXIT_SUCCESS;

    ///////////////////////////////////////////////////////////////////////////
}

/*
 *    TODO:
 *      - encapsulate code in try-catch blocks to capture exceptions.
 *      - execute verification of existing data against input parameters provided to ensure
 *        consistency of inputs and possibly warn user.
 *      - expand code to enable interactive interface for user to provide inputs and select
 *        options (capture command line user input).
 */
<|endoftext|>


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

#include "chrome/browser/chromeos/login/webui_login_display.h"

#include "chrome/browser/chromeos/login/webui_login_view.h"
#include "chrome/browser/chromeos/wm_ipc.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/browser/ui/browser_window.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"
#include "ui/base/l10n/l10n_util.h"
#include "views/widget/widget.h"

#if defined(TOUCH_UI)
#include "chrome/browser/chromeos/login/touch_login_view.h"
#endif

namespace chromeos {

// WebUILoginDisplay, public: --------------------------------------------------

WebUILoginDisplay::~WebUILoginDisplay() {
}

// WebUILoginDisplay, Singleton implementation: --------------------------------

// static
WebUILoginDisplay* WebUILoginDisplay::GetInstance() {
  return Singleton<WebUILoginDisplay>::get();
}

// LoginDisplay implementation: ------------------------------------------------

// static
views::Widget* WebUILoginDisplay::GetLoginWindow() {
  return WebUILoginDisplay::GetInstance()->LoginWindow();
}

views::Widget* WebUILoginDisplay::LoginWindow() {
  return login_window_;
}

void WebUILoginDisplay::Destroy() {
  background_bounds_ = gfx::Rect();
  delegate_ = NULL;
}

  // TODO(rharrison): Add mechanism to pass in the show_guest and show_new_user
  // values.
void WebUILoginDisplay::Init(const std::vector<UserManager::User>& users,
                             bool show_guest,
                             bool show_new_user) {
  // Testing that the delegate has been set.
  DCHECK(delegate_);
  users_ = users;
}

void WebUILoginDisplay::OnBeforeUserRemoved(const std::string& username) {
  // TODO(rharrison): Figure out if I need to split anything between this and
  // OnUserRemoved
}

void WebUILoginDisplay::OnUserImageChanged(UserManager::User* user) {
  // TODO(rharrison): Update the user in the user vector
  // TODO(rharrison): Push the change to WebUI Login screen
}

void WebUILoginDisplay::OnUserRemoved(const std::string& username) {
  // TODO(rharrison): Remove the user from the user vector
  // TODO(rharrison): Push the change to WebUI Login screen
}

void WebUILoginDisplay::OnFadeOut() { }

void WebUILoginDisplay::SetUIEnabled(bool is_enabled) {
  // Send message to WM to enable/disable click on windows.
  WmIpc::Message message(WM_IPC_MESSAGE_WM_SET_LOGIN_STATE);
  message.set_param(0, is_enabled);
  WmIpc::instance()->SendMessage(message);

  if (is_enabled)
    login_handler_->ClearAndEnablePassword();
}

void WebUILoginDisplay::SelectPod(int index) {
  // TODO(rharrison): Figure out what we should be doing here.
}

void WebUILoginDisplay::ShowError(int error_msg_id,
                                  int login_attempts,
                                  HelpAppLauncher::HelpTopic help_topic_id) {
  DCHECK(login_handler_);

  std::string error_text;
  switch (error_msg_id) {
    case IDS_LOGIN_ERROR_AUTHENTICATING_HOSTED:
      error_text = l10n_util::GetStringFUTF8(
          error_msg_id, l10n_util::GetStringUTF16(IDS_PRODUCT_OS_NAME));
      break;
    case IDS_LOGIN_ERROR_CAPTIVE_PORTAL:
      error_text = l10n_util::GetStringFUTF8(
          error_msg_id, delegate()->GetConnectedNetworkName());
      break;
    default:
      error_text = l10n_util::GetStringUTF8(error_msg_id);
      break;
  }

  std::string help_link;
  switch (error_msg_id) {
    case IDS_LOGIN_ERROR_CAPTIVE_PORTAL:
      help_link = l10n_util::GetStringUTF8(IDS_LOGIN_FIX_CAPTIVE_PORTAL);
      break;
    case IDS_LOGIN_ERROR_CAPTIVE_PORTAL_NO_GUEST_MODE:
      // No help link is needed.
      break;
    case IDS_LOGIN_ERROR_AUTHENTICATING_HOSTED:
      help_link = l10n_util::GetStringUTF8(IDS_LEARN_MORE);
      break;
    default:
      if (login_attempts > 1)
        help_link = l10n_util::GetStringUTF8(IDS_LEARN_MORE);
      break;
  }

  login_handler_->ShowError(error_text, help_link, help_topic_id);
}

// WebUILoginDisplay, LoginUIHandlerDelegate implementation: -------------------

void WebUILoginDisplay::Login(const std::string& username,
                              const std::string& password) {
  DCHECK(delegate_);
  delegate_->Login(username, password);
}

void WebUILoginDisplay::LoginAsGuest() {
  DCHECK(delegate_);
  delegate_->LoginAsGuest();
}

// WebUILoginDisplay, private: -------------------------------------------------

// Singleton implementation: ---------------------------------------------------

WebUILoginDisplay::WebUILoginDisplay()
    : LoginDisplay(NULL, gfx::Rect()),
      LoginUIHandlerDelegate(),
      login_window_(NULL) {
}

}  // namespace chromeos
<commit_msg>removed unused include<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/chromeos/login/webui_login_display.h"

#include "chrome/browser/chromeos/login/webui_login_view.h"
#include "chrome/browser/chromeos/wm_ipc.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/browser/ui/browser_window.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"
#include "ui/base/l10n/l10n_util.h"
#include "views/widget/widget.h"

namespace chromeos {

// WebUILoginDisplay, public: --------------------------------------------------

WebUILoginDisplay::~WebUILoginDisplay() {
}

// WebUILoginDisplay, Singleton implementation: --------------------------------

// static
WebUILoginDisplay* WebUILoginDisplay::GetInstance() {
  return Singleton<WebUILoginDisplay>::get();
}

// LoginDisplay implementation: ------------------------------------------------

// static
views::Widget* WebUILoginDisplay::GetLoginWindow() {
  return WebUILoginDisplay::GetInstance()->LoginWindow();
}

views::Widget* WebUILoginDisplay::LoginWindow() {
  return login_window_;
}

void WebUILoginDisplay::Destroy() {
  background_bounds_ = gfx::Rect();
  delegate_ = NULL;
}

  // TODO(rharrison): Add mechanism to pass in the show_guest and show_new_user
  // values.
void WebUILoginDisplay::Init(const std::vector<UserManager::User>& users,
                             bool show_guest,
                             bool show_new_user) {
  // Testing that the delegate has been set.
  DCHECK(delegate_);
  users_ = users;
}

void WebUILoginDisplay::OnBeforeUserRemoved(const std::string& username) {
  // TODO(rharrison): Figure out if I need to split anything between this and
  // OnUserRemoved
}

void WebUILoginDisplay::OnUserImageChanged(UserManager::User* user) {
  // TODO(rharrison): Update the user in the user vector
  // TODO(rharrison): Push the change to WebUI Login screen
}

void WebUILoginDisplay::OnUserRemoved(const std::string& username) {
  // TODO(rharrison): Remove the user from the user vector
  // TODO(rharrison): Push the change to WebUI Login screen
}

void WebUILoginDisplay::OnFadeOut() { }

void WebUILoginDisplay::SetUIEnabled(bool is_enabled) {
  // Send message to WM to enable/disable click on windows.
  WmIpc::Message message(WM_IPC_MESSAGE_WM_SET_LOGIN_STATE);
  message.set_param(0, is_enabled);
  WmIpc::instance()->SendMessage(message);

  if (is_enabled)
    login_handler_->ClearAndEnablePassword();
}

void WebUILoginDisplay::SelectPod(int index) {
  // TODO(rharrison): Figure out what we should be doing here.
}

void WebUILoginDisplay::ShowError(int error_msg_id,
                                  int login_attempts,
                                  HelpAppLauncher::HelpTopic help_topic_id) {
  DCHECK(login_handler_);

  std::string error_text;
  switch (error_msg_id) {
    case IDS_LOGIN_ERROR_AUTHENTICATING_HOSTED:
      error_text = l10n_util::GetStringFUTF8(
          error_msg_id, l10n_util::GetStringUTF16(IDS_PRODUCT_OS_NAME));
      break;
    case IDS_LOGIN_ERROR_CAPTIVE_PORTAL:
      error_text = l10n_util::GetStringFUTF8(
          error_msg_id, delegate()->GetConnectedNetworkName());
      break;
    default:
      error_text = l10n_util::GetStringUTF8(error_msg_id);
      break;
  }

  std::string help_link;
  switch (error_msg_id) {
    case IDS_LOGIN_ERROR_CAPTIVE_PORTAL:
      help_link = l10n_util::GetStringUTF8(IDS_LOGIN_FIX_CAPTIVE_PORTAL);
      break;
    case IDS_LOGIN_ERROR_CAPTIVE_PORTAL_NO_GUEST_MODE:
      // No help link is needed.
      break;
    case IDS_LOGIN_ERROR_AUTHENTICATING_HOSTED:
      help_link = l10n_util::GetStringUTF8(IDS_LEARN_MORE);
      break;
    default:
      if (login_attempts > 1)
        help_link = l10n_util::GetStringUTF8(IDS_LEARN_MORE);
      break;
  }

  login_handler_->ShowError(error_text, help_link, help_topic_id);
}

// WebUILoginDisplay, LoginUIHandlerDelegate implementation: -------------------

void WebUILoginDisplay::Login(const std::string& username,
                              const std::string& password) {
  DCHECK(delegate_);
  delegate_->Login(username, password);
}

void WebUILoginDisplay::LoginAsGuest() {
  DCHECK(delegate_);
  delegate_->LoginAsGuest();
}

// WebUILoginDisplay, private: -------------------------------------------------

// Singleton implementation: ---------------------------------------------------

WebUILoginDisplay::WebUILoginDisplay()
    : LoginDisplay(NULL, gfx::Rect()),
      LoginUIHandlerDelegate(),
      login_window_(NULL) {
}

}  // namespace chromeos
<|endoftext|>