<commit_before>/////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////
/*
    Copyright (C) 2017 LePtitDev
    All rights reserved.

    This software may be modified and distributed under the terms
    of the BSD license.  See the LICENSE file for details.

    Author: Arthur Ferré <leptitdev.com>
*/
/////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////

#include "type.hpp"
#include "object.hpp"
#include "memory.hpp"
#include "basic_memory.hpp"
#include "../script/state.hpp"
#include "../streamer.hpp"

LiteScript::Memory::Memory() :
    first_nfull(0), count(0), Count(count)
{
    for (short i = 0; i < LITESCRIPT_MEMORY_SIZE; i++) {
        this->arr[i] = nullptr;
        this->nfull[i] = i + (short)1;
    }
}

LiteScript::Memory::~Memory() {
    for (unsigned int i = 0; i < LITESCRIPT_MEMORY_SIZE; i++) {
        if (this->arr[i] != nullptr)
            delete (LiteScript::_BasicMemory_1 *)this->arr[i];
    }
}

LiteScript::Variable LiteScript::Memory::Create(Type &type) {
    // Si le premier non plein n'existe pas, on le crée
    if (this->arr[this->first_nfull] == nullptr)
        this->arr[this->first_nfull] = (void *)(new LiteScript::_BasicMemory_1(*this));
    // On crée l'objet
    Variable result = ((LiteScript::_BasicMemory_1 *)(this->arr[this->first_nfull]))->Create(type, ((unsigned int)this->first_nfull) << 16);
    // Si le premier non plein devient plein, on passe au suivant
    if (((LiteScript::_BasicMemory_1 *)(this->arr[this->first_nfull]))->isFull())
        this->first_nfull = this->nfull[this->first_nfull];
    // On incrémente le compteur d'objets
    this->count++;
    // On retourne la variable
    return result;
}

void LiteScript::Memory::Remove(unsigned int id) {
    unsigned int block = id >> 16;
    if (this->arr[block] != nullptr) {
        bool wasFull = ((LiteScript::_BasicMemory_1 *) (this->arr[block]))->isFull();
        unsigned int nb = ((LiteScript::_BasicMemory_1 *) (this->arr[block]))->Count;
        ((LiteScript::_BasicMemory_1 *) (this->arr[block]))->Remove(id & 0xffff);
        // Si le block n'est plus plein, on le place en premier
        if (wasFull && !((LiteScript::_BasicMemory_1 *) (this->arr[block]))->isFull()) {
            this->nfull[block] = this->first_nfull;
            this->first_nfull = (short)block;
        }
        // Si le nombre d'objet à diminué, on décrémente le compteur
        if (nb != ((LiteScript::_BasicMemory_1 *) (this->arr[block]))->Count)
            this->count--;
    }
}

LiteScript::Nullable<LiteScript::Variable> LiteScript::Memory::GetVariable(unsigned int id) {
    unsigned int block = id >> 16;
    if (this->arr[block] != nullptr)
        return Nullable<Variable>(((LiteScript::_BasicMemory_1 *) (this->arr[block]))->GetVariable(id & 0xffff));
    return Nullable<Variable>();
}

void LiteScript::Memory::GarbageCollector(const State& state) {
    std::vector<const State *> tmp;
    tmp.push_back(&state);
    this->GarbageCollector(1, tmp.data());
}

void LiteScript::Memory::GarbageCollector(int scount, const State ** sarray) {
    for (unsigned int i = 0; i < LITESCRIPT_MEMORY_SIZE; i++) {
        if (this->arr[i] != nullptr)
            ((LiteScript::_BasicMemory_1 *)this->arr[i])->FlagsInit();
    }
    for (unsigned int i = 0, sz = (unsigned int)scount; i < sz; i++)
        sarray[i]->GarbageCollector(&Memory::ProtectVariable);
    for (unsigned int i = 0; i < LITESCRIPT_MEMORY_SIZE; i++) {
        if (this->arr[i] != nullptr)
            ((LiteScript::_BasicMemory_1 *)this->arr[i])->FlagsErase();
    }
}

void LiteScript::Memory::Save(std::ostream &stream, const Memory &memory) {
    for (unsigned int i = 0; i < LITESCRIPT_MEMORY_SIZE; i++) {
        if (memory.arr[i] != nullptr)
            ((LiteScript::_BasicMemory_1 *)memory.arr[i])->FlagsInit();
    }
    const std::vector<Type *>& types = Type::GetTypesList();
    OStreamer::Write<unsigned int>(stream, types.size());
    for (unsigned int i = 0, sz = types.size(); i < sz; i++)
        stream << types[i]->GetName() << (uint8_t)0;
    OStreamer::Write<unsigned int>(stream, memory.count);
    for (unsigned int i = 0; i < LITESCRIPT_MEMORY_SIZE; i++) {
        if (memory.arr[i] != nullptr)
            ((LiteScript::_BasicMemory_1 *)memory.arr[i])->Save(stream, memory.SaveVariable);
    }
}

LiteScript::Memory LiteScript::Memory::Load(std::istream &stream) {
    Memory memory;
    const std::vector<Type *>& types = Type::GetTypesList();
    unsigned int sz = IStreamer::Read<unsigned int>(stream);
    std::string str;
    unsigned char c;
    for (unsigned int i = 0; i < sz; i++) {
        str.clear();
        while ((c = (unsigned char)stream.get()) != 0)
            str += c;
        for (unsigned int j = 0, sz_j = types.size(); j < sz_j; j++) {
            if (str == types[j]->GetName()) {
                memory.type_list.push_back(types[j]);
                break;
            }
        }
        if (i == memory.type_list.size())
            return memory;
    }
    sz = IStreamer::Read<unsigned int>(stream);
    for (; memory.count < sz; memory.count++)
        memory.LoadVariable(stream);
    return memory;
}

bool LiteScript::Memory::ProtectVariable(unsigned int i) {
    unsigned int block = i >> 16;
    if (this->arr[block] != nullptr)
        return ((LiteScript::_BasicMemory_1 *)(this->arr[block]))->FlagsProtect(i & 0xffff);
    return false;
}

bool LiteScript::Memory::SaveVariable(std::ostream &stream, unsigned int i) {
    OStreamer streamer(stream);
    unsigned int block = i >> 16;
    if (this->arr[block] != nullptr) {
        if (((LiteScript::_BasicMemory_1 *) (this->arr[block]))->FlagsProtect(i & 0xffff)) {
            streamer << (unsigned char)0 << i;
            return true;
        }
        else {
            Variable v = *this->GetVariable(i);
            streamer << (unsigned char)1 << v->ID << v->GetType().GetID();
            v->GetType().Save(stream, *v, Memory::SaveVariable);
            return false;
        }
    }
    return false;
}

unsigned int LiteScript::Memory::LoadVariable(std::istream &stream) {
    if (stream.get() == 0)
        return IStreamer::Read<unsigned int>(stream);
    else {
        unsigned int i = IStreamer::Read<unsigned int>(stream);
        unsigned int block = i >> 16;
        if (this->arr[block] == nullptr) {
            this->arr[block] = (void *)(new LiteScript::_BasicMemory_1(*this));
            this->nfull[block] = this->first_nfull;
            this->first_nfull = (short)block;
        }
        Object& obj = ((LiteScript::_BasicMemory_1 *)(this->arr[block]))->CreateAt(i);
        this->count++;
        if (((LiteScript::_BasicMemory_1 *)(this->arr[block]))->isFull()) {
            unsigned int j;
            for (j = 0; j < LITESCRIPT_MEMORY_SIZE && this->nfull[j] != block; j++);
            if (j == LITESCRIPT_MEMORY_SIZE)
                this->first_nfull = this->nfull[block];
            else
                this->nfull[j] = this->nfull[block];
        }
        this->type_list[IStreamer::Read<unsigned int>(stream)]->Load(stream, obj, Memory::LoadVariable);
        return i;
    }
}<commit_msg>Correction erreur compilation<commit_after>/////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////
/*
    Copyright (C) 2017 LePtitDev
    All rights reserved.

    This software may be modified and distributed under the terms
    of the BSD license.  See the LICENSE file for details.

    Author: Arthur Ferré <leptitdev.com>
*/
/////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////

#include "type.hpp"
#include "object.hpp"
#include "memory.hpp"
#include "basic_memory.hpp"
#include "../script/state.hpp"
#include "../streamer.hpp"

LiteScript::Memory::Memory() :
    first_nfull(0), count(0), Count(count)
{
    for (short i = 0; i < LITESCRIPT_MEMORY_SIZE; i++) {
        this->arr[i] = nullptr;
        this->nfull[i] = i + (short)1;
    }
}

LiteScript::Memory::~Memory() {
    for (unsigned int i = 0; i < LITESCRIPT_MEMORY_SIZE; i++) {
        if (this->arr[i] != nullptr)
            delete (LiteScript::_BasicMemory_1 *)this->arr[i];
    }
}

LiteScript::Variable LiteScript::Memory::Create(Type &type) {
    // Si le premier non plein n'existe pas, on le crée
    if (this->arr[this->first_nfull] == nullptr)
        this->arr[this->first_nfull] = (void *)(new LiteScript::_BasicMemory_1(*this));
    // On crée l'objet
    Variable result = ((LiteScript::_BasicMemory_1 *)(this->arr[this->first_nfull]))->Create(type, ((unsigned int)this->first_nfull) << 16);
    // Si le premier non plein devient plein, on passe au suivant
    if (((LiteScript::_BasicMemory_1 *)(this->arr[this->first_nfull]))->isFull())
        this->first_nfull = this->nfull[this->first_nfull];
    // On incrémente le compteur d'objets
    this->count++;
    // On retourne la variable
    return result;
}

void LiteScript::Memory::Remove(unsigned int id) {
    unsigned int block = id >> 16;
    if (this->arr[block] != nullptr) {
        bool wasFull = ((LiteScript::_BasicMemory_1 *) (this->arr[block]))->isFull();
        unsigned int nb = ((LiteScript::_BasicMemory_1 *) (this->arr[block]))->Count;
        ((LiteScript::_BasicMemory_1 *) (this->arr[block]))->Remove(id & 0xffff);
        // Si le block n'est plus plein, on le place en premier
        if (wasFull && !((LiteScript::_BasicMemory_1 *) (this->arr[block]))->isFull()) {
            this->nfull[block] = this->first_nfull;
            this->first_nfull = (short)block;
        }
        // Si le nombre d'objet à diminué, on décrémente le compteur
        if (nb != ((LiteScript::_BasicMemory_1 *) (this->arr[block]))->Count)
            this->count--;
    }
}

LiteScript::Nullable<LiteScript::Variable> LiteScript::Memory::GetVariable(unsigned int id) {
    unsigned int block = id >> 16;
    if (this->arr[block] != nullptr)
        return Nullable<Variable>(((LiteScript::_BasicMemory_1 *) (this->arr[block]))->GetVariable(id & 0xffff));
    return Nullable<Variable>();
}

void LiteScript::Memory::GarbageCollector(const State& state) {
    std::vector<const State *> tmp;
    tmp.push_back(&state);
    this->GarbageCollector(1, tmp.data());
}

void LiteScript::Memory::GarbageCollector(int scount, const State ** sarray) {
    for (unsigned int i = 0; i < LITESCRIPT_MEMORY_SIZE; i++) {
        if (this->arr[i] != nullptr)
            ((LiteScript::_BasicMemory_1 *)this->arr[i])->FlagsInit();
    }
    for (unsigned int i = 0, sz = (unsigned int)scount; i < sz; i++)
        sarray[i]->GarbageCollector(&Memory::ProtectVariable);
    for (unsigned int i = 0; i < LITESCRIPT_MEMORY_SIZE; i++) {
        if (this->arr[i] != nullptr)
            ((LiteScript::_BasicMemory_1 *)this->arr[i])->FlagsErase();
    }
}

