<commit_before>#include "../include/QLearn.h"

#include <stdlib.h>
#include <iostream>
#include <fstream>
#include <chrono>
#include <thread>
#include <algorithm>

#include "../include/NeuralNet.h"

using namespace rl;

QLearn::QLearn(net::NeuralNet *modelNetwork, net::Backpropagation backprop_, double learningRate_, double devaluationFactor_, std::vector<Action> possibleActions_) {
	backprop = backprop_;
	learningRate = learningRate_;
	devaluationFactor = devaluationFactor_;

	models = std::vector<Model>(possibleActions_.size());
	for(int a = 0; a < possibleActions_.size(); a++) models.push_back(Model(new net::NeuralNet(modelNetwork), possibleActions_[a]));
}

QLearn::QLearn(std::vector<Model> models_, net::Backpropagation backprop_, double learningRate_, double devaluationFactor_) {
	models = models_;
	backprop = backprop_;
	learningRate = learningRate_;
	devaluationFactor = devaluationFactor_;
}

QLearn::QLearn() {

}

Action QLearn::chooseBestAction(State currentState) {
	lastState = currentState;

	std::vector<double> rewards = getModelRewards(currentState);
	lastModel = models[std::max_element(rewards.begin(), rewards.end()) - rewards.begin()];
	return lastModel.action;
}

Action QLearn::chooseBoltzmanAction(State currentState, double explorationConstant) {
	if(explorationConstant < 0.01) {
		std::cout << "Exploration constant (" << explorationConstant << ") is below 0.01. This is too low!. Will cause integer over flow. Assuming an explorationConstant of 0.01 instead.";
		explorationConstant = 0.01;
	}

	double determiner = (double)rand() / (double)RAND_MAX;

	std::vector<double> rewards = getModelRewards(currentState);

	std::vector<double> exponentTerms(models.size());
	double sumOfExponentTerms = 0;
	std::for_each(rewards.begin(), rewards.end(), [&](double reward){
		double exponentTerm = exp(reward / explorationConstant);
		exponentTerms.push_back(exponentTerm);
		sumOfExponentTerms += exponentTerm;
	});

	double sumOfProbabilities = 0;
	for(int a = 0; a < exponentTerms.size(); a++) {
		sumOfProbabilities += (exponentTerms[a] / sumOfExponentTerms);
		if(sumOfProbabilities >= determiner) {
			lastModel = models[a];
			lastState = currentState;
			return lastModel.action;
		}
	}

	/// Incase a floating point error resulted in no action
	std::cout << "Floating point error when choosing an action using a Boltzmann selection policy! Choosing last action.";

	lastModel = models[models.size() - 1];
	lastState = currentState;
	return lastModel.action;
}

void QLearn::applyReinforcementToLastAction(double reward, State newState) {
	if(lastState.size() == 0) {
		std::cout << "Called applyReinforcementToLastAction before an action had been selected! Because of this, this function call will be ignored.";
	}

	double lr = lastModel.network->getOutput(lastState)[0];
	double targetValueForLastState = lr + learningRate*(reward+(devaluationFactor*getHighestReward(newState))-lr);

	lastModel.addToHistory(std::pair<State, double>(lastState, targetValueForLastState));

	std::vector< std::vector<double> > input;
	std::vector< std::vector<double> > correctOutput;

	std::transform(lastModel.history.begin(), lastModel.history.end(), std::back_inserter(input), [](std::pair<State, double> entry) {
		return entry.first;
	});
	std::transform(lastModel.history.begin(), lastModel.history.end(), std::back_inserter(correctOutput), [](std::pair<State, double> entry) {
		std::vector<double> returnVal = {entry.second};
		return returnVal;
	});

	backprop.train(lastModel.network, input, correctOutput);
}

void QLearn::reset() {
	std::for_each(models.begin(), models.end(), [&](Model model) {
		model.network->randomizeWeights();
	});
}

std::vector<double> QLearn::getModelRewards(State state) {
	std::vector<double> rewards;
	std::for_each(models.begin(), models.end(), [&](Model model){
		rewards.push_back(model.network->getOutput(state)[0]);
	});

	return rewards;
}

double QLearn::getHighestReward(State state) {
	std::vector<double> rewards = getModelRewards(state);
	return *std::max_element(rewards.begin(), rewards.end());
}<commit_msg>Fixes to discrete<commit_after>#include "../include/QLearn.h"

#include <stdlib.h>
#include <iostream>
#include <fstream>
#include <chrono>
#include <thread>
#include <algorithm>

#include "../include/NeuralNet.h"

using namespace rl;

QLearn::QLearn(net::NeuralNet *modelNetwork, net::Backpropagation backprop_, double learningRate_, double devaluationFactor_, std::vector<Action> possibleActions_) {
	backprop = backprop_;
	learningRate = learningRate_;
	devaluationFactor = devaluationFactor_;

	models = std::vector<Model>(possibleActions_.size());
	for(int a = 0; a < possibleActions_.size(); a++) models[a] = (Model(new net::NeuralNet(modelNetwork), possibleActions_[a]));
}

QLearn::QLearn(std::vector<Model> models_, net::Backpropagation backprop_, double learningRate_, double devaluationFactor_) {
	models = models_;
	backprop = backprop_;
	learningRate = learningRate_;
	devaluationFactor = devaluationFactor_;
}

QLearn::QLearn() {

}

Action QLearn::chooseBestAction(State currentState) {
	lastState = currentState;

	std::vector<double> rewards = getModelRewards(currentState);
	lastModel = models[std::max_element(rewards.begin(), rewards.end()) - rewards.begin()];
	return lastModel.action;
}

Action QLearn::chooseBoltzmanAction(State currentState, double explorationConstant) {
	if(explorationConstant < 0.01) {
		std::cout << "Exploration constant (" << explorationConstant << ") is below 0.01. This is too low!. Will cause integer over flow. Assuming an explorationConstant of 0.01 instead.";
		explorationConstant = 0.01;
	}

	double determiner = (double)rand() / (double)RAND_MAX;

	std::vector<double> rewards = getModelRewards(currentState);

	std::vector<double> exponentTerms(0);
	double sumOfExponentTerms = 0;
	std::for_each(rewards.begin(), rewards.end(), [&](double reward){
		double exponentTerm = exp(reward / explorationConstant);
		exponentTerms.push_back(exponentTerm);
		sumOfExponentTerms += exponentTerm;
	});

	double sumOfProbabilities = 0;
	for(int a = 0; a < exponentTerms.size(); a++) {
		sumOfProbabilities += (exponentTerms[a] / sumOfExponentTerms);
		if(sumOfProbabilities >= determiner) {
			lastModel = models[a];
			lastState = currentState;
			return lastModel.action;
		}
	}

	/// Incase a floating point error resulted in no action
	std::cout << "Floating point error when choosing an action using a Boltzmann selection policy! Choosing last action.";

	lastModel = models[models.size() - 1];
	lastState = currentState;
	return lastModel.action;
}

void QLearn::applyReinforcementToLastAction(double reward, State newState) {
	if(lastState.size() == 0) {
		std::cout << "Called applyReinforcementToLastAction before an action had been selected! Because of this, this function call will be ignored.";
	}

	double lr = lastModel.network->getOutput(lastState)[0];
	double targetValueForLastState = lr + learningRate*(reward+(devaluationFactor*getHighestReward(newState))-lr);

	lastModel.addToHistory(std::pair<State, double>(lastState, targetValueForLastState));

	std::vector< std::vector<double> > input;
	std::vector< std::vector<double> > correctOutput;

	std::transform(lastModel.history.begin(), lastModel.history.end(), std::back_inserter(input), [](std::pair<State, double> entry) {
		return entry.first;
	});
	std::transform(lastModel.history.begin(), lastModel.history.end(), std::back_inserter(correctOutput), [](std::pair<State, double> entry) {
		std::vector<double> returnVal = {entry.second};
		return returnVal;
	});

	backprop.train(lastModel.network, input, correctOutput);
}

void QLearn::reset() {
	std::for_each(models.begin(), models.end(), [&](Model model) {
		model.network->randomizeWeights();
		model.history.clear();
	});
}

std::vector<double> QLearn::getModelRewards(State state) {
	std::vector<double> rewards;
	std::for_each(models.begin(), models.end(), [&](Model model){
		rewards.push_back(model.network->getOutput(state)[0]);
	});

	return rewards;
}

double QLearn::getHighestReward(State state) {
	std::vector<double> rewards = getModelRewards(state);
	return *std::max_element(rewards.begin(), rewards.end());
}<|endoftext|>


<commit_before>// -*- c++ -*-
/*
 * Copyright (C) 2017 Kuhn & Völkel GmbH
 *
 * 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 distribted 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.
 */

//
// ex-pcicclient_set_io.cpp
//
// Shows how to use the PCICClient module to control the IOs state
// of the camera.
//

#include <iostream>
#include <string>
#include <thread>
#include <o3d3xx_camera.h>
#include <o3d3xx_pcicclient.h>