void LiteScript::Memory::Save(std::ostream &stream, const Memory &memory) {
    for (unsigned int i = 0; i < LITESCRIPT_MEMORY_SIZE; i++) {
        if (memory.arr[i] != nullptr)
            ((LiteScript::_BasicMemory_1 *)memory.arr[i])->FlagsInit();
    }
    const std::vector<Type *>& types = Type::GetTypesList();
    OStreamer::Write<unsigned int>(stream, types.size());
    for (unsigned int i = 0, sz = types.size(); i < sz; i++)
        stream << types[i]->GetName() << (uint8_t)0;
    OStreamer::Write<unsigned int>(stream, memory.count);
    for (unsigned int i = 0; i < LITESCRIPT_MEMORY_SIZE; i++) {
        if (memory.arr[i] != nullptr)
            ((LiteScript::_BasicMemory_1 *)memory.arr[i])->Save(stream, &Memory::SaveVariable);
    }
}

LiteScript::Memory LiteScript::Memory::Load(std::istream &stream) {
    Memory memory;
    const std::vector<Type *>& types = Type::GetTypesList();
    unsigned int sz = IStreamer::Read<unsigned int>(stream);
    std::string str;
    unsigned char c;
    for (unsigned int i = 0; i < sz; i++) {
        str.clear();
        while ((c = (unsigned char)stream.get()) != 0)
            str += c;
        for (unsigned int j = 0, sz_j = types.size(); j < sz_j; j++) {
            if (str == types[j]->GetName()) {
                memory.type_list.push_back(types[j]);
                break;
            }
        }
        if (i == memory.type_list.size())
            return memory;
    }
    sz = IStreamer::Read<unsigned int>(stream);
    for (; memory.count < sz; memory.count++)
        memory.LoadVariable(stream);
    return memory;
}

bool LiteScript::Memory::ProtectVariable(unsigned int i) {
    unsigned int block = i >> 16;
    if (this->arr[block] != nullptr)
        return ((LiteScript::_BasicMemory_1 *)(this->arr[block]))->FlagsProtect(i & 0xffff);
    return false;
}

bool LiteScript::Memory::SaveVariable(std::ostream &stream, unsigned int i) {
    OStreamer streamer(stream);
    unsigned int block = i >> 16;
    if (this->arr[block] != nullptr) {
        if (((LiteScript::_BasicMemory_1 *) (this->arr[block]))->FlagsProtect(i & 0xffff)) {
            streamer << (unsigned char)0 << i;
            return true;
        }
        else {
            Variable v = *this->GetVariable(i);
            streamer << (unsigned char)1 << v->ID << v->GetType().GetID();
            v->GetType().Save(stream, *v, &Memory::SaveVariable);
            return false;
        }
    }
    return false;
}

unsigned int LiteScript::Memory::LoadVariable(std::istream &stream) {
    if (stream.get() == 0)
        return IStreamer::Read<unsigned int>(stream);
    else {
        unsigned int i = IStreamer::Read<unsigned int>(stream);
        unsigned int block = i >> 16;
        if (this->arr[block] == nullptr) {
            this->arr[block] = (void *)(new LiteScript::_BasicMemory_1(*this));
            this->nfull[block] = this->first_nfull;
            this->first_nfull = (short)block;
        }
        Object& obj = ((LiteScript::_BasicMemory_1 *)(this->arr[block]))->CreateAt(i);
        this->count++;
        if (((LiteScript::_BasicMemory_1 *)(this->arr[block]))->isFull()) {
            unsigned int j;
            for (j = 0; j < LITESCRIPT_MEMORY_SIZE && this->nfull[j] != block; j++);
            if (j == LITESCRIPT_MEMORY_SIZE)
                this->first_nfull = this->nfull[block];
            else
                this->nfull[j] = this->nfull[block];
        }
        this->type_list[IStreamer::Read<unsigned int>(stream)]->Load(stream, obj, &Memory::LoadVariable);
        return i;
    }
}
<|endoftext|>


<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you 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 .
 */

#include <sfx2/dialoghelper.hxx>
#include <svx/paraprev.hxx>
#include <vcl/builder.hxx>
#include <vcl/settings.hxx>

// class SvxParaPrevWindow -----------------------------------------------

SvxParaPrevWindow::SvxParaPrevWindow( Window* pParent,  WinBits nBits) :

    Window( pParent, nBits),

    nLeftMargin     ( 0 ),
    nRightMargin    ( 0 ),
    nFirstLineOfst  ( 0 ),
    nUpper          ( 0 ),
    nLower          ( 0 ),
    eAdjust         ( SVX_ADJUST_LEFT ),
    eLastLine       ( SVX_ADJUST_LEFT ),
    eLine           ( SVX_PREV_LINESPACE_1 ),
    nLineVal        ( 0 )

{
    // Count in Twips by default
    SetMapMode( MapMode( MAP_TWIP ) );

    aSize = Size( 11905, 16837 );

    SetBorderStyle( WINDOW_BORDER_MONO );
}

extern "C" SAL_DLLPUBLIC_EXPORT Window* SAL_CALL makeSvxParaPrevWindow(Window *pParent, VclBuilder::stringmap &)
{
    return new SvxParaPrevWindow(pParent, WB_BORDER);
}

Size SvxParaPrevWindow::GetOptimalSize() const
{
    return getParagraphPreviewOptimalSize(this);
}

void SvxParaPrevWindow::Paint( const Rectangle& )
{
    DrawParagraph( true );
}

#define DEF_MARGIN  120

void SvxParaPrevWindow::DrawParagraph( bool bAll )
{
    Size aWinSize = GetOutputSizePixel();
    aWinSize = PixelToLogic( aWinSize );
    Size aTmp(1, 1);
    aTmp = PixelToLogic(aTmp);
    aWinSize.Width() -= aTmp.Width() /2;
    aWinSize.Height() -= aTmp.Height() /2;

    const StyleSettings& rStyleSettings = GetSettings().GetStyleSettings();
    const Color& rWinColor = rStyleSettings.GetWindowColor();
    Color aGrayColor(COL_LIGHTGRAY);

    SetFillColor( Color( rWinColor ) );
    if( bAll )
        DrawRect( Rectangle( Point(), aWinSize ) );

    SetLineColor();

    long nH = aWinSize.Height() / 19;
    Size aLineSiz( aWinSize.Width() - DEF_MARGIN, nH ),
         aSiz = aLineSiz;
    Point aPnt;
    aPnt.X() = DEF_MARGIN / 2;
    SetFillColor( aGrayColor );

    for ( sal_uInt16 i = 0; i < 9; ++i )
    {
        if ( 3 == i )
        {
            SetFillColor( Color( COL_GRAY ) );
            long nTop = nUpper * aLineSiz.Height() / aSize.Height();
            aPnt.Y() += nTop * 2;
        }

        if ( 6 == i )
            SetFillColor( aGrayColor );

        if ( 3 <= i && 6 > i )
        {
            long nLeft = nLeftMargin * aLineSiz.Width() / aSize.Width();
            long nFirst = nFirstLineOfst * aLineSiz.Width() / aSize.Width();
            long nTmp = nLeft + nFirst;

            if ( 3 == i )
            {
                aPnt.X() += nTmp;
                aSiz.Width() -= nTmp;
            }
            else
            {
                aPnt.X() += nLeft;
                aSiz.Width() -= nLeft;
            }
            long nRight = nRightMargin * aLineSiz.Width() / aSize.Width();
            aSiz.Width() -= nRight;
        }

        if ( 4 == i || 5 == i || 6 == i )
        {
            switch ( eLine )
            {
                case SVX_PREV_LINESPACE_1:                      break;
                case SVX_PREV_LINESPACE_15: aPnt.Y() += nH / 2; break;
                case SVX_PREV_LINESPACE_2:  aPnt.Y() += nH;     break;

                case SVX_PREV_LINESPACE_PROP:
                case SVX_PREV_LINESPACE_MIN:
                case SVX_PREV_LINESPACE_DURCH:                  break;
            }
        }

        aPnt.Y() += nH;

        if ( (3 <= i) && (5 >= i) )
        {
            long nLW;
            switch( i )
            {
                case 3: nLW = aLineSiz.Width() * 8 / 10;    break;
                case 4: nLW = aLineSiz.Width() * 9 / 10;    break;
                case 5: nLW = aLineSiz.Width() / 2;         break;
            }

            if ( nLW > aSiz.Width() )
                nLW = aSiz.Width();

            switch ( eAdjust )
            {
                case SVX_ADJUST_LEFT:
                    break;
                case SVX_ADJUST_RIGHT:
                    aPnt.X() += ( aSiz.Width() - nLW );
                    break;
                case SVX_ADJUST_CENTER:
                    aPnt.X() += ( aSiz.Width() - nLW ) / 2;
                    break;
                default: ; //prevent warning
            }
            if( SVX_ADJUST_BLOCK == eAdjust )
            {
                if( 5 == i )
                {
                    switch( eLastLine )
                    {
                        case SVX_ADJUST_LEFT:
                            break;
                        case SVX_ADJUST_RIGHT:
                            aPnt.X() += ( aSiz.Width() - nLW );
                            break;
                        case SVX_ADJUST_CENTER:
                            aPnt.X() += ( aSiz.Width() - nLW ) / 2;
                            break;
                        case SVX_ADJUST_BLOCK:
                            nLW = aSiz.Width();
                            break;
                        default: ; //prevent warning
                    }
                }
                else
                    nLW = aSiz.Width();
            }
            aSiz.Width() = nLW;
        }

        Rectangle aRect( aPnt, aSiz );

        if ( Lines[i] != aRect || bAll )
        {
            if ( !bAll )
            {
                Color aFillCol = GetFillColor();
                SetFillColor( rWinColor );
                DrawRect( Lines[i] );
                SetFillColor( aFillCol );
            }
            DrawRect( aRect );
            Lines[i] = aRect;
        }

        if ( 5 == i )
        {
            long nBottom = nLower * aLineSiz.Height() / aSize.Height();
            aPnt.Y() += nBottom * 2;
        }

        aPnt.Y() += nH;
        // Reset, recalculate for each line
        aPnt.X() = DEF_MARGIN / 2;
        aSiz = aLineSiz;
    }
}

#undef DEF_MARGIN

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>warning C4701: potentially uninitialized local variable used<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you 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 .
 */

#include <sfx2/dialoghelper.hxx>
#include <svx/paraprev.hxx>
#include <vcl/builder.hxx>
#include <vcl/settings.hxx>

// class SvxParaPrevWindow -----------------------------------------------

SvxParaPrevWindow::SvxParaPrevWindow( Window* pParent,  WinBits nBits) :

    Window( pParent, nBits),

    nLeftMargin     ( 0 ),
    nRightMargin    ( 0 ),
    nFirstLineOfst  ( 0 ),
    nUpper          ( 0 ),
    nLower          ( 0 ),
    eAdjust         ( SVX_ADJUST_LEFT ),
    eLastLine       ( SVX_ADJUST_LEFT ),
    eLine           ( SVX_PREV_LINESPACE_1 ),
    nLineVal        ( 0 )

{
    // Count in Twips by default
    SetMapMode( MapMode( MAP_TWIP ) );

    aSize = Size( 11905, 16837 );

    SetBorderStyle( WINDOW_BORDER_MONO );
}

extern "C" SAL_DLLPUBLIC_EXPORT Window* SAL_CALL makeSvxParaPrevWindow(Window *pParent, VclBuilder::stringmap &)
{
    return new SvxParaPrevWindow(pParent, WB_BORDER);
}

Size SvxParaPrevWindow::GetOptimalSize() const
{
    return getParagraphPreviewOptimalSize(this);
}

void SvxParaPrevWindow::Paint( const Rectangle& )
{
    DrawParagraph( true );
}

#define DEF_MARGIN  120