// Camera configuration string:
// * Create and activate application with index 1
// * Set LogicGraph to control IOs state via PCIC interface
const char *config = R"CONFIG(
{
    "o3d3xx":
    {
        "Device":
        {
            "ActiveApplication": "1"
        },
        "Apps":
        [
            {
                "Name": "PCICClient Example",
                "Description": "Manipulates digital IOs",
                "Index" : "1",
                "LogicGraph": "{\n    \"IOMap\": {\n        \"OUT1\": \"PCIC_OUT\",\n        \"OUT2\": \"PCIC_OUT\"\n    },\n    \"blocks\": {\n        \"B00001\": {\n            \"pos\": {\n                \"x\": 262,\n                \"y\": 132\n            },\n            \"properties\": {\n            },\n            \"type\": \"PIN_EVENT_PCIC_O_CMD\"\n        },\n        \"B00003\": {\n            \"pos\": {\n                \"x\": 600,\n                \"y\": 75\n            },\n            \"properties\": {\n                \"pulse_duration\": 0\n            },\n            \"type\": \"DIGITAL_OUT1\"\n        },\n        \"B00005\": {\n            \"pos\": {\n                \"x\": 600,\n                \"y\": 200\n            },\n            \"properties\": {\n                \"pulse_duration\": 0\n            },\n            \"type\": \"DIGITAL_OUT2\"\n        }\n    },\n    \"connectors\": {\n        \"C00000\": {\n            \"dst\": \"B00003\",\n            \"dstEP\": 0,\n            \"src\": \"B00001\",\n            \"srcEP\": 0\n        },\n        \"C00001\": {\n            \"dst\": \"B00005\",\n            \"dstEP\": 0,\n            \"src\": \"B00001\",\n            \"srcEP\": 0\n        }\n    }\n}\n"
            }
        ]
    }
}
)CONFIG";

int main(int argc, char** argv)
{
  // Create camera
  o3d3xx::Camera::Ptr cam = std::make_shared<o3d3xx::Camera>();

  // Configure camera to allow user defined IO state
  cam->FromJSON(config);

  // Create pcic interface
  o3d3xx::PCICClient::Ptr pcic = std::make_shared<o3d3xx::PCICClient>(cam);

  // Start setting IOs (and led flashing) for ~10 seconds
  pcic->Call("o010"); // OUT1 off
  pcic->Call("o020"); // OUT2 off
  for(int i = 0; i < 25; ++i)
    {
      std::cout << "Pass " << (i+1) << "/" << 25 << std::endl;
      pcic->Call("o011"); // OUT1 on
      std::this_thread::sleep_for(std::chrono::milliseconds(100));
      pcic->Call("o021"); // OUT2 on
      std::this_thread::sleep_for(std::chrono::milliseconds(100));
      pcic->Call("o010"); // OUT1 off
      std::this_thread::sleep_for(std::chrono::milliseconds(100));
      pcic->Call("o020"); // OUT2 off
      std::this_thread::sleep_for(std::chrono::milliseconds(100));
    }

  return 0;
}
<commit_msg>Add querying/printing IO state via O? command<commit_after>// -*- c++ -*-
/*
 * Copyright (C) 2017 Kuhn & Völkel GmbH
 *
 * 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 distribted 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.
 */

//
// ex-pcicclient_set_io.cpp
//
// Shows how to use the PCICClient module to control the IOs state
// of the camera.
//

#include <iostream>
#include <string>
#include <thread>
#include <o3d3xx_camera.h>
#include <o3d3xx_pcicclient.h>

// Camera configuration string:
// * Create and activate application with index 1
// * Set LogicGraph to control IOs state via PCIC interface
const char *config = R"CONFIG(
{
    "o3d3xx":
    {
        "Device":
        {
            "ActiveApplication": "1"
        },
        "Apps":
        [
            {
                "Name": "PCICClient Example",
                "Description": "Manipulates digital IOs",
                "Index" : "1",
                "LogicGraph": "{\n    \"IOMap\": {\n        \"OUT1\": \"PCIC_OUT\",\n        \"OUT2\": \"PCIC_OUT\"\n    },\n    \"blocks\": {\n        \"B00001\": {\n            \"pos\": {\n                \"x\": 262,\n                \"y\": 132\n            },\n            \"properties\": {\n            },\n            \"type\": \"PIN_EVENT_PCIC_O_CMD\"\n        },\n        \"B00003\": {\n            \"pos\": {\n                \"x\": 600,\n                \"y\": 75\n            },\n            \"properties\": {\n                \"pulse_duration\": 0\n            },\n            \"type\": \"DIGITAL_OUT1\"\n        },\n        \"B00005\": {\n            \"pos\": {\n                \"x\": 600,\n                \"y\": 200\n            },\n            \"properties\": {\n                \"pulse_duration\": 0\n            },\n            \"type\": \"DIGITAL_OUT2\"\n        }\n    },\n    \"connectors\": {\n        \"C00000\": {\n            \"dst\": \"B00003\",\n            \"dstEP\": 0,\n            \"src\": \"B00001\",\n            \"srcEP\": 0\n        },\n        \"C00001\": {\n            \"dst\": \"B00005\",\n            \"dstEP\": 0,\n            \"src\": \"B00001\",\n            \"srcEP\": 0\n        }\n    }\n}\n"
            }
        ]
    }
}
)CONFIG";