void SvxParaPrevWindow::DrawParagraph( bool bAll )
{
    Size aWinSize = GetOutputSizePixel();
    aWinSize = PixelToLogic( aWinSize );
    Size aTmp(1, 1);
    aTmp = PixelToLogic(aTmp);
    aWinSize.Width() -= aTmp.Width() /2;
    aWinSize.Height() -= aTmp.Height() /2;

    const StyleSettings& rStyleSettings = GetSettings().GetStyleSettings();
    const Color& rWinColor = rStyleSettings.GetWindowColor();
    Color aGrayColor(COL_LIGHTGRAY);

    SetFillColor( Color( rWinColor ) );
    if( bAll )
        DrawRect( Rectangle( Point(), aWinSize ) );

    SetLineColor();

    long nH = aWinSize.Height() / 19;
    Size aLineSiz( aWinSize.Width() - DEF_MARGIN, nH ),
         aSiz = aLineSiz;
    Point aPnt;
    aPnt.X() = DEF_MARGIN / 2;
    SetFillColor( aGrayColor );

    for ( sal_uInt16 i = 0; i < 9; ++i )
    {
        if ( 3 == i )
        {
            SetFillColor( Color( COL_GRAY ) );
            long nTop = nUpper * aLineSiz.Height() / aSize.Height();
            aPnt.Y() += nTop * 2;
        }

        if ( 6 == i )
            SetFillColor( aGrayColor );

        if ( 3 <= i && 6 > i )
        {
            long nLeft = nLeftMargin * aLineSiz.Width() / aSize.Width();
            long nFirst = nFirstLineOfst * aLineSiz.Width() / aSize.Width();
            long nTmp = nLeft + nFirst;

            if ( 3 == i )
            {
                aPnt.X() += nTmp;
                aSiz.Width() -= nTmp;
            }
            else
            {
                aPnt.X() += nLeft;
                aSiz.Width() -= nLeft;
            }
            long nRight = nRightMargin * aLineSiz.Width() / aSize.Width();
            aSiz.Width() -= nRight;
        }

        if ( 4 == i || 5 == i || 6 == i )
        {
            switch ( eLine )
            {
                case SVX_PREV_LINESPACE_1:                      break;
                case SVX_PREV_LINESPACE_15: aPnt.Y() += nH / 2; break;
                case SVX_PREV_LINESPACE_2:  aPnt.Y() += nH;     break;

                case SVX_PREV_LINESPACE_PROP:
                case SVX_PREV_LINESPACE_MIN:
                case SVX_PREV_LINESPACE_DURCH:                  break;
            }
        }

        aPnt.Y() += nH;

        if ( (3 <= i) && (5 >= i) )
        {
            long nLW = long();
            switch( i )
            {
                case 3: nLW = aLineSiz.Width() * 8 / 10;    break;
                case 4: nLW = aLineSiz.Width() * 9 / 10;    break;
                case 5: nLW = aLineSiz.Width() / 2;         break;
            }

            if ( nLW > aSiz.Width() )
                nLW = aSiz.Width();

            switch ( eAdjust )
            {
                case SVX_ADJUST_LEFT:
                    break;
                case SVX_ADJUST_RIGHT:
                    aPnt.X() += ( aSiz.Width() - nLW );
                    break;
                case SVX_ADJUST_CENTER:
                    aPnt.X() += ( aSiz.Width() - nLW ) / 2;
                    break;
                default: ; //prevent warning
            }
            if( SVX_ADJUST_BLOCK == eAdjust )
            {
                if( 5 == i )
                {
                    switch( eLastLine )
                    {
                        case SVX_ADJUST_LEFT:
                            break;
                        case SVX_ADJUST_RIGHT:
                            aPnt.X() += ( aSiz.Width() - nLW );
                            break;
                        case SVX_ADJUST_CENTER:
                            aPnt.X() += ( aSiz.Width() - nLW ) / 2;
                            break;
                        case SVX_ADJUST_BLOCK:
                            nLW = aSiz.Width();
                            break;
                        default: ; //prevent warning
                    }
                }
                else
                    nLW = aSiz.Width();
            }
            aSiz.Width() = nLW;
        }

        Rectangle aRect( aPnt, aSiz );

        if ( Lines[i] != aRect || bAll )
        {
            if ( !bAll )
            {
                Color aFillCol = GetFillColor();
                SetFillColor( rWinColor );
                DrawRect( Lines[i] );
                SetFillColor( aFillCol );
            }
            DrawRect( aRect );
            Lines[i] = aRect;
        }

        if ( 5 == i )
        {
            long nBottom = nLower * aLineSiz.Height() / aSize.Height();
            aPnt.Y() += nBottom * 2;
        }

        aPnt.Y() += nH;
        // Reset, recalculate for each line
        aPnt.X() = DEF_MARGIN / 2;
        aSiz = aLineSiz;
    }
}

#undef DEF_MARGIN

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>


<commit_before>/*
 * RandomConn.hpp
 *
 *  Created on: Apr 27, 2009
 *      Author: rasmussn
 */

#ifndef RANDOMCONN_HPP_
#define RANDOMCONN_HPP_

#include "HyPerConn.hpp"

namespace PV {

enum RandDistType {
   UNDEFINED = 0,
   UNIFORM = 1,
   GAUSSIAN = 2
};

class RandomConn: public PV::HyPerConn {
public:
   RandomConn(const char * name, HyPerCol * hc, HyPerLayer * pre,
              HyPerLayer * post, int channel);

   RandomConn(const char * name, HyPerCol * hc, HyPerLayer * pre,
              HyPerLayer * post, int channel, RandDistType distrib);

   virtual int initializeWeights(const char * filename);
   int initializeUniformWeights(int seed);
   int uniformWeights(PVPatch * wp, float wMin, float wMax, int seed);
   int initializeGaussianWeights(int seed);
   int gaussianWeights(PVPatch *wp, float mean, float stdev, int seed);
   int gaussianWeightsMA(PVPatch *wp, float mean, float stdev, long *);
   float randgauss(float mean, float stdev);
   float randgaussMA(float mean, float stdev, long *);
private:
   float          wMin;
   RandDistType   randDistType; // the type of distribution
   float          wGaussMean;   // mean of the Gaussian distribution
   float          wGaussStdev;  // std deviation of the Gaussian distribution
   long           idum;

   void InitRandomConn(const char *name, HyPerCol *hc,
                       HyPerLayer *pre, HyPerLayer *post, int channel);

   float ranf();
   float ran1(long *);
};

}

#endif /* RANDOMCONN_HPP_ */
<commit_msg>Shreyas's changes to this class: includes a constructor with a distribution type as argument.<commit_after>/*
 * RandomConn.hpp
 *
 *  Created on: Apr 27, 2009
 *      Author: rasmussn
 */

#ifndef RANDOMCONN_HPP_
#define RANDOMCONN_HPP_

#include "HyPerConn.hpp"

namespace PV {

enum RandDistType {
   UNDEFINED = 0,
   UNIFORM = 1,
   GAUSSIAN = 2
};

class RandomConn: public PV::HyPerConn {
public:
   RandomConn(const char * name, HyPerCol * hc, HyPerLayer * pre,
              HyPerLayer * post, int channel);

   RandomConn(const char * name, HyPerCol * hc, HyPerLayer * pre,
              HyPerLayer * post, int channel, RandDistType distrib);

   virtual int initializeWeights(const char * filename);
   int initializeUniformWeights(int seed);
   int uniformWeights(PVPatch * wp, float wMin, float wMax, int seed);
   int initializeGaussianWeights(int seed);
   int gaussianWeights(PVPatch *wp, float mean, float stdev, int seed);
   int gaussianWeightsMA(PVPatch *wp, float mean, float stdev, long *);
   float randgauss(float mean, float stdev);
   float randgaussMA(float mean, float stdev, long *);
private:
   float          wMin;
   RandDistType   randDistType; // the type of distribution
   float          wGaussMean;   // mean of the Gaussian distribution
   float          wGaussStdev;  // std deviation of the Gaussian distribution
   long           idum;

   float ranf();
   float ran1(long *);
};

}

#endif /* RANDOMCONN_HPP_ */
<|endoftext|>


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

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_svx.hxx"

#include "txencbox.hxx"
#include "txenctab.hxx"
#include "dialogs.hrc"

#ifndef SVX_DBCHARSETHELPER_HXX
#include "dbcharsethelper.hxx"
#endif
#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif
#ifndef _RTL_TENCINFO_H
#include <rtl/tencinfo.h>
#endif
#ifndef _RTL_LOCALE_H_
#include <rtl/locale.h>
#endif
#ifndef _OSL_NLSUPPORT_H_
#include <osl/nlsupport.h>
#endif

//========================================================================
//  class SvxTextEncodingBox
//========================================================================

SvxTextEncodingBox::SvxTextEncodingBox( Window* pParent, const ResId& rResId )
    :
    ListBox( pParent, rResId )
{
    m_pEncTable = new SvxTextEncodingTable;
}

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

SvxTextEncodingBox::~SvxTextEncodingBox()
{
    delete m_pEncTable;
}

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

USHORT SvxTextEncodingBox::EncodingToPos_Impl( rtl_TextEncoding nEnc ) const
{
    USHORT nCount = GetEntryCount();
    for ( USHORT i=0; i<nCount; i++ )
    {
        if ( nEnc == rtl_TextEncoding( (ULONG)GetEntryData(i) ) )
            return i;
    }
    return LISTBOX_ENTRY_NOTFOUND;
}

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

void SvxTextEncodingBox::FillFromTextEncodingTable(
        sal_Bool bExcludeImportSubsets, sal_uInt32 nExcludeInfoFlags,
        sal_uInt32 nButIncludeInfoFlags )
{
    rtl_TextEncodingInfo aInfo;
    aInfo.StructSize = sizeof(rtl_TextEncodingInfo);
    USHORT nCount = m_pEncTable->Count();
    for ( USHORT j=0; j<nCount; j++ )
    {
        BOOL bInsert = TRUE;
        rtl_TextEncoding nEnc = rtl_TextEncoding( m_pEncTable->GetValue( j ) );
        if ( nExcludeInfoFlags )
        {
            if ( !rtl_getTextEncodingInfo( nEnc, &aInfo ) )
                bInsert = FALSE;
            else
            {
                if ( (aInfo.Flags & nExcludeInfoFlags) == 0 )
                {
                    if ( (nExcludeInfoFlags & RTL_TEXTENCODING_INFO_UNICODE) &&
                            ((nEnc == RTL_TEXTENCODING_UCS2) ||
                            nEnc == RTL_TEXTENCODING_UCS4) )
                        bInsert = FALSE;    // InfoFlags don't work for Unicode :-(
                }
                else if ( (aInfo.Flags & nButIncludeInfoFlags) == 0 )
                    bInsert = FALSE;
            }
        }
        if ( bInsert )
        {
            if ( bExcludeImportSubsets )
            {
                switch ( nEnc )
                {
                    // subsets of RTL_TEXTENCODING_GB_18030
                    case RTL_TEXTENCODING_GB_2312 :
                    case RTL_TEXTENCODING_GBK :
                    case RTL_TEXTENCODING_MS_936 :
                        bInsert = FALSE;
                    break;
                }
            }
            if ( bInsert )
                InsertTextEncoding( nEnc, m_pEncTable->GetString( j ) );
        }
    }
}

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

void SvxTextEncodingBox::FillFromDbTextEncodingMap(
        sal_Bool bExcludeImportSubsets, sal_uInt32 nExcludeInfoFlags,
        sal_uInt32 nButIncludeInfoFlags )
{
    rtl_TextEncodingInfo aInfo;
    aInfo.StructSize = sizeof(rtl_TextEncodingInfo);
    svxform::ODataAccessCharsetHelper aCSH;
    ::std::vector< rtl_TextEncoding > aEncs;
    sal_Int32 nCount = aCSH.getSupportedTextEncodings( aEncs );
    for ( USHORT j=0; j<nCount; j++ )
    {
        BOOL bInsert = TRUE;
        rtl_TextEncoding nEnc = rtl_TextEncoding( aEncs[j] );
        if ( nExcludeInfoFlags )
        {
            if ( !rtl_getTextEncodingInfo( nEnc, &aInfo ) )
                bInsert = FALSE;
            else
            {
                if ( (aInfo.Flags & nExcludeInfoFlags) == 0 )
                {
                    if ( (nExcludeInfoFlags & RTL_TEXTENCODING_INFO_UNICODE) &&
                            ((nEnc == RTL_TEXTENCODING_UCS2) ||
                            nEnc == RTL_TEXTENCODING_UCS4) )
                        bInsert = FALSE;    // InfoFlags don't work for Unicode :-(
                }
                else if ( (aInfo.Flags & nButIncludeInfoFlags) == 0 )
                    bInsert = FALSE;
            }
        }
        if ( bInsert )
        {
            if ( bExcludeImportSubsets )
            {
                switch ( nEnc )
                {
                    // subsets of RTL_TEXTENCODING_GB_18030
                    case RTL_TEXTENCODING_GB_2312 :
                    case RTL_TEXTENCODING_GBK :
                    case RTL_TEXTENCODING_MS_936 :
                        bInsert = FALSE;
                    break;
                }
            }
            // CharsetMap offers a RTL_TEXTENCODING_DONTKNOW for internal use,
            // makes no sense here and would result in an empty string as list
            // entry.
            if ( bInsert && nEnc != RTL_TEXTENCODING_DONTKNOW )
                InsertTextEncoding( nEnc );
        }
    }
}

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

// static
rtl_TextEncoding SvxTextEncodingBox::GetBestMimeEncoding()
{
    const sal_Char* pCharSet = rtl_getBestMimeCharsetFromTextEncoding(
            gsl_getSystemTextEncoding() );
    if ( !pCharSet )
    {
        // If the system locale is unknown to us, e.g. LC_ALL=xx, match the UI
        // language if possible.
        ::com::sun::star::lang::Locale aLocale(
                Application::GetSettings().GetUILocale() );
        rtl_Locale * pLocale = rtl_locale_register( aLocale.Language.getStr(),
                aLocale.Country.getStr(), aLocale.Variant.getStr() );
        rtl_TextEncoding nEnc = osl_getTextEncodingFromLocale( pLocale );
        pCharSet = rtl_getBestMimeCharsetFromTextEncoding( nEnc );
    }
    rtl_TextEncoding nRet;
    if ( pCharSet )
        nRet = rtl_getTextEncodingFromMimeCharset( pCharSet );
    else
        nRet = RTL_TEXTENCODING_UTF8;
    return nRet;
}

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

void SvxTextEncodingBox::FillWithMimeAndSelectBest()
{
    FillFromTextEncodingTable( sal_False, 0xffffffff, RTL_TEXTENCODING_INFO_MIME );
    rtl_TextEncoding nEnc = GetBestMimeEncoding();
    SelectTextEncoding( nEnc );
}

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

void SvxTextEncodingBox::InsertTextEncoding( const rtl_TextEncoding nEnc,
            const String& rEntry, USHORT nPos )
{
    USHORT nAt = InsertEntry( rEntry, nPos );
    SetEntryData( nAt, (void*)(ULONG)nEnc );
}

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

void SvxTextEncodingBox::InsertTextEncoding( const rtl_TextEncoding nEnc, USHORT nPos )
{
    const String& rEntry = m_pEncTable->GetTextString( nEnc );
    if ( rEntry.Len() )
        InsertTextEncoding( nEnc, rEntry, nPos );
    else
    {
#ifdef DBG_UTIL
        ByteString aMsg( "SvxTextEncodingBox::InsertTextEncoding: no resource string for text encoding: " );
        aMsg += ByteString::CreateFromInt32( nEnc );
        DBG_ERRORFILE( aMsg.GetBuffer() );
#endif
    }
}

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

void SvxTextEncodingBox::RemoveTextEncoding( const rtl_TextEncoding nEnc )
{
    USHORT nAt = EncodingToPos_Impl( nEnc );

    if ( nAt != LISTBOX_ENTRY_NOTFOUND )
        RemoveEntry( nAt );
}

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

rtl_TextEncoding SvxTextEncodingBox::GetSelectTextEncoding() const
{
    USHORT nPos = GetSelectEntryPos();

    if ( nPos != LISTBOX_ENTRY_NOTFOUND )
        return rtl_TextEncoding( (ULONG)GetEntryData(nPos) );
    else
        return RTL_TEXTENCODING_DONTKNOW;
}

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

void SvxTextEncodingBox::SelectTextEncoding( const rtl_TextEncoding nEnc, BOOL bSelect )
{
    USHORT nAt = EncodingToPos_Impl( nEnc );

    if ( nAt != LISTBOX_ENTRY_NOTFOUND )
        SelectEntryPos( nAt, bSelect );
}

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

BOOL SvxTextEncodingBox::IsTextEncodingSelected( const rtl_TextEncoding nEnc ) const
{
    USHORT nAt = EncodingToPos_Impl( nEnc );

    if ( nAt != LISTBOX_ENTRY_NOTFOUND )
        return IsEntryPosSelected( nAt );
    else
        return FALSE;
}

<commit_msg>INTEGRATION: CWS sb59 (1.9.62); FILE MERGED 2006/08/18 12:02:52 sb 1.9.62.1: #i67487# Made code warning-free (wntmsci10).<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: txencbox.cxx,v $
 *
 *  $Revision: 1.11 $
 *
 *  last change: $Author: obo $ $Date: 2006-10-12 12:32:50 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_svx.hxx"

#include "txencbox.hxx"
#include "txenctab.hxx"
#include "dialogs.hrc"

#ifndef SVX_DBCHARSETHELPER_HXX
#include "dbcharsethelper.hxx"
#endif
#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif
#ifndef _RTL_TENCINFO_H
#include <rtl/tencinfo.h>
#endif
#ifndef _RTL_LOCALE_H_
#include <rtl/locale.h>
#endif
#ifndef _OSL_NLSUPPORT_H_
#include <osl/nlsupport.h>
#endif

//========================================================================
//  class SvxTextEncodingBox
//========================================================================

SvxTextEncodingBox::SvxTextEncodingBox( Window* pParent, const ResId& rResId )
    :
    ListBox( pParent, rResId )
{
    m_pEncTable = new SvxTextEncodingTable;
}

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

SvxTextEncodingBox::~SvxTextEncodingBox()
{
    delete m_pEncTable;
}

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

USHORT SvxTextEncodingBox::EncodingToPos_Impl( rtl_TextEncoding nEnc ) const
{
    USHORT nCount = GetEntryCount();
    for ( USHORT i=0; i<nCount; i++ )
    {
        if ( nEnc == rtl_TextEncoding( (ULONG)GetEntryData(i) ) )
            return i;
    }
    return LISTBOX_ENTRY_NOTFOUND;
}

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

void SvxTextEncodingBox::FillFromTextEncodingTable(
        sal_Bool bExcludeImportSubsets, sal_uInt32 nExcludeInfoFlags,
        sal_uInt32 nButIncludeInfoFlags )
{
    rtl_TextEncodingInfo aInfo;
    aInfo.StructSize = sizeof(rtl_TextEncodingInfo);
    sal_uInt32 nCount = m_pEncTable->Count();
    for ( sal_uInt32 j=0; j<nCount; j++ )
    {
        BOOL bInsert = TRUE;
        rtl_TextEncoding nEnc = rtl_TextEncoding( m_pEncTable->GetValue( j ) );
        if ( nExcludeInfoFlags )
        {
            if ( !rtl_getTextEncodingInfo( nEnc, &aInfo ) )
                bInsert = FALSE;
            else
            {
                if ( (aInfo.Flags & nExcludeInfoFlags) == 0 )
                {
                    if ( (nExcludeInfoFlags & RTL_TEXTENCODING_INFO_UNICODE) &&
                            ((nEnc == RTL_TEXTENCODING_UCS2) ||
                            nEnc == RTL_TEXTENCODING_UCS4) )
                        bInsert = FALSE;    // InfoFlags don't work for Unicode :-(
                }
                else if ( (aInfo.Flags & nButIncludeInfoFlags) == 0 )
                    bInsert = FALSE;
            }
        }
        if ( bInsert )
        {
            if ( bExcludeImportSubsets )
            {
                switch ( nEnc )
                {
                    // subsets of RTL_TEXTENCODING_GB_18030
                    case RTL_TEXTENCODING_GB_2312 :
                    case RTL_TEXTENCODING_GBK :
                    case RTL_TEXTENCODING_MS_936 :
                        bInsert = FALSE;
                    break;
                }
            }
            if ( bInsert )
                InsertTextEncoding( nEnc, m_pEncTable->GetString( j ) );
        }
    }
}

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

void SvxTextEncodingBox::FillFromDbTextEncodingMap(
        sal_Bool bExcludeImportSubsets, sal_uInt32 nExcludeInfoFlags,
        sal_uInt32 nButIncludeInfoFlags )
{
    rtl_TextEncodingInfo aInfo;
    aInfo.StructSize = sizeof(rtl_TextEncodingInfo);
    svxform::ODataAccessCharsetHelper aCSH;
    ::std::vector< rtl_TextEncoding > aEncs;
    sal_Int32 nCount = aCSH.getSupportedTextEncodings( aEncs );
    for ( USHORT j=0; j<nCount; j++ )
    {
        BOOL bInsert = TRUE;
        rtl_TextEncoding nEnc = rtl_TextEncoding( aEncs[j] );
        if ( nExcludeInfoFlags )
        {
            if ( !rtl_getTextEncodingInfo( nEnc, &aInfo ) )
                bInsert = FALSE;
            else
            {
                if ( (aInfo.Flags & nExcludeInfoFlags) == 0 )
                {
                    if ( (nExcludeInfoFlags & RTL_TEXTENCODING_INFO_UNICODE) &&
                            ((nEnc == RTL_TEXTENCODING_UCS2) ||
                            nEnc == RTL_TEXTENCODING_UCS4) )
                        bInsert = FALSE;    // InfoFlags don't work for Unicode :-(
                }
                else if ( (aInfo.Flags & nButIncludeInfoFlags) == 0 )
                    bInsert = FALSE;
            }
        }
        if ( bInsert )
        {
            if ( bExcludeImportSubsets )
            {
                switch ( nEnc )
                {
                    // subsets of RTL_TEXTENCODING_GB_18030
                    case RTL_TEXTENCODING_GB_2312 :
                    case RTL_TEXTENCODING_GBK :
                    case RTL_TEXTENCODING_MS_936 :
                        bInsert = FALSE;
                    break;
                }
            }
            // CharsetMap offers a RTL_TEXTENCODING_DONTKNOW for internal use,
            // makes no sense here and would result in an empty string as list
            // entry.
            if ( bInsert && nEnc != RTL_TEXTENCODING_DONTKNOW )
                InsertTextEncoding( nEnc );
        }
    }
}

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

// static
rtl_TextEncoding SvxTextEncodingBox::GetBestMimeEncoding()
{
    const sal_Char* pCharSet = rtl_getBestMimeCharsetFromTextEncoding(
            gsl_getSystemTextEncoding() );
    if ( !pCharSet )
    {
        // If the system locale is unknown to us, e.g. LC_ALL=xx, match the UI
        // language if possible.
        ::com::sun::star::lang::Locale aLocale(
                Application::GetSettings().GetUILocale() );
        rtl_Locale * pLocale = rtl_locale_register( aLocale.Language.getStr(),
                aLocale.Country.getStr(), aLocale.Variant.getStr() );
        rtl_TextEncoding nEnc = osl_getTextEncodingFromLocale( pLocale );
        pCharSet = rtl_getBestMimeCharsetFromTextEncoding( nEnc );
    }
    rtl_TextEncoding nRet;
    if ( pCharSet )
        nRet = rtl_getTextEncodingFromMimeCharset( pCharSet );
    else
        nRet = RTL_TEXTENCODING_UTF8;
    return nRet;
}

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

void SvxTextEncodingBox::FillWithMimeAndSelectBest()
{
    FillFromTextEncodingTable( sal_False, 0xffffffff, RTL_TEXTENCODING_INFO_MIME );
    rtl_TextEncoding nEnc = GetBestMimeEncoding();
    SelectTextEncoding( nEnc );
}

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

void SvxTextEncodingBox::InsertTextEncoding( const rtl_TextEncoding nEnc,
            const String& rEntry, USHORT nPos )
{
    USHORT nAt = InsertEntry( rEntry, nPos );
    SetEntryData( nAt, (void*)(ULONG)nEnc );
}

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

void SvxTextEncodingBox::InsertTextEncoding( const rtl_TextEncoding nEnc, USHORT nPos )
{
    const String& rEntry = m_pEncTable->GetTextString( nEnc );
    if ( rEntry.Len() )
        InsertTextEncoding( nEnc, rEntry, nPos );
    else
    {
#ifdef DBG_UTIL
        ByteString aMsg( "SvxTextEncodingBox::InsertTextEncoding: no resource string for text encoding: " );
        aMsg += ByteString::CreateFromInt32( nEnc );
        DBG_ERRORFILE( aMsg.GetBuffer() );
#endif
    }
}

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