int main(int argc, char** argv)
{
  // Create camera
  o3d3xx::Camera::Ptr cam = std::make_shared<o3d3xx::Camera>();

  // Configure camera to allow user defined IO state
  cam->FromJSON(config);

  // Create pcic interface
  o3d3xx::PCICClient::Ptr pcic = std::make_shared<o3d3xx::PCICClient>(cam);

  // Start setting IOs (and led flashing)
  pcic->Call("o010"); // OUT1 off
  pcic->Call("o020"); // OUT2 off
  for(int i = 0; i < 10; ++i)
    {
      std::cout << "Pass " << (i+1) << "/" << 25 << std::endl;

      pcic->Call("o011"); // OUT1 on
      std::cout << "State: " << pcic->Call("O01?") << " " << pcic->Call("O02?") << std::endl;
      std::this_thread::sleep_for(std::chrono::milliseconds(100));

      pcic->Call("o021"); // OUT2 on
      std::cout << "State: " << pcic->Call("O01?") << " " << pcic->Call("O02?") << std::endl;
      std::this_thread::sleep_for(std::chrono::milliseconds(100));

      pcic->Call("o010"); // OUT1 off
      std::cout << "State: " << pcic->Call("O01?") << " " << pcic->Call("O02?") << std::endl;
      std::this_thread::sleep_for(std::chrono::milliseconds(100));

      pcic->Call("o020"); // OUT2 off
      std::cout << "State: " << pcic->Call("O01?") << " " << pcic->Call("O02?") << std::endl;
      std::this_thread::sleep_for(std::chrono::milliseconds(100));

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

  return 0;
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: spelleng.cxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: obo $ $Date: 2004-04-27 16:13:37 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifdef PCH
#include "ui_pch.hxx"
#endif

#pragma hdrstop

#include <memory>

#include "scitems.hxx"
#include <svx/eeitem.hxx>
#define ITEMID_FIELD EE_FEATURE_FIELD

#include <svx/langitem.hxx>
#include <svx/editobj.hxx>
#include <svx/editview.hxx>
#include <vcl/msgbox.hxx>
#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif

#include "spelleng.hxx"
#include "tabvwsh.hxx"
#include "docsh.hxx"
#include "cell.hxx"
#include "patattr.hxx"
#include "waitoff.hxx"
#include "globstr.hrc"

// ============================================================================

namespace {

bool lclHasString( ScDocument& rDoc, USHORT nCol, USHORT nRow, USHORT nTab, const String& rString )
{
    String aCompStr;
    rDoc.GetString( nCol, nRow, nTab, aCompStr );
    return aCompStr == rString;      //! case-insensitive?
}

} // namespace

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

ScConversionEngineBase::ScConversionEngineBase(
        SfxItemPool* pEnginePool, ScViewData& rViewData,
        ScDocument* pUndoDoc, ScDocument* pRedoDoc,
        ESelection* pEdSelection,
        USHORT nCol, USHORT nRow, USHORT nTab,
        bool bCellSelection ) :
    ScEditEngineDefaulter( pEnginePool ),
    mrViewData( rViewData ),
    mrDocShell( *rViewData.GetDocShell() ),
    mrDoc( *rViewData.GetDocShell()->GetDocument() ),
    mpUndoDoc( pUndoDoc ),
    mpRedoDoc( pRedoDoc ),
    mpEditSel( pEdSelection ),
    meCurrLang( LANGUAGE_ENGLISH_US ),
    mnStartCol( nCol ),
    mnStartRow( nRow ),
    mnStartTab( nTab ),
    mnCurrCol( nCol ),
    mnCurrRow( nRow ),
    mbCellSelect( bCellSelection ),
    mbIsAnyModified( false ),
    mbInitialState( true ),
    mbWrappedInTable( false )
{
}

ScConversionEngineBase::~ScConversionEngineBase()
{
}

bool ScConversionEngineBase::FindNextConversionCell()
{
    ScMarkData& rMark = mrViewData.GetMarkData();
    ScTabViewShell* pViewShell = mrViewData.GetViewShell();
    ScSplitPos eWhich = mrViewData.GetActivePart();
    ScBaseCell* pCell = NULL;
    const ScPatternAttr* pPattern = NULL;
    const ScPatternAttr* pLastPattern = NULL;
    ::std::auto_ptr< SfxItemSet > pEditDefaults( new SfxItemSet( GetEmptyItemSet() ) );

    if( IsModified() )
    {
        mbIsAnyModified = true;

        String aNewStr = GetText();

        BOOL bMultiTab = (rMark.GetSelectCount() > 1);
        String aVisibleStr;
        if( bMultiTab )
            mrDoc.GetString( mnCurrCol, mnCurrRow, mnStartTab, aVisibleStr );

        for( USHORT nTab = 0, nTabCount = mrDoc.GetTableCount(); nTab < nTabCount; ++nTab )
        {
            //  #69965# always change the cell on the visible tab,
            //  on the other selected tabs only if they contain the same text

            if( (nTab == mnStartTab) ||
                (bMultiTab && rMark.GetTableSelect( nTab ) &&
                 lclHasString( mrDoc, mnCurrCol, mnCurrRow, nTab, aVisibleStr )) )
            {
                CellType eCellType;
                mrDoc.GetCellType( mnCurrCol, mnCurrRow, nTab, eCellType );
                mrDoc.GetCell( mnCurrCol, mnCurrRow, nTab, pCell );

                if( mpUndoDoc && pCell )
                {
                    ScBaseCell* pUndoCell = pCell->Clone( mpUndoDoc );
                    mpUndoDoc->PutCell( mnCurrCol, mnCurrRow, nTab, pUndoCell );
                }

                if( eCellType == CELLTYPE_EDIT )
                {
                    if( pCell )
                    {
                        ScEditCell* pEditCell = static_cast< ScEditCell* >( pCell );
                        ::std::auto_ptr< EditTextObject > pEditObj( CreateTextObject() );
                        pEditCell->SetData( pEditObj.get(), GetEditTextObjectPool() );
                    }
                }
                else
                {
                    mrDoc.SetString( mnCurrCol, mnCurrRow, nTab, aNewStr );
                    mrDoc.GetCell( mnCurrCol, mnCurrRow, nTab, pCell );
                }

                if( mpRedoDoc && pCell )
                {
                    ScBaseCell* pRedoCell = pCell->Clone( mpRedoDoc );
                    mpRedoDoc->PutCell( mnCurrCol, mnCurrRow, nTab, pRedoCell );
                }

                mrDocShell.PostPaintCell( mnCurrCol, mnCurrRow, nTab );
            }
        }
    }
    pCell = NULL;
    USHORT nNewCol = mnCurrCol;
    USHORT nNewRow = mnCurrRow;

    if( mbInitialState )
    {
        /*  On very first call, decrement row to let GetNextSpellingCell() find
            the first cell of current range. */
        mbInitialState = false;
        --nNewRow;
    }

    bool bLoop = true;
    bool bFound = false;
    while( bLoop && !bFound )
    {
        bLoop = mrDoc.GetNextSpellingCell( nNewCol, nNewRow, mnStartTab, mbCellSelect, rMark );
        if( bLoop )
        {
            FillFromCell( mnCurrCol, mnCurrRow, mnStartTab );

            if( mbWrappedInTable && ((nNewCol > mnStartCol) || ((nNewCol == mnStartCol) && (nNewRow >= mnStartRow))) )
            {
                ShowFinishDialog();
                bLoop = false;
            }
            else if( nNewCol > MAXCOL )
            {
                // no more cells in the sheet - try to restart at top of sheet

                if( mbCellSelect || ((mnStartCol == 0) && (mnStartRow == 0)) )
                {
                    // conversion started at cell A1 or in selection, do not query to restart at top
                    ShowFinishDialog();
                    bLoop = false;
                }
                else if( ShowTableWrapDialog() )
                {
                    // conversion started anywhere but in cell A1, user wants to restart
                    nNewRow = MAXROW + 2;
                    mbWrappedInTable = true;
                }
                else
                    bLoop = false;
            }
            else
            {
                pPattern = mrDoc.GetPattern( nNewCol, nNewRow, mnStartTab );
                if( pPattern && (pPattern != pLastPattern) )
                {
                    pPattern->FillEditItemSet( pEditDefaults.get() );
                    SetDefaults( *pEditDefaults );
                    pLastPattern = pPattern;
                }

                // language changed?
                const SfxPoolItem* pItem = mrDoc.GetAttr( nNewCol, nNewRow, mnStartTab, ATTR_FONT_LANGUAGE );
                if( const SvxLanguageItem* pLangItem = PTR_CAST( SvxLanguageItem, pItem ) )
                {
                    LanguageType eLang = static_cast< LanguageType >( pLangItem->GetValue() );
                    if( eLang == LANGUAGE_SYSTEM )
                        eLang = Application::GetSettings().GetLanguage();   // never use SYSTEM for spelling
                    if( eLang != meCurrLang )
                    {
                        meCurrLang = eLang;
                        SetDefaultLanguage( eLang );
                    }
                }

                FillFromCell( nNewCol, nNewRow, mnStartTab );

                bFound = bLoop && NeedsConversion();
            }
        }
    }

    if( bFound )
    {
        pViewShell->AlignToCursor( nNewCol, nNewRow, SC_FOLLOW_JUMP );
        pViewShell->SetCursor( nNewCol, nNewRow, TRUE );
        mrViewData.GetView()->MakeEditView( this, nNewCol, nNewRow );
        EditView* pEditView = mrViewData.GetSpellingView();
        if( mpEditSel )
        {
            pEditView->SetSelection( *mpEditSel );
            mpEditSel = NULL;
        }
        else
        {
            ESelection aSel;
            pEditView->SetSelection( aSel );
        }

        ClearModifyFlag();
        mnCurrCol = nNewCol;
        mnCurrRow = nNewRow;
    }

    return bFound;
}

bool ScConversionEngineBase::ShowTableWrapDialog()
{
    // default: no dialog, always restart at top
    return true;
}

void ScConversionEngineBase::ShowFinishDialog()
{
    // default: no dialog
}

// private --------------------------------------------------------------------

void ScConversionEngineBase::FillFromCell( USHORT nCol, USHORT nRow, USHORT nTab )
{
    CellType eCellType;
    mrDoc.GetCellType( nCol, nRow, nTab, eCellType );

    switch( eCellType )
    {
        case CELLTYPE_STRING:
        {
            String aText;
            mrDoc.GetString( nCol, nRow, nTab, aText );
            SetText( aText );
        }
        break;
        case CELLTYPE_EDIT:
        {
            ScBaseCell* pCell = NULL;
            mrDoc.GetCell( nCol, nRow, nTab, pCell );
            if( pCell )
            {
                const EditTextObject* pNewEditObj = NULL;
                static_cast< ScEditCell* >( pCell )->GetData( pNewEditObj );
                if( pNewEditObj )
                    SetText( *pNewEditObj );
            }
        }
        break;
        default:
            SetText( EMPTY_STRING );
    }
}

// ============================================================================

ScSpellingEngine::ScSpellingEngine(
        SfxItemPool* pEnginePool, ScViewData& rViewData,
        ScDocument* pUndoDoc, ScDocument* pRedoDoc,
        ESelection* pEdSelection,
        USHORT nCol, USHORT nRow, USHORT nTab,
        bool bCellSelection, XSpellCheckerRef xSpeller ) :
    ScConversionEngineBase( pEnginePool, rViewData, pUndoDoc, pRedoDoc, pEdSelection, nCol, nRow, nTab, bCellSelection )
{
    SetSpeller( xSpeller );
}

void ScSpellingEngine::ConvertAll( EditView& rEditView )
{
    EESpellState eState = EE_SPELL_OK;
    if( FindNextConversionCell() )
        eState = rEditView.StartSpeller( static_cast< BOOL >( TRUE ) );

    DBG_ASSERT( eState != EE_SPELL_NOSPELLER, "ScSpellingEngine::Convert - no spell checker" );
    if( eState == EE_SPELL_NOLANGUAGE )
    {
        ScWaitCursorOff aWaitOff( mrDocShell.GetDialogParent() );
        InfoBox( mrViewData.GetDialogParent(), ScGlobal::GetRscString( STR_NOLANGERR ) ).Execute();
    }
}

BOOL ScSpellingEngine::SpellNextDocument()
{
    return FindNextConversionCell();
}

bool ScSpellingEngine::NeedsConversion()
{
    return HasSpellErrors() != EE_SPELL_OK;
}

bool ScSpellingEngine::ShowTableWrapDialog()
{
    ScWaitCursorOff aWaitOff( mrDocShell.GetDialogParent() );
    MessBox aMsgBox( mrViewData.GetDialogParent(), WinBits( WB_YES_NO | WB_DEF_YES ),
        ScGlobal::GetRscString( STR_MSSG_DOSUBTOTALS_0 ),
        ScGlobal::GetRscString( STR_SPELLING_BEGIN_TAB) );
    return aMsgBox.Execute() == RET_YES;
}

void ScSpellingEngine::ShowFinishDialog()
{
    ScWaitCursorOff aWaitOff( mrDocShell.GetDialogParent() );
    InfoBox( mrViewData.GetDialogParent(), ScGlobal::GetRscString( STR_SPELLING_STOP_OK ) ).Execute();
}

// ============================================================================

ScTextConversionEngine::ScTextConversionEngine(
        SfxItemPool* pEnginePool, ScViewData& rViewData,
        ScDocument* pUndoDoc, ScDocument* pRedoDoc,
        ESelection* pEdSelection,
        USHORT nCol, USHORT nRow, USHORT nTab,
        bool bCellSelection, LanguageType eConvLanguage ) :
    ScConversionEngineBase( pEnginePool, rViewData, pUndoDoc, pRedoDoc, pEdSelection, nCol, nRow, nTab, bCellSelection ),
    meConvLang( eConvLanguage )
{
}

void ScTextConversionEngine::ConvertAll( EditView& rEditView )
{
    if( FindNextConversionCell() )
        rEditView.StartTextConversion( meConvLang, TRUE );
}

BOOL ScTextConversionEngine::ConvertNextDocument()
{
    return FindNextConversionCell();
}

bool ScTextConversionEngine::NeedsConversion()
{
    return HasConvertibleTextPortion( meConvLang );
}

// ============================================================================

<commit_msg>INTEGRATION: CWS rowlimit (1.5.310); FILE MERGED 2004/01/16 17:43:04 er 1.5.310.1: #i1967# SCCOL,SCROW,SCTAB replace USHORT; SCsCOL,SCsROW,SCsTAB replace short<commit_after>/*************************************************************************
 *
 *  $RCSfile: spelleng.cxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: obo $ $Date: 2004-06-04 13:40:55 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifdef PCH
#include "ui_pch.hxx"
#endif

#pragma hdrstop

#include <memory>

#include "scitems.hxx"
#include <svx/eeitem.hxx>
#define ITEMID_FIELD EE_FEATURE_FIELD

#include <svx/langitem.hxx>
#include <svx/editobj.hxx>
#include <svx/editview.hxx>
#include <vcl/msgbox.hxx>
#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif

#include "spelleng.hxx"
#include "tabvwsh.hxx"
#include "docsh.hxx"
#include "cell.hxx"
#include "patattr.hxx"
#include "waitoff.hxx"
#include "globstr.hrc"

// ============================================================================

namespace {

bool lclHasString( ScDocument& rDoc, SCCOL nCol, SCROW nRow, SCTAB nTab, const String& rString )
{
    String aCompStr;
    rDoc.GetString( nCol, nRow, nTab, aCompStr );
    return aCompStr == rString;      //! case-insensitive?
}

} // namespace

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

ScConversionEngineBase::ScConversionEngineBase(
        SfxItemPool* pEnginePool, ScViewData& rViewData,
        ScDocument* pUndoDoc, ScDocument* pRedoDoc,
        ESelection* pEdSelection,
        SCCOL nCol, SCROW nRow, SCTAB nTab,
        bool bCellSelection ) :
    ScEditEngineDefaulter( pEnginePool ),
    mrViewData( rViewData ),
    mrDocShell( *rViewData.GetDocShell() ),
    mrDoc( *rViewData.GetDocShell()->GetDocument() ),
    mpUndoDoc( pUndoDoc ),
    mpRedoDoc( pRedoDoc ),
    mpEditSel( pEdSelection ),
    meCurrLang( LANGUAGE_ENGLISH_US ),
    mnStartCol( nCol ),
    mnStartRow( nRow ),
    mnStartTab( nTab ),
    mnCurrCol( nCol ),
    mnCurrRow( nRow ),
    mbCellSelect( bCellSelection ),
    mbIsAnyModified( false ),
    mbInitialState( true ),
    mbWrappedInTable( false )
{
}

ScConversionEngineBase::~ScConversionEngineBase()
{
}

bool ScConversionEngineBase::FindNextConversionCell()
{
    ScMarkData& rMark = mrViewData.GetMarkData();
    ScTabViewShell* pViewShell = mrViewData.GetViewShell();
    ScSplitPos eWhich = mrViewData.GetActivePart();
    ScBaseCell* pCell = NULL;
    const ScPatternAttr* pPattern = NULL;
    const ScPatternAttr* pLastPattern = NULL;
    ::std::auto_ptr< SfxItemSet > pEditDefaults( new SfxItemSet( GetEmptyItemSet() ) );

    if( IsModified() )
    {
        mbIsAnyModified = true;

        String aNewStr = GetText();

        BOOL bMultiTab = (rMark.GetSelectCount() > 1);
        String aVisibleStr;
        if( bMultiTab )
            mrDoc.GetString( mnCurrCol, mnCurrRow, mnStartTab, aVisibleStr );

        for( SCTAB nTab = 0, nTabCount = mrDoc.GetTableCount(); nTab < nTabCount; ++nTab )
        {
            //  #69965# always change the cell on the visible tab,
            //  on the other selected tabs only if they contain the same text

            if( (nTab == mnStartTab) ||
                (bMultiTab && rMark.GetTableSelect( nTab ) &&
                 lclHasString( mrDoc, mnCurrCol, mnCurrRow, nTab, aVisibleStr )) )
            {
                CellType eCellType;
                mrDoc.GetCellType( mnCurrCol, mnCurrRow, nTab, eCellType );
                mrDoc.GetCell( mnCurrCol, mnCurrRow, nTab, pCell );

                if( mpUndoDoc && pCell )
                {
                    ScBaseCell* pUndoCell = pCell->Clone( mpUndoDoc );
                    mpUndoDoc->PutCell( mnCurrCol, mnCurrRow, nTab, pUndoCell );
                }

                if( eCellType == CELLTYPE_EDIT )
                {
                    if( pCell )
                    {
                        ScEditCell* pEditCell = static_cast< ScEditCell* >( pCell );
                        ::std::auto_ptr< EditTextObject > pEditObj( CreateTextObject() );
                        pEditCell->SetData( pEditObj.get(), GetEditTextObjectPool() );
                    }
                }
                else
                {
                    mrDoc.SetString( mnCurrCol, mnCurrRow, nTab, aNewStr );
                    mrDoc.GetCell( mnCurrCol, mnCurrRow, nTab, pCell );
                }

                if( mpRedoDoc && pCell )
                {
                    ScBaseCell* pRedoCell = pCell->Clone( mpRedoDoc );
                    mpRedoDoc->PutCell( mnCurrCol, mnCurrRow, nTab, pRedoCell );
                }

                mrDocShell.PostPaintCell( mnCurrCol, mnCurrRow, nTab );
            }
        }
    }
    pCell = NULL;
    SCCOL nNewCol = mnCurrCol;
    SCROW nNewRow = mnCurrRow;

    if( mbInitialState )
    {
        /*  On very first call, decrement row to let GetNextSpellingCell() find
            the first cell of current range. */
        mbInitialState = false;
        --nNewRow;
    }

    bool bLoop = true;
    bool bFound = false;
    while( bLoop && !bFound )
    {
        bLoop = mrDoc.GetNextSpellingCell( nNewCol, nNewRow, mnStartTab, mbCellSelect, rMark );
        if( bLoop )
        {
            FillFromCell( mnCurrCol, mnCurrRow, mnStartTab );

            if( mbWrappedInTable && ((nNewCol > mnStartCol) || ((nNewCol == mnStartCol) && (nNewRow >= mnStartRow))) )
            {
                ShowFinishDialog();
                bLoop = false;
            }
            else if( nNewCol > MAXCOL )
            {
                // no more cells in the sheet - try to restart at top of sheet

                if( mbCellSelect || ((mnStartCol == 0) && (mnStartRow == 0)) )
                {
                    // conversion started at cell A1 or in selection, do not query to restart at top
                    ShowFinishDialog();
                    bLoop = false;
                }
                else if( ShowTableWrapDialog() )
                {
                    // conversion started anywhere but in cell A1, user wants to restart
                    nNewRow = MAXROW + 2;
                    mbWrappedInTable = true;
                }
                else
                    bLoop = false;
            }
            else
            {
                pPattern = mrDoc.GetPattern( nNewCol, nNewRow, mnStartTab );
                if( pPattern && (pPattern != pLastPattern) )
                {
                    pPattern->FillEditItemSet( pEditDefaults.get() );
                    SetDefaults( *pEditDefaults );
                    pLastPattern = pPattern;
                }

                // language changed?
                const SfxPoolItem* pItem = mrDoc.GetAttr( nNewCol, nNewRow, mnStartTab, ATTR_FONT_LANGUAGE );
                if( const SvxLanguageItem* pLangItem = PTR_CAST( SvxLanguageItem, pItem ) )
                {
                    LanguageType eLang = static_cast< LanguageType >( pLangItem->GetValue() );
                    if( eLang == LANGUAGE_SYSTEM )
                        eLang = Application::GetSettings().GetLanguage();   // never use SYSTEM for spelling
                    if( eLang != meCurrLang )
                    {
                        meCurrLang = eLang;
                        SetDefaultLanguage( eLang );
                    }
                }

                FillFromCell( nNewCol, nNewRow, mnStartTab );

                bFound = bLoop && NeedsConversion();
            }
        }
    }

    if( bFound )
    {
        pViewShell->AlignToCursor( nNewCol, nNewRow, SC_FOLLOW_JUMP );
        pViewShell->SetCursor( nNewCol, nNewRow, TRUE );
        mrViewData.GetView()->MakeEditView( this, nNewCol, nNewRow );
        EditView* pEditView = mrViewData.GetSpellingView();
        if( mpEditSel )
        {
            pEditView->SetSelection( *mpEditSel );
            mpEditSel = NULL;
        }
        else
        {
            ESelection aSel;
            pEditView->SetSelection( aSel );
        }

        ClearModifyFlag();
        mnCurrCol = nNewCol;
        mnCurrRow = nNewRow;
    }

    return bFound;
}

bool ScConversionEngineBase::ShowTableWrapDialog()
{
    // default: no dialog, always restart at top
    return true;
}

void ScConversionEngineBase::ShowFinishDialog()
{
    // default: no dialog
}

// private --------------------------------------------------------------------

void ScConversionEngineBase::FillFromCell( SCCOL nCol, SCROW nRow, SCTAB nTab )
{
    CellType eCellType;
    mrDoc.GetCellType( nCol, nRow, nTab, eCellType );

    switch( eCellType )
    {
        case CELLTYPE_STRING:
        {
            String aText;
            mrDoc.GetString( nCol, nRow, nTab, aText );
            SetText( aText );
        }
        break;
        case CELLTYPE_EDIT:
        {
            ScBaseCell* pCell = NULL;
            mrDoc.GetCell( nCol, nRow, nTab, pCell );
            if( pCell )
            {
                const EditTextObject* pNewEditObj = NULL;
                static_cast< ScEditCell* >( pCell )->GetData( pNewEditObj );
                if( pNewEditObj )
                    SetText( *pNewEditObj );
            }
        }
        break;
        default:
            SetText( EMPTY_STRING );
    }
}

// ============================================================================

ScSpellingEngine::ScSpellingEngine(
        SfxItemPool* pEnginePool, ScViewData& rViewData,
        ScDocument* pUndoDoc, ScDocument* pRedoDoc,
        ESelection* pEdSelection,
        SCCOL nCol, SCROW nRow, SCTAB nTab,
        bool bCellSelection, XSpellCheckerRef xSpeller ) :
    ScConversionEngineBase( pEnginePool, rViewData, pUndoDoc, pRedoDoc, pEdSelection, nCol, nRow, nTab, bCellSelection )
{
    SetSpeller( xSpeller );
}

void ScSpellingEngine::ConvertAll( EditView& rEditView )
{
    EESpellState eState = EE_SPELL_OK;
    if( FindNextConversionCell() )
        eState = rEditView.StartSpeller( static_cast< BOOL >( TRUE ) );

    DBG_ASSERT( eState != EE_SPELL_NOSPELLER, "ScSpellingEngine::Convert - no spell checker" );
    if( eState == EE_SPELL_NOLANGUAGE )
    {
        ScWaitCursorOff aWaitOff( mrDocShell.GetDialogParent() );
        InfoBox( mrViewData.GetDialogParent(), ScGlobal::GetRscString( STR_NOLANGERR ) ).Execute();
    }
}

BOOL ScSpellingEngine::SpellNextDocument()
{
    return FindNextConversionCell();
}

bool ScSpellingEngine::NeedsConversion()
{
    return HasSpellErrors() != EE_SPELL_OK;
}

bool ScSpellingEngine::ShowTableWrapDialog()
{
    ScWaitCursorOff aWaitOff( mrDocShell.GetDialogParent() );
    MessBox aMsgBox( mrViewData.GetDialogParent(), WinBits( WB_YES_NO | WB_DEF_YES ),
        ScGlobal::GetRscString( STR_MSSG_DOSUBTOTALS_0 ),
        ScGlobal::GetRscString( STR_SPELLING_BEGIN_TAB) );
    return aMsgBox.Execute() == RET_YES;
}

void ScSpellingEngine::ShowFinishDialog()
{
    ScWaitCursorOff aWaitOff( mrDocShell.GetDialogParent() );
    InfoBox( mrViewData.GetDialogParent(), ScGlobal::GetRscString( STR_SPELLING_STOP_OK ) ).Execute();
}

// ============================================================================

ScTextConversionEngine::ScTextConversionEngine(
        SfxItemPool* pEnginePool, ScViewData& rViewData,
        ScDocument* pUndoDoc, ScDocument* pRedoDoc,
        ESelection* pEdSelection,
        SCCOL nCol, SCROW nRow, SCTAB nTab,
        bool bCellSelection, LanguageType eConvLanguage ) :
    ScConversionEngineBase( pEnginePool, rViewData, pUndoDoc, pRedoDoc, pEdSelection, nCol, nRow, nTab, bCellSelection ),
    meConvLang( eConvLanguage )
{
}

void ScTextConversionEngine::ConvertAll( EditView& rEditView )
{
    if( FindNextConversionCell() )
        rEditView.StartTextConversion( meConvLang, TRUE );
}

BOOL ScTextConversionEngine::ConvertNextDocument()
{
    return FindNextConversionCell();
}

bool ScTextConversionEngine::NeedsConversion()
{
    return HasConvertibleTextPortion( meConvLang );
}

// ============================================================================

<|endoftext|>


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

#include <errno.h>
#include <sys/file.h>

#include "base/basictypes.h"
#include "base/scoped_ptr.h"
#include "chrome/browser/chromeos/external_metrics.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace chromeos {  // Need this because of the FRIEND_TEST

class ExternalMetricsTest : public testing::Test {
};

// Because the metrics service is not essential, errors will not cause the
// program to terminate.  However, the errors produce logs.

#define MAXLENGTH ExternalMetrics::kMetricsMessageMaxLength

static void SendMessage(const char* path, const char* name, const char* value) {
  int fd = open(path, O_CREAT | O_APPEND | O_WRONLY, 0666);
  int32 l = strlen(name) + strlen(value) + 2 + sizeof(l);
  write(fd, &l, sizeof(l));
  write(fd, name, strlen(name) + 1);
  write(fd, value, strlen(value) + 1);
  close(fd);
}

static scoped_ptr<std::string> received_name;
static scoped_ptr<std::string> received_value;
int received_count = 0;

static void ReceiveMessage(const char* name, const char* value) {
  received_name.reset(new std::string(name));
  received_value.reset(new std::string(value));
  received_count++;
}

static void CheckMessage(const char* name, const char* value, int count) {
  EXPECT_EQ(*received_name.get(), name);
  EXPECT_EQ(*received_value.get(), value);
  EXPECT_EQ(received_count, count);
}

TEST(ExternalMetricsTest, ParseExternalMetricsFile) {
  struct {
    const char* name;
    const char* value;
  } pairs[] = {
    {"BootTime", "9500"},
    {"BootTime", "10000"},
    {"BootTime", "9200"},
    {"TabOverviewExitMouse", ""},
    {"ConnmanIdle", "1000"},
    {"ConnmanIdle", "1200"},
    {"TabOverviewKeystroke", ""},
    {"ConnmanDisconnect", "1000"},
    {"ConnmanFailure", "1000"},
    {"ConnmanFailure", "1300"},
    {"ConnmanAssociation", "1000"},
    {"ConnmanConfiguration", "1000"},
    {"ConnmanOffline", "1000"},
    {"ConnmanOnline", "1000"},
    {"ConnmanOffline", "2000"},
    {"ConnmanReady", "33000"},
    {"ConnmanReady", "44000"},
    {"ConnmanReady", "22000"},
  };
  int npairs = ARRAYSIZE_UNSAFE(pairs);
  int32 i;
  const char* path = "/tmp/.chromeos-metrics";
  scoped_refptr<chromeos::ExternalMetrics>
      external_metrics(new chromeos::ExternalMetrics());
  external_metrics->SetRecorder(&ReceiveMessage);

  EXPECT_TRUE(unlink(path) == 0 || errno == ENOENT);

  // Sends a few valid messages.  Once in a while, collect them and check the
  // last message.  We don't want to check every single message because we also
  // want to test the ability to deal with a file containing more than one
  // message.
  for (i = 0; i < npairs; i++) {
    SendMessage(path, pairs[i].name, pairs[i].value);
    if (i % 3 == 2) {
      external_metrics->CollectEvents();
      CheckMessage(pairs[i].name, pairs[i].value, i + 1);
    }
  }

  // Sends a message that's too large.
  char b[MAXLENGTH + 100];
  for (i = 0; i < MAXLENGTH + 99; i++) {
    b[i] = 'x';
  }
  b[i] = '\0';
  SendMessage(path, b, "yyy");
  external_metrics->CollectEvents();
  EXPECT_EQ(received_count, npairs);

  // Sends a malformed message (first string is not null-terminated).
  i = 100 + sizeof(i);
  int fd = open(path, O_CREAT | O_WRONLY);
  EXPECT_GT(fd, 0);
  EXPECT_EQ(write(fd, &i, sizeof(i)), static_cast<int>(sizeof(i)));
  EXPECT_EQ(write(fd, b, i), i);
  EXPECT_EQ(close(fd), 0);

  external_metrics->CollectEvents();
  EXPECT_EQ(received_count, npairs);

  // Sends a malformed message (second string is not null-terminated).
  b[50] = '\0';
  fd = open(path, O_CREAT | O_WRONLY);
  EXPECT_GT(fd, 0);
  EXPECT_EQ(write(fd, &i, sizeof(i)), static_cast<int>(sizeof(i)));
  EXPECT_EQ(write(fd, b, i), i);
  EXPECT_EQ(close(fd), 0);

  external_metrics->CollectEvents();
  EXPECT_EQ(received_count, npairs);

  // Checks that we survive when file doesn't exist.
  EXPECT_EQ(unlink(path), 0);
  external_metrics->CollectEvents();
  EXPECT_EQ(received_count, npairs);
}

}  // namespace chromeos
<commit_msg>Fix compile error : " error: open with O_CREAT in second argument needs 3 arguments"<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include <errno.h>
#include <sys/file.h>

#include "base/basictypes.h"
#include "base/scoped_ptr.h"
#include "chrome/browser/chromeos/external_metrics.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace chromeos {  // Need this because of the FRIEND_TEST

class ExternalMetricsTest : public testing::Test {
};

// Because the metrics service is not essential, errors will not cause the
// program to terminate.  However, the errors produce logs.

#define MAXLENGTH ExternalMetrics::kMetricsMessageMaxLength

static void SendMessage(const char* path, const char* name, const char* value) {
  int fd = open(path, O_CREAT | O_APPEND | O_WRONLY, 0666);
  int32 l = strlen(name) + strlen(value) + 2 + sizeof(l);
  write(fd, &l, sizeof(l));
  write(fd, name, strlen(name) + 1);
  write(fd, value, strlen(value) + 1);
  close(fd);
}

static scoped_ptr<std::string> received_name;
static scoped_ptr<std::string> received_value;
int received_count = 0;

static void ReceiveMessage(const char* name, const char* value) {
  received_name.reset(new std::string(name));
  received_value.reset(new std::string(value));
  received_count++;
}

static void CheckMessage(const char* name, const char* value, int count) {
  EXPECT_EQ(*received_name.get(), name);
  EXPECT_EQ(*received_value.get(), value);
  EXPECT_EQ(received_count, count);
}

TEST(ExternalMetricsTest, ParseExternalMetricsFile) {
  struct {
    const char* name;
    const char* value;
  } pairs[] = {
    {"BootTime", "9500"},
    {"BootTime", "10000"},
    {"BootTime", "9200"},
    {"TabOverviewExitMouse", ""},
    {"ConnmanIdle", "1000"},
    {"ConnmanIdle", "1200"},
    {"TabOverviewKeystroke", ""},
    {"ConnmanDisconnect", "1000"},
    {"ConnmanFailure", "1000"},
    {"ConnmanFailure", "1300"},
    {"ConnmanAssociation", "1000"},
    {"ConnmanConfiguration", "1000"},
    {"ConnmanOffline", "1000"},
    {"ConnmanOnline", "1000"},
    {"ConnmanOffline", "2000"},
    {"ConnmanReady", "33000"},
    {"ConnmanReady", "44000"},
    {"ConnmanReady", "22000"},
  };
  int npairs = ARRAYSIZE_UNSAFE(pairs);
  int32 i;
  const char* path = "/tmp/.chromeos-metrics";
  scoped_refptr<chromeos::ExternalMetrics>
      external_metrics(new chromeos::ExternalMetrics());
  external_metrics->SetRecorder(&ReceiveMessage);

  EXPECT_TRUE(unlink(path) == 0 || errno == ENOENT);

  // Sends a few valid messages.  Once in a while, collect them and check the
  // last message.  We don't want to check every single message because we also
  // want to test the ability to deal with a file containing more than one
  // message.
  for (i = 0; i < npairs; i++) {
    SendMessage(path, pairs[i].name, pairs[i].value);
    if (i % 3 == 2) {
      external_metrics->CollectEvents();
      CheckMessage(pairs[i].name, pairs[i].value, i + 1);
    }
  }

  // Sends a message that's too large.
  char b[MAXLENGTH + 100];
  for (i = 0; i < MAXLENGTH + 99; i++) {
    b[i] = 'x';
  }
  b[i] = '\0';
  SendMessage(path, b, "yyy");
  external_metrics->CollectEvents();
  EXPECT_EQ(received_count, npairs);

  // Sends a malformed message (first string is not null-terminated).
  i = 100 + sizeof(i);
  int fd = open(path, O_CREAT | O_WRONLY, 0666);
  EXPECT_GT(fd, 0);
  EXPECT_EQ(write(fd, &i, sizeof(i)), static_cast<int>(sizeof(i)));
  EXPECT_EQ(write(fd, b, i), i);
  EXPECT_EQ(close(fd), 0);

  external_metrics->CollectEvents();
  EXPECT_EQ(received_count, npairs);

  // Sends a malformed message (second string is not null-terminated).
  b[50] = '\0';
  fd = open(path, O_CREAT | O_WRONLY, 0666);
  EXPECT_GT(fd, 0);
  EXPECT_EQ(write(fd, &i, sizeof(i)), static_cast<int>(sizeof(i)));
  EXPECT_EQ(write(fd, b, i), i);
  EXPECT_EQ(close(fd), 0);

  external_metrics->CollectEvents();
  EXPECT_EQ(received_count, npairs);

  // Checks that we survive when file doesn't exist.
  EXPECT_EQ(unlink(path), 0);
  external_metrics->CollectEvents();
  EXPECT_EQ(received_count, npairs);
}

}  // namespace chromeos
<|endoftext|>