void SvxTextEncodingBox::RemoveTextEncoding( const rtl_TextEncoding nEnc )
{
    USHORT nAt = EncodingToPos_Impl( nEnc );

    if ( nAt != LISTBOX_ENTRY_NOTFOUND )
        RemoveEntry( nAt );
}

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

rtl_TextEncoding SvxTextEncodingBox::GetSelectTextEncoding() const
{
    USHORT nPos = GetSelectEntryPos();

    if ( nPos != LISTBOX_ENTRY_NOTFOUND )
        return rtl_TextEncoding( (ULONG)GetEntryData(nPos) );
    else
        return RTL_TEXTENCODING_DONTKNOW;
}

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

void SvxTextEncodingBox::SelectTextEncoding( const rtl_TextEncoding nEnc, BOOL bSelect )
{
    USHORT nAt = EncodingToPos_Impl( nEnc );

    if ( nAt != LISTBOX_ENTRY_NOTFOUND )
        SelectEntryPos( nAt, bSelect );
}

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

BOOL SvxTextEncodingBox::IsTextEncodingSelected( const rtl_TextEncoding nEnc ) const
{
    USHORT nAt = EncodingToPos_Impl( nEnc );

    if ( nAt != LISTBOX_ENTRY_NOTFOUND )
        return IsEntryPosSelected( nAt );
    else
        return FALSE;
}

<|endoftext|>


<commit_before>/*****************************************************************************\
 *                        ANALYSIS PERFORMANCE TOOLS                         *
 *                               libparaver-api                              *
 *                       Paraver Main Computing Library                      *
 *****************************************************************************
 *     ___     This library is free software; you can redistribute it and/or *
 *    /  __         modify it under the terms of the GNU LGPL as published   *
 *   /  /  _____    by the Free Software Foundation; either version 2.1      *
 *  /  /  /     \   of the License, or (at your option) any later version.   *
 * (  (  ( B S C )                                                           *
 *  \  \  \_____/   This library is distributed in 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 LGPL 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA          *
 * The GNU LEsser General Public License is contained in the file COPYING.   *
 *                                 ---------                                 *
 *   Barcelona Supercomputing Center - Centro Nacional de Supercomputacion   *
\*****************************************************************************/

/* -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- *\
 | @file: $HeadURL$
 | @last_commit: $Date$
 | @version:     $Revision$
\* -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- */

#include "kwindow.h"
#include "intervalcpu.h"

KRecordList *IntervalCPU::init( TRecordTime initialTime, TCreateList create,
                                KRecordList *displayList )
{
  createList = create;
  currentValue = 0.0;

  if ( displayList == NULL )
    displayList = &myDisplayList;

  function = ( SemanticCPU * ) window->getSemanticFunction( level );
  functionThread = ( SemanticThread * ) window->getSemanticFunction( THREAD );
  functionComposeThread = ( SemanticCompose * ) window->getSemanticFunction( COMPOSETHREAD );

  if ( begin != NULL )
    delete begin;
  if ( end != NULL )
    delete end;

  threadState.clear();
  threadState.insert( threadState.begin(), window->getTrace()->totalThreads(), 0.0 );
// se necesitan los dos: getCPURecordByTime para el recorrido dentro del intervalo
// de CPU, y getThreadRecordByTime para los recorridos de los intervalos de thread
// !!! Para cada CPU hay que reiniciar los intervalos de thread que le tocan por si
//     acaso estamos dibujando por CPU !!!
// VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV
// !!! Aunque quizas seria mejor crear en cada intervalo de CPU todos sus posibles
//     intervalos de thread para que no hubiera conflicto entre ellos !!!
//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// Por culpa de funciones como Stacked se han de copiar (clonar) las funciones semanticas
// de los compose thread y thread en cada intervalo de CPU y que se asignen directamente
// a esos intervalos, debiendo cambiar los constructores o los init para que admitan
// esa posibilidad. No deberia haber ningun problema por usar el constructor por copia
// por defecto.
// Ademas en los intervalos de compose tambien se tiene que poder
// pàsar los intervalos de thread para que no use los de la ventana.
// El problema puede estar en la copia de iteradores que se hace en los compose,
// ya que mira si la ventana esta a nivel de recursos o procesos. Quizas hay que
// meter otra opcion que sea si el intervalo por debajo es thread que siempre copie
// los iteradores por procesos.
// Luego en la CPU (aqui) solo se miraran los tiempos y se usaran los propios iteradores
// de CPU para delimitar el intervalo semantico.
  begin = window->copyCPUIterator( window->getThreadRecordByTime( order ) );
  end = window->copyCPUIterator( begin );

  if ( ( !function->getInitFromBegin() ) && ( !functionThread->getInitFromBegin() ) &&
       ( initialTime > 0.0 ) )
    calcPrev( displayList, true );

  calcNext( displayList, true );
  while ( ( !end->isNull() ) && ( end->getTime() <= initialTime ) )
    calcNext( displayList );

  return displayList;
}

KRecordList *IntervalCPU::calcNext( KRecordList *displayList, bool initCalc )
{
  SemanticHighInfo highInfo;
  SemanticThreadInfo threadInfo;

  if ( displayList == NULL )
    displayList = &myDisplayList;

  if ( !initCalc )
  {
    *begin = *end;
  }

  threadInfo.callingInterval = getWindowInterval( THREAD, begin->getOrder() );
  highInfo.callingInterval = this;
  threadInfo.it = begin;
  if( !( window->passFilter( begin ) && functionThread->validRecord( begin ) ) )
    highInfo.values.push_back( threadState[ begin->getThread() ] );
  else if( begin->getType() == STATE + END )
    highInfo.values.push_back( 0.0 );
  else
  {
    SemanticHighInfo tmpHighInfo;
    tmpHighInfo.callingInterval = getWindowInterval( COMPOSETHREAD, begin->getThread() );
    tmpHighInfo.values.push_back( functionThread->execute( &threadInfo ) );
    threadState[ begin->getThread() ] = functionComposeThread->execute( &tmpHighInfo );
    highInfo.values.push_back( threadState[ begin->getThread() ] );
  }
  currentValue = function->execute( &highInfo );
  end = getNextRecord( end, displayList );

  return displayList;
}

KRecordList *IntervalCPU::calcPrev( KRecordList *displayList, bool initCalc )
{
  SemanticHighInfo highInfo;
  SemanticThreadInfo threadInfo;

  if ( displayList == NULL )
    displayList = &myDisplayList;

  if ( !initCalc )
  {
    *end = *begin;
  }

  begin = getPrevRecord( begin, displayList );
  highInfo.callingInterval = this;
  threadInfo.callingInterval = this;
  threadInfo.it = begin;
  highInfo.values.push_back( functionThread->execute( &threadInfo ) );
  currentValue = function->execute( &highInfo );

  if ( initCalc )
  {
    *end = *begin;
  }

  return displayList;
}

MemoryTrace::iterator *IntervalCPU::getNextRecord( MemoryTrace::iterator *it,
    KRecordList *displayList )
{
  TThreadOrder threadOrder = it->getThread();
  ++( *it );
  while ( !it->isNull() )
  {
    if ( window->passFilter( it ) )
    {
      if ( ( ( createList & CREATEEVENTS ) && ( it->getType() & EVENT ) )
           ||
           ( ( createList & CREATECOMMS ) && ( it->getType() & COMM ) ) )
        displayList->insert( window, it );

      if ( functionThread->validRecord( it ) )
        break;
    }
    if( it->getThread() != threadOrder )
      break;
    ++( *it );
  }

  if ( it->isNull() )
  {
    delete it;
    it = window->getCPUEndRecord( order );
  }

  return it;
}

MemoryTrace::iterator *IntervalCPU::getPrevRecord( MemoryTrace::iterator *it,
    KRecordList *displayList )
{
  --( *it );
  while ( !it->isNull() )
  {
    if ( window->passFilter( it ) )
    {
      if ( ( ( createList & CREATEEVENTS ) && ( it->getType() & EVENT ) )
           ||
           ( ( createList & CREATECOMMS ) && ( it->getType() & COMM ) ) )
        displayList->insert( window, it );

      if ( functionThread->validRecord( it ) )
        break;
    }
    --( *it );
  }

  if ( it->isNull() )
  {
    delete it;
    it = window->getCPUBeginRecord( order );
  }

  return it;
}

TWindowLevel IntervalCPU::getWindowLevel() const
{
  return window->getLevel();
}

Interval *IntervalCPU::getWindowInterval( TWindowLevel whichLevel,
    TObjectOrder whichOrder )
{
  return window->getLevelInterval( whichLevel, whichOrder );
}

bool IntervalCPU::IsDerivedWindow() const
{
  return window->isDerivedWindow();
}

TWindowLevel IntervalCPU::getComposeLevel( TWindowLevel whichLevel ) const
{
  return window->getComposeLevel( whichLevel );
}

KTrace *IntervalCPU::getWindowTrace() const
{
  return ( KTrace* )window->getTrace();
}

<commit_msg>*** empty log message ***<commit_after>/*****************************************************************************\
 *                        ANALYSIS PERFORMANCE TOOLS                         *
 *                               libparaver-api                              *
 *                       Paraver Main Computing Library                      *
 *****************************************************************************
 *     ___     This library is free software; you can redistribute it and/or *
 *    /  __         modify it under the terms of the GNU LGPL as published   *
 *   /  /  _____    by the Free Software Foundation; either version 2.1      *
 *  /  /  /     \   of the License, or (at your option) any later version.   *
 * (  (  ( B S C )                                                           *
 *  \  \  \_____/   This library is distributed in 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 LGPL 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA          *
 * The GNU LEsser General Public License is contained in the file COPYING.   *
 *                                 ---------                                 *
 *   Barcelona Supercomputing Center - Centro Nacional de Supercomputacion   *
\*****************************************************************************/

/* -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- *\
 | @file: $HeadURL$
 | @last_commit: $Date$
 | @version:     $Revision$
\* -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- */

#include "kwindow.h"
#include "intervalcpu.h"

KRecordList *IntervalCPU::init( TRecordTime initialTime, TCreateList create,
                                KRecordList *displayList )
{
  createList = create;
  currentValue = 0.0;

  if ( displayList == NULL )
    displayList = &myDisplayList;

  function = ( SemanticCPU * ) window->getSemanticFunction( level );
  functionThread = ( SemanticThread * ) window->getSemanticFunction( THREAD );
  functionComposeThread = ( SemanticCompose * ) window->getSemanticFunction( COMPOSETHREAD );

  if ( begin != NULL )
    delete begin;
  if ( end != NULL )
    delete end;

  threadState.clear();
  threadState.insert( threadState.begin(), window->getTrace()->totalThreads(), 0.0 );
// se necesitan los dos: getCPURecordByTime para el recorrido dentro del intervalo
// de CPU, y getThreadRecordByTime para los recorridos de los intervalos de thread
// !!! Para cada CPU hay que reiniciar los intervalos de thread que le tocan por si
//     acaso estamos dibujando por CPU !!!
// VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV
// !!! Aunque quizas seria mejor crear en cada intervalo de CPU todos sus posibles
//     intervalos de thread para que no hubiera conflicto entre ellos !!!
//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// Por culpa de funciones como Stacked se han de copiar (clonar) las funciones semanticas
// de los compose thread y thread en cada intervalo de CPU y que se asignen directamente
// a esos intervalos, debiendo cambiar los constructores o los init para que admitan
// esa posibilidad. No deberia haber ningun problema por usar el constructor por copia
// por defecto.
// Ademas en los intervalos de compose tambien se tiene que poder
// pàsar los intervalos de thread para que no use los de la ventana.
// El problema puede estar en la copia de iteradores que se hace en los compose,
// ya que mira si la ventana esta a nivel de recursos o procesos. Quizas hay que
// meter otra opcion que sea si el intervalo por debajo es thread que siempre copie
// los iteradores por procesos.
// Luego en la CPU (aqui) solo se miraran los tiempos y se usaran los propios iteradores
// de CPU para delimitar el intervalo semantico.
  begin = window->copyCPUIterator( window->getThreadRecordByTime( order ) );
  end = window->copyCPUIterator( begin );

  if ( ( !function->getInitFromBegin() ) && ( !functionThread->getInitFromBegin() ) &&
       ( !functionComposeThread->getInitFromBegin() ) && ( initialTime > 0.0 ) )
    calcPrev( displayList, true );

  calcNext( displayList, true );
  while ( ( !end->isNull() ) && ( end->getTime() <= initialTime ) )
    calcNext( displayList );

  return displayList;
}

KRecordList *IntervalCPU::calcNext( KRecordList *displayList, bool initCalc )
{
  SemanticHighInfo highInfo;
  SemanticThreadInfo threadInfo;

  if ( displayList == NULL )
    displayList = &myDisplayList;

  if ( !initCalc )
  {
    *begin = *end;
  }

  threadInfo.callingInterval = getWindowInterval( THREAD, begin->getOrder() );
  highInfo.callingInterval = this;
  threadInfo.it = begin;
  if( !( window->passFilter( begin ) && functionThread->validRecord( begin ) ) )
    highInfo.values.push_back( threadState[ begin->getThread() ] );
  else if( begin->getType() == STATE + END )
    highInfo.values.push_back( 0.0 );
  else
  {
    SemanticHighInfo tmpHighInfo;
    tmpHighInfo.callingInterval = getWindowInterval( COMPOSETHREAD, begin->getThread() );
    tmpHighInfo.values.push_back( functionThread->execute( &threadInfo ) );
    threadState[ begin->getThread() ] = functionComposeThread->execute( &tmpHighInfo );
    highInfo.values.push_back( threadState[ begin->getThread() ] );
  }
  currentValue = function->execute( &highInfo );
  end = getNextRecord( end, displayList );

  return displayList;
}

KRecordList *IntervalCPU::calcPrev( KRecordList *displayList, bool initCalc )
{
  SemanticHighInfo highInfo;
  SemanticThreadInfo threadInfo;

  if ( displayList == NULL )
    displayList = &myDisplayList;

  if ( !initCalc )
  {
    *end = *begin;
  }

  begin = getPrevRecord( begin, displayList );
  highInfo.callingInterval = this;
  threadInfo.callingInterval = this;
  threadInfo.it = begin;
  highInfo.values.push_back( functionThread->execute( &threadInfo ) );
  currentValue = function->execute( &highInfo );

  if ( initCalc )
  {
    *end = *begin;
  }

  return displayList;
}

MemoryTrace::iterator *IntervalCPU::getNextRecord( MemoryTrace::iterator *it,
    KRecordList *displayList )
{
  TThreadOrder threadOrder = it->getThread();
  ++( *it );
  while ( !it->isNull() )
  {
    if ( window->passFilter( it ) )
    {
      if ( ( ( createList & CREATEEVENTS ) && ( it->getType() & EVENT ) )
           ||
           ( ( createList & CREATECOMMS ) && ( it->getType() & COMM ) ) )
        displayList->insert( window, it );

      if ( functionThread->validRecord( it ) )
        break;
    }
    if( it->getThread() != threadOrder )
      break;
    ++( *it );
  }

  if ( it->isNull() )
  {
    delete it;
    it = window->getCPUEndRecord( order );
  }

  return it;
}

MemoryTrace::iterator *IntervalCPU::getPrevRecord( MemoryTrace::iterator *it,
    KRecordList *displayList )
{
  --( *it );
  while ( !it->isNull() )
  {
    if ( window->passFilter( it ) )
    {
      if ( ( ( createList & CREATEEVENTS ) && ( it->getType() & EVENT ) )
           ||
           ( ( createList & CREATECOMMS ) && ( it->getType() & COMM ) ) )
        displayList->insert( window, it );

      if ( functionThread->validRecord( it ) )
        break;
    }
    --( *it );
  }

  if ( it->isNull() )
  {
    delete it;
    it = window->getCPUBeginRecord( order );
  }

  return it;
}

TWindowLevel IntervalCPU::getWindowLevel() const
{
  return window->getLevel();
}

Interval *IntervalCPU::getWindowInterval( TWindowLevel whichLevel,
    TObjectOrder whichOrder )
{
  return window->getLevelInterval( whichLevel, whichOrder );
}

bool IntervalCPU::IsDerivedWindow() const
{
  return window->isDerivedWindow();
}

TWindowLevel IntervalCPU::getComposeLevel( TWindowLevel whichLevel ) const
{
  return window->getComposeLevel( whichLevel );
}

KTrace *IntervalCPU::getWindowTrace() const
{
  return ( KTrace* )window->getTrace();
}

<|endoftext|>


<commit_before>// Module:  Log4CPLUS
// File:    global-init.cxx
// Created: 5/2003
// Author:  Tad E. Smith
//
//
// Copyright 2003-2009 Tad E. Smith
//
// 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.

#include <log4cplus/config.hxx>
#include <log4cplus/config/windowsh-inc.h>
#include <log4cplus/logger.h>
#include <log4cplus/ndc.h>
#include <log4cplus/helpers/loglog.h>
#include <log4cplus/internal/internal.h>
#include <log4cplus/thread/impl/tls.h>
#include <iostream>

// Forward Declarations
namespace log4cplus
{

#ifdef UNICODE
LOG4CPLUS_EXPORT tostream & tcout = std::wcout;
LOG4CPLUS_EXPORT tostream & tcerr = std::wcerr;

#else
LOG4CPLUS_EXPORT tostream & tcout = std::cout;
LOG4CPLUS_EXPORT tostream & tcerr = std::cerr;

#endif // UNICODE

namespace internal
{

gft_scratch_pad::gft_scratch_pad ()
    : uc_q_str_valid (false)
    , q_str_valid (false)
    , s_str_valid (false)
{ }

gft_scratch_pad::~gft_scratch_pad ()
{ }

appender_sratch_pad::appender_sratch_pad ()
{ }

appender_sratch_pad::~appender_sratch_pad ()
{ }

per_thread_data::per_thread_data ()
    : macro_body_scratch_pad (macros_oss, forced_log_ev)
    , fnull (0)
{ }

per_thread_data::~per_thread_data ()
{ }

log4cplus::thread::impl::tls_key_type tls_storage_key;

#if ! defined (LOG4CPLUS_SINGLE_THREADED)

# if defined (LOG4CPLUS_THREAD_LOCAL_VAR)

LOG4CPLUS_THREAD_LOCAL_VAR per_thread_data * ptd = 0;

per_thread_data *
alloc_ptd ()
{
    per_thread_data * tmp = new per_thread_data;
    set_ptd (tmp);
    // This is a special hack. We set the keys' value to non-NULL to
    // get the ptd_cleanup_func to execute when this thread ends. The
    // cast is safe; the associated value will never be used if read
    // again using the key.
    thread::impl::tls_set_value (tls_storage_key,
        reinterpret_cast<void *>(1));

    return tmp;
}

#  else

per_thread_data *
alloc_ptd ()
{
    per_thread_data * tmp = new per_thread_data;
    set_ptd (tmp);
    return tmp;
}

#  endif

#else

std::auto_ptr<per_thread_data> ptd;

per_thread_data *
alloc_ptd ()
{
    per_thread_data * tmp = new per_thread_data;
    set_ptd (tmp);
    return tmp;
}

#endif

} // namespace internal

void initializeFactoryRegistry();

#if ! defined (LOG4CPLUS_SINGLE_THREADED)

//! Thread local storage clean up function for POSIX threads.
static
void
ptd_cleanup_func (void * arg)
{
    // Either it is a dummy value or it should be the per thread data
    // pointer we get from internal::get_ptd().
    assert (arg == reinterpret_cast<void *>(1)
        || arg == internal::get_ptd ());
    (void)arg;

    threadCleanup ();

    // Setting the value through the key here is necessary in case we
    // are using TLS using __thread or __declspec(thread) or similar
    // constructs with POSIX threads. Otherwise POSIX calls this cleanup
    // routine more than once if the value stays non-NULL after it returns.
    thread::impl::tls_set_value (internal::tls_storage_key, 0);
}

#endif

void initializeLog4cplus()
{
    static bool initialized = false;
    if (initialized)
        return;

#if ! defined (LOG4CPLUS_SINGLE_THREADED)

    internal::tls_storage_key = thread::impl::tls_init (ptd_cleanup_func);

#endif

    helpers::LogLog::getLogLog();
    getLogLevelManager ();
    getNDC();
    Logger::getRoot();
    initializeFactoryRegistry();

    initialized = true;
}

} // namespace log4cplus

#if defined (_WIN32) && defined (LOG4CPLUS_BUILD_DLL)

BOOL WINAPI DllMain(LOG4CPLUS_DLLMAIN_HINSTANCE hinstDLL,  // handle to DLL module
                    DWORD fdwReason,     // reason for calling function
                    LPVOID lpReserved )  // reserved
{
    namespace internal = log4cplus::internal;

    // Perform actions based on the reason for calling.
    switch( fdwReason )
    {
    case DLL_PROCESS_ATTACH:
    {
        log4cplus::initializeLog4cplus();
#if ! defined (LOG4CPLUS_SINGLE_THREADED)
        // Do thread-specific initialization for the main thread.
        internal::per_thread_data * ptd = new internal::per_thread_data;
        internal::set_ptd (ptd);
#endif
        break;
    }

    case DLL_THREAD_ATTACH:
    {
#if ! defined (LOG4CPLUS_SINGLE_THREADED)
        // Do thread-specific initialization.
        internal::per_thread_data * ptd = new internal::per_thread_data;
        internal::set_ptd (ptd);
#endif
        break;
    }

    case DLL_THREAD_DETACH:
    {
#if ! defined (LOG4CPLUS_SINGLE_THREADED)
        // Do thread-specific cleanup.
        log4cplus::threadCleanup ();
#endif
        break;
    }

    case DLL_PROCESS_DETACH:
    {
        // Perform any necessary cleanup.
#if ! defined (LOG4CPLUS_SINGLE_THREADED)
        // Do thread-specific cleanup.
        log4cplus::threadCleanup ();
#  if ! defined (LOG4CPLUS_THREAD_LOCAL_VAR)
        log4cplus::thread::impl::tls_cleanup (internal::tls_storage_key);
#  endif
#endif
        break;
    }

    }

    return TRUE;  // Successful DLL_PROCESS_ATTACH.
}

#else

namespace {

    struct _static_log4cplus_initializer
    {
        _static_log4cplus_initializer ()
        {
            log4cplus::initializeLog4cplus();
        }

        ~_static_log4cplus_initializer ()
        {
            // Last thread cleanup.
            log4cplus::threadCleanup ();
        }
    } static initializer;
}

#endif

namespace log4cplus
{

void
threadCleanup ()
{
#if ! defined (LOG4CPLUS_SINGLE_THREADED)
    // Do thread-specific cleanup.
    internal::per_thread_data * ptd = internal::get_ptd (false);
    delete ptd;
    internal::set_ptd (0);
#endif
}

} // namespace log4cplus
<commit_msg>global-init.cxx: Close per thread null file FILE instance when destroying per thread data.<commit_after>// Module:  Log4CPLUS
// File:    global-init.cxx
// Created: 5/2003
// Author:  Tad E. Smith
//
//
// Copyright 2003-2009 Tad E. Smith
//
// 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.

#include <log4cplus/config.hxx>
#include <log4cplus/config/windowsh-inc.h>
#include <log4cplus/logger.h>
#include <log4cplus/ndc.h>
#include <log4cplus/helpers/loglog.h>
#include <log4cplus/internal/internal.h>
#include <log4cplus/thread/impl/tls.h>
#include <cstdio>
#include <iostream>