<commit_before><commit_msg>*** empty log message ***<commit_after><|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/setting_level_bubble_view.h"

#include <string>

#include "base/logging.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "ui/gfx/canvas.h"
#include "views/controls/progress_bar.h"

using views::Background;
using views::View;
using views::Widget;

namespace {

// Bubble metrics.
const int kWidth = 350, kHeight = 100;
const int kPadding = 20;
const int kProgressBarWidth = 211;
const int kProgressBarHeight = 17;

}  // namespace

namespace chromeos {

SettingLevelBubbleView::SettingLevelBubbleView()
    : progress_bar_(NULL),
      icon_(NULL) {
}

void SettingLevelBubbleView::Init(SkBitmap* icon, int level_percent) {
  DCHECK(icon);
  DCHECK(level_percent >= 0 && level_percent <= 100);
  icon_ = icon;
  progress_bar_ = new views::ProgressBar();
  AddChildView(progress_bar_);
  Update(level_percent);
}

void SettingLevelBubbleView::SetIcon(SkBitmap* icon) {
  DCHECK(icon);
  icon_ = icon;
  SchedulePaint();
}

void SettingLevelBubbleView::Update(int level_percent) {
  DCHECK(level_percent >= 0 && level_percent <= 100);
  progress_bar_->SetProgress(level_percent);
}

void SettingLevelBubbleView::OnPaint(gfx::Canvas* canvas) {
  views::View::OnPaint(canvas);
  canvas->DrawBitmapInt(*icon_, kPadding, (height() - icon_->height()) / 2);
}

void SettingLevelBubbleView::Layout() {
  progress_bar_->SetBounds(width() - kPadding - kProgressBarWidth,
                           (height() - kProgressBarHeight) / 2,
                           kProgressBarWidth, kProgressBarHeight);
}

gfx::Size SettingLevelBubbleView::GetPreferredSize() {
  return gfx::Size(kWidth, kHeight);
}

}  // namespace chromeos
<commit_msg>Mirror the volume/brightness level bubble views for right-to-left UIs.  Doing this also fixes the overlapping icon problem (see bug).<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/setting_level_bubble_view.h"

#include <string>

#include "base/logging.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "ui/gfx/canvas.h"
#include "views/controls/progress_bar.h"

using views::Background;
using views::View;
using views::Widget;

namespace {

// Bubble metrics.
const int kWidth = 350, kHeight = 100;
const int kPadding = 20;
const int kProgressBarWidth = 211;
const int kProgressBarHeight = 17;

}  // namespace

namespace chromeos {

SettingLevelBubbleView::SettingLevelBubbleView()
    : progress_bar_(NULL),
      icon_(NULL) {
}

void SettingLevelBubbleView::Init(SkBitmap* icon, int level_percent) {
  DCHECK(icon);
  DCHECK(level_percent >= 0 && level_percent <= 100);
  icon_ = icon;
  progress_bar_ = new views::ProgressBar();
  AddChildView(progress_bar_);
  Update(level_percent);
  progress_bar_->EnableCanvasFlippingForRTLUI(true);
  EnableCanvasFlippingForRTLUI(true);
}

void SettingLevelBubbleView::SetIcon(SkBitmap* icon) {
  DCHECK(icon);
  icon_ = icon;
  SchedulePaint();
}

void SettingLevelBubbleView::Update(int level_percent) {
  DCHECK(level_percent >= 0 && level_percent <= 100);
  progress_bar_->SetProgress(level_percent);
}

void SettingLevelBubbleView::OnPaint(gfx::Canvas* canvas) {
  views::View::OnPaint(canvas);
  canvas->DrawBitmapInt(*icon_, kPadding, (height() - icon_->height()) / 2);
}

void SettingLevelBubbleView::Layout() {
  progress_bar_->SetBounds(width() - kPadding - kProgressBarWidth,
                           (height() - kProgressBarHeight) / 2,
                           kProgressBarWidth, kProgressBarHeight);
}

gfx::Size SettingLevelBubbleView::GetPreferredSize() {
  return gfx::Size(kWidth, kHeight);
}

}  // namespace chromeos
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: tabvwshe.cxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: nn $ $Date: 2001-05-09 12:52:26 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifdef PCH
#include "ui_pch.hxx"
#endif