// Forward Declarations
namespace log4cplus
{

#ifdef UNICODE
LOG4CPLUS_EXPORT tostream & tcout = std::wcout;
LOG4CPLUS_EXPORT tostream & tcerr = std::wcerr;

#else
LOG4CPLUS_EXPORT tostream & tcout = std::cout;
LOG4CPLUS_EXPORT tostream & tcerr = std::cerr;

#endif // UNICODE

namespace internal
{

gft_scratch_pad::gft_scratch_pad ()
    : uc_q_str_valid (false)
    , q_str_valid (false)
    , s_str_valid (false)
{ }

gft_scratch_pad::~gft_scratch_pad ()
{ }

appender_sratch_pad::appender_sratch_pad ()
{ }

appender_sratch_pad::~appender_sratch_pad ()
{ }

per_thread_data::per_thread_data ()
    : macro_body_scratch_pad (macros_oss, forced_log_ev)
    , fnull (0)
{ }

per_thread_data::~per_thread_data ()
{
    if (fnull)
        std::fclose (fnull);
}

log4cplus::thread::impl::tls_key_type tls_storage_key;

#if ! defined (LOG4CPLUS_SINGLE_THREADED)

# if defined (LOG4CPLUS_THREAD_LOCAL_VAR)

LOG4CPLUS_THREAD_LOCAL_VAR per_thread_data * ptd = 0;

per_thread_data *
alloc_ptd ()
{
    per_thread_data * tmp = new per_thread_data;
    set_ptd (tmp);
    // This is a special hack. We set the keys' value to non-NULL to
    // get the ptd_cleanup_func to execute when this thread ends. The
    // cast is safe; the associated value will never be used if read
    // again using the key.
    thread::impl::tls_set_value (tls_storage_key,
        reinterpret_cast<void *>(1));

    return tmp;
}

#  else

per_thread_data *
alloc_ptd ()
{
    per_thread_data * tmp = new per_thread_data;
    set_ptd (tmp);
    return tmp;
}

#  endif

#else

std::auto_ptr<per_thread_data> ptd;

per_thread_data *
alloc_ptd ()
{
    per_thread_data * tmp = new per_thread_data;
    set_ptd (tmp);
    return tmp;
}

#endif

} // namespace internal

void initializeFactoryRegistry();

#if ! defined (LOG4CPLUS_SINGLE_THREADED)

//! Thread local storage clean up function for POSIX threads.
static
void
ptd_cleanup_func (void * arg)
{
    // Either it is a dummy value or it should be the per thread data
    // pointer we get from internal::get_ptd().
    assert (arg == reinterpret_cast<void *>(1)
        || arg == internal::get_ptd ());
    (void)arg;

    threadCleanup ();

    // Setting the value through the key here is necessary in case we
    // are using TLS using __thread or __declspec(thread) or similar
    // constructs with POSIX threads. Otherwise POSIX calls this cleanup
    // routine more than once if the value stays non-NULL after it returns.
    thread::impl::tls_set_value (internal::tls_storage_key, 0);
}

#endif

void initializeLog4cplus()
{
    static bool initialized = false;
    if (initialized)
        return;

#if ! defined (LOG4CPLUS_SINGLE_THREADED)

    internal::tls_storage_key = thread::impl::tls_init (ptd_cleanup_func);

#endif

    helpers::LogLog::getLogLog();
    getLogLevelManager ();
    getNDC();
    Logger::getRoot();
    initializeFactoryRegistry();

    initialized = true;
}

} // namespace log4cplus

#if defined (_WIN32) && defined (LOG4CPLUS_BUILD_DLL)

BOOL WINAPI DllMain(LOG4CPLUS_DLLMAIN_HINSTANCE hinstDLL,  // handle to DLL module
                    DWORD fdwReason,     // reason for calling function
                    LPVOID lpReserved )  // reserved
{
    namespace internal = log4cplus::internal;

    // Perform actions based on the reason for calling.
    switch( fdwReason )
    {
    case DLL_PROCESS_ATTACH:
    {
        log4cplus::initializeLog4cplus();
#if ! defined (LOG4CPLUS_SINGLE_THREADED)
        // Do thread-specific initialization for the main thread.
        internal::per_thread_data * ptd = new internal::per_thread_data;
        internal::set_ptd (ptd);
#endif
        break;
    }

    case DLL_THREAD_ATTACH:
    {
#if ! defined (LOG4CPLUS_SINGLE_THREADED)
        // Do thread-specific initialization.
        internal::per_thread_data * ptd = new internal::per_thread_data;
        internal::set_ptd (ptd);
#endif
        break;
    }

    case DLL_THREAD_DETACH:
    {
#if ! defined (LOG4CPLUS_SINGLE_THREADED)
        // Do thread-specific cleanup.
        log4cplus::threadCleanup ();
#endif
        break;
    }

    case DLL_PROCESS_DETACH:
    {
        // Perform any necessary cleanup.
#if ! defined (LOG4CPLUS_SINGLE_THREADED)
        // Do thread-specific cleanup.
        log4cplus::threadCleanup ();
#  if ! defined (LOG4CPLUS_THREAD_LOCAL_VAR)
        log4cplus::thread::impl::tls_cleanup (internal::tls_storage_key);
#  endif
#endif
        break;
    }

    }

    return TRUE;  // Successful DLL_PROCESS_ATTACH.
}

#else

namespace {

    struct _static_log4cplus_initializer
    {
        _static_log4cplus_initializer ()
        {
            log4cplus::initializeLog4cplus();
        }

        ~_static_log4cplus_initializer ()
        {
            // Last thread cleanup.
            log4cplus::threadCleanup ();
        }
    } static initializer;
}

#endif

namespace log4cplus
{

void
threadCleanup ()
{
#if ! defined (LOG4CPLUS_SINGLE_THREADED)
    // Do thread-specific cleanup.
    internal::per_thread_data * ptd = internal::get_ptd (false);
    delete ptd;
    internal::set_ptd (0);
#endif
}

} // namespace log4cplus
<|endoftext|>


<commit_before><commit_msg>Fix file diaglog on windows<commit_after><|endoftext|>


<commit_before>/* Copyright 2013 - 2015 CyberTech Labs Ltd, Smirnov Mikhail, Kogutich Denis
 *
 * 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. */

#include "display.h"

#include <QtCore/QFileInfo>
#include <qglobal.h>

#if QT_VERSION < QT_VERSION_CHECK(5, 0, 0)
	#include <QtGui/QApplication>
#else
	#include <QtWidgets/QApplication>
#endif

#include <QsLog.h>

#include "src/guiWorker.h"

trikControl::Display::Display(const QString &mediaPath)
	: mMediaPath(mediaPath)
	, mGuiWorker(new GuiWorker())
{
	if (!qApp) {
		QLOG_ERROR() << "No QApplication object, it seems that trikControl is used from console application";
		return;
	}

	mGuiWorker->moveToThread(qApp->thread());
	QMetaObject::invokeMethod(mGuiWorker, "init");
}

trikControl::Display::~Display()
{
	QMetaObject::invokeMethod(mGuiWorker, "deleteWorker");
	qApp->thread()->wait(1000);
}

trikControl::DisplayWidgetInterface &trikControl::Display::graphicsWidget()
{
	return mGuiWorker->graphicsWidget();
}

void trikControl::Display::showImage(const QString &fileName)
{
	QFileInfo imageFile(fileName);
	const QString correctedFileName = imageFile.exists() ? fileName : mMediaPath + fileName;
	QMetaObject::invokeMethod(mGuiWorker, "showImage", Q_ARG(QString, correctedFileName));
}

void trikControl::Display::addLabel(const QString &text, int x, int y)
{
	QMetaObject::invokeMethod(mGuiWorker, "addLabel", Q_ARG(QString, text), Q_ARG(int, x), Q_ARG(int, y));
}

void trikControl::Display::removeLabels()
{
	QMetaObject::invokeMethod(mGuiWorker, "removeLabels");
}

void trikControl::Display::setBackground(const QString &color)
{
	QMetaObject::invokeMethod(mGuiWorker, "setBackground", Q_ARG(QString, color));
}

void trikControl::Display::hide()
{
	QMetaObject::invokeMethod(mGuiWorker, "hide");
}

void trikControl::Display::clear()
{
	QMetaObject::invokeMethod(mGuiWorker, "clear");
}

void trikControl::Display::reset()
{
	QMetaObject::invokeMethod(mGuiWorker, "reset");
}

void trikControl::Display::redraw()
{
	QMetaObject::invokeMethod(mGuiWorker, "redraw");
}

void trikControl::Display::drawLine(int x1, int y1, int x2, int y2)
{
	QMetaObject::invokeMethod(mGuiWorker, "drawLine", Q_ARG(int, x1), Q_ARG(int, y1), Q_ARG(int, x2), Q_ARG(int, y2));
}

void trikControl::Display::drawPoint(int x, int y)
{
	QMetaObject::invokeMethod(mGuiWorker, "drawPoint", Q_ARG(int, x), Q_ARG(int, y));
}

void trikControl::Display::drawRect(int x, int y, int width, int height, bool filled)
{
	QMetaObject::invokeMethod(mGuiWorker, "drawRect", Q_ARG(int, x), Q_ARG(int, y)
			, Q_ARG(int, width), Q_ARG(int, height), Q_ARG(bool, filled));
}

void trikControl::Display::drawEllipse(int x, int y, int width, int height, bool filled)
{
	QMetaObject::invokeMethod(mGuiWorker, "drawEllipse", Q_ARG(int, x), Q_ARG(int, y)
			, Q_ARG(int, width), Q_ARG(int, height), Q_ARG(bool, filled));
}

void trikControl::Display::drawArc(int x, int y, int width, int height, int startAngle, int spanAngle)
{
	QMetaObject::invokeMethod(mGuiWorker, "drawArc", Q_ARG(int, x), Q_ARG(int, y)
			, Q_ARG(int, width), Q_ARG(int, height), Q_ARG(int, startAngle), Q_ARG(int, spanAngle));
}

void trikControl::Display::setPainterColor(const QString &color)
{
	QMetaObject::invokeMethod(mGuiWorker, "setPainterColor", Q_ARG(QString, color));
}

void trikControl::Display::setPainterWidth(int penWidth)
{
	QMetaObject::invokeMethod(mGuiWorker, "setPainterWidth", Q_ARG(int, penWidth));
}
<commit_msg>Fix memory leak in UI thread<commit_after>/* Copyright 2013 - 2015 CyberTech Labs Ltd, Smirnov Mikhail, Kogutich Denis
 *
 * 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. */

#include "display.h"

#include <QtCore/QFileInfo>
#include <qglobal.h>

#if QT_VERSION < QT_VERSION_CHECK(5, 0, 0)
	#include <QtGui/QApplication>
#else
	#include <QtWidgets/QApplication>
#endif

#include <QsLog.h>

#include "src/guiWorker.h"

trikControl::Display::Display(const QString &mediaPath)
	: mMediaPath(mediaPath)
	, mGuiWorker(new GuiWorker())
{
	mGuiWorker->setParent(this);
	if (!qApp) {
		QLOG_ERROR() << "No QApplication object, it seems that trikControl is used from console application";
		return;
	}

	mGuiWorker->moveToThread(qApp->thread());
	QMetaObject::invokeMethod(mGuiWorker, "init");
}

trikControl::Display::~Display()
{
	QMetaObject::invokeMethod(mGuiWorker, "deleteWorker");
	qApp->thread()->wait(1000);
}

trikControl::DisplayWidgetInterface &trikControl::Display::graphicsWidget()
{
	return mGuiWorker->graphicsWidget();
}

void trikControl::Display::showImage(const QString &fileName)
{
	QFileInfo imageFile(fileName);
	const QString correctedFileName = imageFile.exists() ? fileName : mMediaPath + fileName;
	QMetaObject::invokeMethod(mGuiWorker, "showImage", Q_ARG(QString, correctedFileName));
}

void trikControl::Display::addLabel(const QString &text, int x, int y)
{
	QMetaObject::invokeMethod(mGuiWorker, "addLabel", Q_ARG(QString, text), Q_ARG(int, x), Q_ARG(int, y));
}

void trikControl::Display::removeLabels()
{
	QMetaObject::invokeMethod(mGuiWorker, "removeLabels");
}

void trikControl::Display::setBackground(const QString &color)
{
	QMetaObject::invokeMethod(mGuiWorker, "setBackground", Q_ARG(QString, color));
}

void trikControl::Display::hide()
{
	QMetaObject::invokeMethod(mGuiWorker, "hide");
}

void trikControl::Display::clear()
{
	QMetaObject::invokeMethod(mGuiWorker, "clear");
}

void trikControl::Display::reset()
{
	QMetaObject::invokeMethod(mGuiWorker, "reset");
}