#pragma hdrstop

// INCLUDE ---------------------------------------------------------------

#ifndef _EEITEM_HXX //autogen
#include <svx/eeitem.hxx>
#endif

#include "scitems.hxx"
#define ITEMID_FIELD EE_FEATURE_FIELD
#include <svx/editview.hxx>
#include <svx/flditem.hxx>
#include <svx/hlnkitem.hxx>
#include <svx/srchitem.hxx>
#include <sfx2/dispatch.hxx>
#include <sfx2/viewfrm.hxx>
#include <sfx2/request.hxx>
#include <sfx2/objface.hxx>
#include <svtools/stritem.hxx>

#include "tabvwsh.hxx"
#include "sc.hrc"
#include "scmod.hxx"
#include "impex.hxx"
#include "editsh.hxx"
#include "dociter.hxx"
#include "inputhdl.hxx"

//==================================================================

String __EXPORT ScTabViewShell::GetSelectionText( BOOL bWholeWord )
{
    String aStrSelection;

    if ( pEditShell && pEditShell == GetMySubShell() )
    {
        aStrSelection = pEditShell->GetSelectionText( bWholeWord );
    }
    else
    {
        ScRange aRange;

        if ( GetViewData()->GetSimpleArea( aRange ) )
        {
            ScDocument* pDoc = GetViewData()->GetDocument();
            if ( bInFormatDialog && aRange.aStart.Row() != aRange.aEnd.Row() )
            {
                // Range auf eine Datenzeile begrenzen
                // (#48613# nur wenn der Aufruf aus einem Format-Dialog kommt)
                ScHorizontalCellIterator aIter( pDoc, aRange.aStart.Tab(),
                    aRange.aStart.Col(), aRange.aStart.Row(),
                    aRange.aEnd.Col(), aRange.aEnd.Row() );
                USHORT nCol, nRow;
                if ( aIter.GetNext( nCol, nRow ) )
                {
                    aRange.aStart.SetCol( nCol );
                    aRange.aStart.SetRow( nRow );
                    aRange.aEnd.SetRow( nRow );
                }
                else
                    aRange.aEnd = aRange.aStart;
            }

            ScImportExport aObj( pDoc, aRange );
            aObj.SetFormulas( GetViewData()->GetOptions().GetOption( VOPT_FORMULAS ) );
            aObj.ExportString( aStrSelection );

            aStrSelection.ConvertLineEnd( LINEEND_CR );

            //  Tab/CR durch Space ersetzen, wenn fuer Dialog oder per Basic/SelectionTextExt,
            //  oder wenn es eine einzelne Zeile ist.
            //  Sonst mehrzeilig mit Tabs beibehalten (z.B. Mail oder Basic/SelectionText).
            //  Fuer Mail werden die Tabs dann spaeter in (mehrere) Spaces gewandelt.

            if ( bInFormatDialog || bWholeWord || aRange.aEnd.Row() == aRange.aStart.Row() )
            {
                xub_StrLen nAt;
                while (  (nAt = aStrSelection.Search( CHAR_CR )) != STRING_NOTFOUND )
                    aStrSelection.SetChar( nAt, ' ' );
                while (  (nAt = aStrSelection.Search( '\t' )) != STRING_NOTFOUND )
                    aStrSelection.SetChar( nAt, ' ' );

                aStrSelection.EraseTrailingChars( ' ' );
            }
        }
    }

    return aStrSelection;
}

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

void ScTabViewShell::InsertURL( const String& rName, const String& rURL, const String& rTarget,
                                USHORT nMode )
{
    SvxLinkInsertMode eMode = (SvxLinkInsertMode) nMode;
    BOOL bAsText = ( eMode != HLINK_BUTTON );       // Default ist jetzt Text

    if ( bAsText )
    {
        //  InsertBookmark ?
        InsertURLField( rName, rURL, rTarget );
    }
    else
    {
        SC_MOD()->InputEnterHandler();
        InsertURLButton( rName, rURL, rTarget );
    }
}

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

// wenn CLOOKs: -> mit <editview.hxx> <flditem.hxx>in neue tabvwsh

void lcl_SelectFieldAfterInsert( EditView& rView )
{
    ESelection aSel = rView.GetSelection();
    if ( aSel.nStartPos == aSel.nEndPos && aSel.nStartPos > 0 )
    {
        //  Cursor is behind the inserted field -> extend selection to the left

        --aSel.nStartPos;
        rView.SetSelection( aSel );
    }
}

void ScTabViewShell::InsertURLField( const String& rName, const String& rURL, const String& rTarget )
{
    SvxURLField aURLField( rURL, rName, SVXURLFORMAT_REPR );
    aURLField.SetTargetFrame( rTarget );
    SvxFieldItem aURLItem( aURLField );

    ScViewData*     pViewData   = GetViewData();
    ScTabView*      pView       = pViewData->GetView();
    ScModule*       pScMod      = SC_MOD();
    ScInputHandler* pHdl        = pScMod->GetInputHdl( pViewData->GetViewShell() );

    BOOL bSelectFirst = FALSE;
    if ( !pScMod->IsEditMode() )
    {
        // single url in cell is shown in the dialog and replaced
        bSelectFirst = HasBookmarkAtCursor( NULL );
        pScMod->SetInputMode( SC_INPUT_TABLE );
    }

    EditView*       pTopView    = pHdl->GetTopView();
    EditView*       pTableView  = pHdl->GetTableView();
    DBG_ASSERT( pTopView || pTableView, "No EditView" );

    if ( bSelectFirst )
    {
        if ( pTopView )
            pTopView->SetSelection( ESelection(0,0,0,1) );
        if ( pTableView )
            pTableView->SetSelection( ESelection(0,0,0,1) );
    }

    pHdl->DataChanging();

    if ( pTopView )
    {
        pTopView->InsertField( aURLItem );
        lcl_SelectFieldAfterInsert( *pTopView );
    }
    if ( pTableView )
    {
        pTableView->InsertField( aURLItem );
        lcl_SelectFieldAfterInsert( *pTableView );
    }

    pHdl->DataChanged();
}

void ScTabViewShell::ExecSearch( SfxRequest& rReq )
{
    SfxBindings&        rBindings   = GetViewFrame()->GetBindings();
    const SfxItemSet*   pReqArgs    = rReq.GetArgs();
    USHORT              nSlot       = rReq.GetSlot();
    const SfxPoolItem*  pItem;

    switch ( nSlot )
    {
        case FID_SEARCH_NOW:
            {
                const SfxPoolItem* pItem;
                if ( pReqArgs &&
                     SFX_ITEM_SET == pReqArgs->GetItemState(SID_SEARCH_ITEM, FALSE, &pItem) )
                {
                    DBG_ASSERT( pItem->ISA(SvxSearchItem), "falsches Item" );
                    const SvxSearchItem* pSearchItem = (const SvxSearchItem*) pItem;

                    ScGlobal::SetSearchItem( *pSearchItem );
                    SearchAndReplace( pSearchItem, TRUE, rReq.IsAPI() );
                    rReq.Done();
                }
            }
            break;

        case SID_SEARCH_ITEM:
            if (pReqArgs && SFX_ITEM_SET ==
                            pReqArgs->GetItemState(SID_SEARCH_ITEM, FALSE, &pItem))
            {
                //  Search-Item merken
                DBG_ASSERT( pItem->ISA(SvxSearchItem), "falsches Item" );
                ScGlobal::SetSearchItem( *(const SvxSearchItem*) pItem );
            }
            else
                DBG_ERROR("SID_SEARCH_ITEM ohne Parameter");
            break;
        case FID_SEARCH:
        case FID_REPLACE:
        case FID_REPLACE_ALL:
        case FID_SEARCH_ALL:
            {
                if (pReqArgs && SFX_ITEM_SET == pReqArgs->GetItemState(nSlot, FALSE, &pItem))
                {
                    //  SearchItem holen

                    SvxSearchItem aSearchItem = ScGlobal::GetSearchItem();

                    //  SearchItem fuellen

                    aSearchItem.SetSearchString(((SfxStringItem*)pItem)->GetValue());
                    if(SFX_ITEM_SET == pReqArgs->GetItemState(FN_PARAM_1, FALSE, &pItem))
                        aSearchItem.SetReplaceString(((SfxStringItem*)pItem)->GetValue());

                    if (nSlot == FID_SEARCH)
                        aSearchItem.SetCommand(SVX_SEARCHCMD_FIND);
                    else if(nSlot == FID_REPLACE)
                        aSearchItem.SetCommand(SVX_SEARCHCMD_REPLACE);
                    else if(nSlot == FID_REPLACE_ALL)
                        aSearchItem.SetCommand(SVX_SEARCHCMD_REPLACE_ALL);
                    else
                        aSearchItem.SetCommand(SVX_SEARCHCMD_FIND_ALL);

                    //  Request ausfuehren (dabei wird das SearchItem gespeichert)

                    aSearchItem.SetWhich(SID_SEARCH_ITEM);
                    GetViewData()->GetDispatcher().Execute( FID_SEARCH_NOW,
                            rReq.IsAPI() ? SFX_CALLMODE_API|SFX_CALLMODE_SYNCHRON :
                                            SFX_CALLMODE_STANDARD,
                            &aSearchItem, 0L );
                }
                else
                {
                    GetViewData()->GetDispatcher().Execute(
                            SID_SEARCH_DLG, SFX_CALLMODE_ASYNCHRON|SFX_CALLMODE_RECORD );
                }
            }
            break;
        case FID_REPEAT_SEARCH:
            {
                //  nochmal mit ScGlobal::GetSearchItem()

                SvxSearchItem aSearchItem = ScGlobal::GetSearchItem();
                aSearchItem.SetWhich(SID_SEARCH_ITEM);
                GetViewData()->GetDispatcher().Execute( FID_SEARCH_NOW,
                        rReq.IsAPI() ? SFX_CALLMODE_API|SFX_CALLMODE_SYNCHRON :
                                        SFX_CALLMODE_STANDARD,
                        &aSearchItem, 0L );
            }
            break;
//      case FID_SEARCH_COUNT:
    }
}

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

<commit_msg>#91216# InsertURL: InsertBookmark if view is not active<commit_after>/*************************************************************************
 *
 *  $RCSfile: tabvwshe.cxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: nn $ $Date: 2001-08-20 17:04:25 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifdef PCH
#include "ui_pch.hxx"
#endif

#pragma hdrstop

// INCLUDE ---------------------------------------------------------------

#ifndef _EEITEM_HXX //autogen
#include <svx/eeitem.hxx>
#endif

#include "scitems.hxx"
#define ITEMID_FIELD EE_FEATURE_FIELD
#include <svx/editview.hxx>
#include <svx/flditem.hxx>
#include <svx/hlnkitem.hxx>
#include <svx/srchitem.hxx>
#include <sfx2/dispatch.hxx>
#include <sfx2/viewfrm.hxx>
#include <sfx2/request.hxx>
#include <sfx2/objface.hxx>
#include <svtools/stritem.hxx>

#include "tabvwsh.hxx"
#include "sc.hrc"
#include "scmod.hxx"
#include "impex.hxx"
#include "editsh.hxx"
#include "dociter.hxx"
#include "inputhdl.hxx"

//==================================================================