void trikControl::Display::redraw()
{
	QMetaObject::invokeMethod(mGuiWorker, "redraw");
}

void trikControl::Display::drawLine(int x1, int y1, int x2, int y2)
{
	QMetaObject::invokeMethod(mGuiWorker, "drawLine", Q_ARG(int, x1), Q_ARG(int, y1), Q_ARG(int, x2), Q_ARG(int, y2));
}

void trikControl::Display::drawPoint(int x, int y)
{
	QMetaObject::invokeMethod(mGuiWorker, "drawPoint", Q_ARG(int, x), Q_ARG(int, y));
}

void trikControl::Display::drawRect(int x, int y, int width, int height, bool filled)
{
	QMetaObject::invokeMethod(mGuiWorker, "drawRect", Q_ARG(int, x), Q_ARG(int, y)
			, Q_ARG(int, width), Q_ARG(int, height), Q_ARG(bool, filled));
}

void trikControl::Display::drawEllipse(int x, int y, int width, int height, bool filled)
{
	QMetaObject::invokeMethod(mGuiWorker, "drawEllipse", Q_ARG(int, x), Q_ARG(int, y)
			, Q_ARG(int, width), Q_ARG(int, height), Q_ARG(bool, filled));
}

void trikControl::Display::drawArc(int x, int y, int width, int height, int startAngle, int spanAngle)
{
	QMetaObject::invokeMethod(mGuiWorker, "drawArc", Q_ARG(int, x), Q_ARG(int, y)
			, Q_ARG(int, width), Q_ARG(int, height), Q_ARG(int, startAngle), Q_ARG(int, spanAngle));
}

void trikControl::Display::setPainterColor(const QString &color)
{
	QMetaObject::invokeMethod(mGuiWorker, "setPainterColor", Q_ARG(QString, color));
}

void trikControl::Display::setPainterWidth(int penWidth)
{
	QMetaObject::invokeMethod(mGuiWorker, "setPainterWidth", Q_ARG(int, penWidth));
}
<|endoftext|>


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

#include <string> // HACK: prevent conflict between STLPORT and Workshop headern

#ifndef _STDMENU_HXX //autogen
#include <svtools/stdmenu.hxx>
#endif
#ifndef _SFXAPP_HXX //autogen
#include <sfx2/app.hxx>
#endif
#ifndef _SFX_OBJSH_HXX //autogen
#include <sfx2/objsh.hxx>
#endif
#ifndef _SFXDISPATCH_HXX //autogen
#include <sfx2/dispatch.hxx>
#endif

#define ITEMID_FONT     1
#define ITEMID_FONTLIST 2

#include "fntctl.hxx"       // ITEMID_FONT muss vorher definiert sein!
#include "svxids.hrc"

#ifndef _SVX_FLSTITEM_HXX //autogen
#include "flstitem.hxx"
#endif
#ifndef _SVX_FONTITEM_HXX //autogen
#include "fontitem.hxx"
#endif

// STATIC DATA -----------------------------------------------------------

SFX_IMPL_MENU_CONTROL(SvxFontMenuControl, SvxFontItem);

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

/*  [Beschreibung]

    Ctor; setzt den Select-Handler am Men"u und tr"agt das Men"u
    in seinen Parent ein.
*/

SvxFontMenuControl::SvxFontMenuControl
(
    USHORT          nId,
    Menu&           rMenu,
    SfxBindings&    rBindings
) :
    pMenu   ( new FontNameMenu ),
    rParent ( rMenu )
{
    rMenu.SetPopupMenu( nId, pMenu );
    pMenu->SetSelectHdl( LINK( this, SvxFontMenuControl, MenuSelect ) );
    StartListening( rBindings );
    FillMenu();
}

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

/*  [Beschreibung]

    F"ullt das Men"u mit den aktuellen Fonts aus der Fontlist
    der DocumentShell.
*/

void SvxFontMenuControl::FillMenu()
{
    SfxObjectShell *pDoc = SfxObjectShell::Current();

    if ( pDoc )
    {
        const SvxFontListItem* pFonts =
            (const SvxFontListItem*)pDoc->GetItem( SID_ATTR_CHAR_FONTLIST );
        const FontList* pList = pFonts ? pFonts->GetFontList(): 0;
        DBG_ASSERT( pList, "Kein Fonts gefunden" );
        pMenu->Fill( pList );
    }
}

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

/*  [Beschreibung]

    Statusbenachrichtigung;
    f"ullt ggf. das Men"u mit den aktuellen Fonts aus der Fontlist
    der DocumentShell.
    Ist die Funktionalit"at disabled, wird der entsprechende
    Men"ueintrag im Parentmen"u disabled, andernfalls wird er enabled.
    Der aktuelle Font wird mit einer Checkmark versehen.
*/

void SvxFontMenuControl::StateChanged(

    USHORT nSID, SfxItemState eState, const SfxPoolItem* pState )

{
    rParent.EnableItem( GetId(), SFX_ITEM_DISABLED != eState );

    if ( SFX_ITEM_AVAILABLE == eState )
    {
        if ( !pMenu->GetItemCount() )
            FillMenu();
        const SvxFontItem* pFontItem = PTR_CAST( SvxFontItem, pState );
        String aFont;

        if ( pFontItem )
            aFont = pFontItem->GetFamilyName();
        pMenu->SetCurName( aFont );
    }
}

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

/*  [Beschreibung]

    Statusbenachrichtigung "uber Bindings;  bei DOCCHANGED
    wird das Men"u mit den aktuellen Fonts aus der Fontlist
    der DocumentShell gef"ullt.
*/

void SvxFontMenuControl::SFX_NOTIFY( SfxBroadcaster& rBC, const TypeId& rBCType,
                                 const SfxHint& rHint, const TypeId& rHintType )
{
    if ( rHint.Type() != TYPE(SfxSimpleHint) &&
         ( (SfxSimpleHint&)rHint ).GetId() == SFX_HINT_DOCCHANGED )
        FillMenu();
}

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

/*  [Beschreibung]

    Select-Handler des Men"us; der Name des selektierten Fonts
    wird in einem SvxFontItem verschickt. Das F"ullen mit den
    weiteren Fontinformationen mu\s durch die Applikation geschehen.
*/

IMPL_LINK_INLINE_START( SvxFontMenuControl, MenuSelect, FontNameMenu *, pMen )
{
    SvxFontItem aItem( GetId() );
    aItem.GetFamilyName() = pMen->GetCurName();
    GetBindings().GetDispatcher()->Execute( GetId(), SFX_CALLMODE_RECORD, &aItem, 0L );
    return 0;
}
IMPL_LINK_INLINE_END( SvxFontMenuControl, MenuSelect, FontNameMenu *, pMen )

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

/*  [Beschreibung]

    Dtor; gibt das Men"u frei.
*/

SvxFontMenuControl::~SvxFontMenuControl()
{
    delete pMenu;
}

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

/*  [Beschreibung]

    Gibt das Men"u zur"uck
*/

PopupMenu* SvxFontMenuControl::GetPopup() const
{
    return pMenu;
}

<commit_msg>INTEGRATION: CWS pchfix02 (1.3.116); FILE MERGED 2006/09/01 17:47:03 kaib 1.3.116.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: fntctl.cxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-17 05:25:14 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_svx.hxx"

#include <string> // HACK: prevent conflict between STLPORT and Workshop headern

#ifndef _STDMENU_HXX //autogen
#include <svtools/stdmenu.hxx>
#endif
#ifndef _SFXAPP_HXX //autogen
#include <sfx2/app.hxx>
#endif
#ifndef _SFX_OBJSH_HXX //autogen
#include <sfx2/objsh.hxx>
#endif
#ifndef _SFXDISPATCH_HXX //autogen
#include <sfx2/dispatch.hxx>
#endif

#define ITEMID_FONT     1
#define ITEMID_FONTLIST 2

#include "fntctl.hxx"       // ITEMID_FONT muss vorher definiert sein!
#include "svxids.hrc"

#ifndef _SVX_FLSTITEM_HXX //autogen
#include "flstitem.hxx"
#endif
#ifndef _SVX_FONTITEM_HXX //autogen
#include "fontitem.hxx"
#endif

// STATIC DATA -----------------------------------------------------------

SFX_IMPL_MENU_CONTROL(SvxFontMenuControl, SvxFontItem);

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

/*  [Beschreibung]

    Ctor; setzt den Select-Handler am Men"u und tr"agt das Men"u
    in seinen Parent ein.
*/

SvxFontMenuControl::SvxFontMenuControl
(
    USHORT          nId,
    Menu&           rMenu,
    SfxBindings&    rBindings
) :
    pMenu   ( new FontNameMenu ),
    rParent ( rMenu )
{
    rMenu.SetPopupMenu( nId, pMenu );
    pMenu->SetSelectHdl( LINK( this, SvxFontMenuControl, MenuSelect ) );
    StartListening( rBindings );
    FillMenu();
}

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

/*  [Beschreibung]

    F"ullt das Men"u mit den aktuellen Fonts aus der Fontlist
    der DocumentShell.
*/

void SvxFontMenuControl::FillMenu()
{
    SfxObjectShell *pDoc = SfxObjectShell::Current();

    if ( pDoc )
    {
        const SvxFontListItem* pFonts =
            (const SvxFontListItem*)pDoc->GetItem( SID_ATTR_CHAR_FONTLIST );
        const FontList* pList = pFonts ? pFonts->GetFontList(): 0;
        DBG_ASSERT( pList, "Kein Fonts gefunden" );
        pMenu->Fill( pList );
    }
}

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

/*  [Beschreibung]

    Statusbenachrichtigung;
    f"ullt ggf. das Men"u mit den aktuellen Fonts aus der Fontlist
    der DocumentShell.
    Ist die Funktionalit"at disabled, wird der entsprechende
    Men"ueintrag im Parentmen"u disabled, andernfalls wird er enabled.
    Der aktuelle Font wird mit einer Checkmark versehen.
*/

void SvxFontMenuControl::StateChanged(

    USHORT nSID, SfxItemState eState, const SfxPoolItem* pState )

{
    rParent.EnableItem( GetId(), SFX_ITEM_DISABLED != eState );

    if ( SFX_ITEM_AVAILABLE == eState )
    {
        if ( !pMenu->GetItemCount() )
            FillMenu();
        const SvxFontItem* pFontItem = PTR_CAST( SvxFontItem, pState );
        String aFont;

        if ( pFontItem )
            aFont = pFontItem->GetFamilyName();
        pMenu->SetCurName( aFont );
    }
}

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

/*  [Beschreibung]

    Statusbenachrichtigung "uber Bindings;  bei DOCCHANGED
    wird das Men"u mit den aktuellen Fonts aus der Fontlist
    der DocumentShell gef"ullt.
*/

void SvxFontMenuControl::SFX_NOTIFY( SfxBroadcaster& rBC, const TypeId& rBCType,
                                 const SfxHint& rHint, const TypeId& rHintType )
{
    if ( rHint.Type() != TYPE(SfxSimpleHint) &&
         ( (SfxSimpleHint&)rHint ).GetId() == SFX_HINT_DOCCHANGED )
        FillMenu();
}

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

/*  [Beschreibung]

    Select-Handler des Men"us; der Name des selektierten Fonts
    wird in einem SvxFontItem verschickt. Das F"ullen mit den
    weiteren Fontinformationen mu\s durch die Applikation geschehen.
*/

IMPL_LINK_INLINE_START( SvxFontMenuControl, MenuSelect, FontNameMenu *, pMen )
{
    SvxFontItem aItem( GetId() );
    aItem.GetFamilyName() = pMen->GetCurName();
    GetBindings().GetDispatcher()->Execute( GetId(), SFX_CALLMODE_RECORD, &aItem, 0L );
    return 0;
}
IMPL_LINK_INLINE_END( SvxFontMenuControl, MenuSelect, FontNameMenu *, pMen )

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

/*  [Beschreibung]

    Dtor; gibt das Men"u frei.
*/

SvxFontMenuControl::~SvxFontMenuControl()
{
    delete pMenu;
}

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

/*  [Beschreibung]

    Gibt das Men"u zur"uck
*/

PopupMenu* SvxFontMenuControl::GetPopup() const
{
    return pMenu;
}

<|endoftext|>