String __EXPORT ScTabViewShell::GetSelectionText( BOOL bWholeWord )
{
    String aStrSelection;

    if ( pEditShell && pEditShell == GetMySubShell() )
    {
        aStrSelection = pEditShell->GetSelectionText( bWholeWord );
    }
    else
    {
        ScRange aRange;

        if ( GetViewData()->GetSimpleArea( aRange ) )
        {
            ScDocument* pDoc = GetViewData()->GetDocument();
            if ( bInFormatDialog && aRange.aStart.Row() != aRange.aEnd.Row() )
            {
                // Range auf eine Datenzeile begrenzen
                // (#48613# nur wenn der Aufruf aus einem Format-Dialog kommt)
                ScHorizontalCellIterator aIter( pDoc, aRange.aStart.Tab(),
                    aRange.aStart.Col(), aRange.aStart.Row(),
                    aRange.aEnd.Col(), aRange.aEnd.Row() );
                USHORT nCol, nRow;
                if ( aIter.GetNext( nCol, nRow ) )
                {
                    aRange.aStart.SetCol( nCol );
                    aRange.aStart.SetRow( nRow );
                    aRange.aEnd.SetRow( nRow );
                }
                else
                    aRange.aEnd = aRange.aStart;
            }

            ScImportExport aObj( pDoc, aRange );
            aObj.SetFormulas( GetViewData()->GetOptions().GetOption( VOPT_FORMULAS ) );
            aObj.ExportString( aStrSelection );

            aStrSelection.ConvertLineEnd( LINEEND_CR );

            //  Tab/CR durch Space ersetzen, wenn fuer Dialog oder per Basic/SelectionTextExt,
            //  oder wenn es eine einzelne Zeile ist.
            //  Sonst mehrzeilig mit Tabs beibehalten (z.B. Mail oder Basic/SelectionText).
            //  Fuer Mail werden die Tabs dann spaeter in (mehrere) Spaces gewandelt.

            if ( bInFormatDialog || bWholeWord || aRange.aEnd.Row() == aRange.aStart.Row() )
            {
                xub_StrLen nAt;
                while (  (nAt = aStrSelection.Search( CHAR_CR )) != STRING_NOTFOUND )
                    aStrSelection.SetChar( nAt, ' ' );
                while (  (nAt = aStrSelection.Search( '\t' )) != STRING_NOTFOUND )
                    aStrSelection.SetChar( nAt, ' ' );

                aStrSelection.EraseTrailingChars( ' ' );
            }
        }
    }

    return aStrSelection;
}

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

void ScTabViewShell::InsertURL( const String& rName, const String& rURL, const String& rTarget,
                                USHORT nMode )
{
    SvxLinkInsertMode eMode = (SvxLinkInsertMode) nMode;
    BOOL bAsText = ( eMode != HLINK_BUTTON );       // Default ist jetzt Text

    if ( bAsText )
    {
        if ( GetViewData()->IsActive() )
        {
            //  if the view is active, always use InsertURLField, which starts EditMode
            //  and selects the URL, so it can be changed from the URL bar / dialog

            InsertURLField( rName, rURL, rTarget );
        }
        else
        {
            //  #91216# if the view is not active, InsertURLField doesn't work
            //  -> use InsertBookmark to directly manipulate cell content
            //  bTryReplace=TRUE -> if cell contains only one URL, replace it

            USHORT nPosX = GetViewData()->GetCurX();
            USHORT nPosY = GetViewData()->GetCurY();
            InsertBookmark( rName, rURL, nPosX, nPosY, &rTarget, TRUE );
        }
    }
    else
    {
        SC_MOD()->InputEnterHandler();
        InsertURLButton( rName, rURL, rTarget );
    }
}

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

// wenn CLOOKs: -> mit <editview.hxx> <flditem.hxx>in neue tabvwsh

void lcl_SelectFieldAfterInsert( EditView& rView )
{
    ESelection aSel = rView.GetSelection();
    if ( aSel.nStartPos == aSel.nEndPos && aSel.nStartPos > 0 )
    {
        //  Cursor is behind the inserted field -> extend selection to the left

        --aSel.nStartPos;
        rView.SetSelection( aSel );
    }
}

void ScTabViewShell::InsertURLField( const String& rName, const String& rURL, const String& rTarget )
{
    SvxURLField aURLField( rURL, rName, SVXURLFORMAT_REPR );
    aURLField.SetTargetFrame( rTarget );
    SvxFieldItem aURLItem( aURLField );

    ScViewData*     pViewData   = GetViewData();
    ScTabView*      pView       = pViewData->GetView();
    ScModule*       pScMod      = SC_MOD();
    ScInputHandler* pHdl        = pScMod->GetInputHdl( pViewData->GetViewShell() );

    BOOL bSelectFirst = FALSE;
    if ( !pScMod->IsEditMode() )
    {
        // single url in cell is shown in the dialog and replaced
        bSelectFirst = HasBookmarkAtCursor( NULL );
        pScMod->SetInputMode( SC_INPUT_TABLE );
    }

    EditView*       pTopView    = pHdl->GetTopView();
    EditView*       pTableView  = pHdl->GetTableView();
    DBG_ASSERT( pTopView || pTableView, "No EditView" );

    if ( bSelectFirst )
    {
        if ( pTopView )
            pTopView->SetSelection( ESelection(0,0,0,1) );
        if ( pTableView )
            pTableView->SetSelection( ESelection(0,0,0,1) );
    }

    pHdl->DataChanging();

    if ( pTopView )
    {
        pTopView->InsertField( aURLItem );
        lcl_SelectFieldAfterInsert( *pTopView );
    }
    if ( pTableView )
    {
        pTableView->InsertField( aURLItem );
        lcl_SelectFieldAfterInsert( *pTableView );
    }

    pHdl->DataChanged();
}

void ScTabViewShell::ExecSearch( SfxRequest& rReq )
{
    SfxBindings&        rBindings   = GetViewFrame()->GetBindings();
    const SfxItemSet*   pReqArgs    = rReq.GetArgs();
    USHORT              nSlot       = rReq.GetSlot();
    const SfxPoolItem*  pItem;

    switch ( nSlot )
    {
        case FID_SEARCH_NOW:
            {
                const SfxPoolItem* pItem;
                if ( pReqArgs &&
                     SFX_ITEM_SET == pReqArgs->GetItemState(SID_SEARCH_ITEM, FALSE, &pItem) )
                {
                    DBG_ASSERT( pItem->ISA(SvxSearchItem), "falsches Item" );
                    const SvxSearchItem* pSearchItem = (const SvxSearchItem*) pItem;

                    ScGlobal::SetSearchItem( *pSearchItem );
                    SearchAndReplace( pSearchItem, TRUE, rReq.IsAPI() );
                    rReq.Done();
                }
            }
            break;

        case SID_SEARCH_ITEM:
            if (pReqArgs && SFX_ITEM_SET ==
                            pReqArgs->GetItemState(SID_SEARCH_ITEM, FALSE, &pItem))
            {
                //  Search-Item merken
                DBG_ASSERT( pItem->ISA(SvxSearchItem), "falsches Item" );
                ScGlobal::SetSearchItem( *(const SvxSearchItem*) pItem );
            }
            else
                DBG_ERROR("SID_SEARCH_ITEM ohne Parameter");
            break;
        case FID_SEARCH:
        case FID_REPLACE:
        case FID_REPLACE_ALL:
        case FID_SEARCH_ALL:
            {
                if (pReqArgs && SFX_ITEM_SET == pReqArgs->GetItemState(nSlot, FALSE, &pItem))
                {
                    //  SearchItem holen

                    SvxSearchItem aSearchItem = ScGlobal::GetSearchItem();

                    //  SearchItem fuellen

                    aSearchItem.SetSearchString(((SfxStringItem*)pItem)->GetValue());
                    if(SFX_ITEM_SET == pReqArgs->GetItemState(FN_PARAM_1, FALSE, &pItem))
                        aSearchItem.SetReplaceString(((SfxStringItem*)pItem)->GetValue());

                    if (nSlot == FID_SEARCH)
                        aSearchItem.SetCommand(SVX_SEARCHCMD_FIND);
                    else if(nSlot == FID_REPLACE)
                        aSearchItem.SetCommand(SVX_SEARCHCMD_REPLACE);
                    else if(nSlot == FID_REPLACE_ALL)
                        aSearchItem.SetCommand(SVX_SEARCHCMD_REPLACE_ALL);
                    else
                        aSearchItem.SetCommand(SVX_SEARCHCMD_FIND_ALL);

                    //  Request ausfuehren (dabei wird das SearchItem gespeichert)

                    aSearchItem.SetWhich(SID_SEARCH_ITEM);
                    GetViewData()->GetDispatcher().Execute( FID_SEARCH_NOW,
                            rReq.IsAPI() ? SFX_CALLMODE_API|SFX_CALLMODE_SYNCHRON :
                                            SFX_CALLMODE_STANDARD,
                            &aSearchItem, 0L );
                }
                else
                {
                    GetViewData()->GetDispatcher().Execute(
                            SID_SEARCH_DLG, SFX_CALLMODE_ASYNCHRON|SFX_CALLMODE_RECORD );
                }
            }
            break;
        case FID_REPEAT_SEARCH:
            {
                //  nochmal mit ScGlobal::GetSearchItem()

                SvxSearchItem aSearchItem = ScGlobal::GetSearchItem();
                aSearchItem.SetWhich(SID_SEARCH_ITEM);
                GetViewData()->GetDispatcher().Execute( FID_SEARCH_NOW,
                        rReq.IsAPI() ? SFX_CALLMODE_API|SFX_CALLMODE_SYNCHRON :
                                        SFX_CALLMODE_STANDARD,
                        &aSearchItem, 0L );
            }
            break;
//      case FID_SEARCH_COUNT:
    }
}

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

<|endoftext|>