<commit_before>/* Copyright 2017 The Apollo Authors. All Rights Reserved.

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 "modules/dreamview/backend/handlers/image_handler.h"

#include "cyber/common/log.h"
#include "modules/common/adapters/adapter_gflags.h"
#include "modules/common/configs/config_gflags.h"

#include "opencv2/opencv.hpp"

namespace apollo {
namespace dreamview {

using apollo::drivers::CompressedImage;
using apollo::drivers::Image;

constexpr double ImageHandler::kImageScale;

template <>
void ImageHandler::OnImage(const std::shared_ptr<Image> &image) {
  if (requests_ == 0) {
    return;
  }

  cv::Mat mat(image->height(), image->width(), CV_8UC3,
              const_cast<char *>(image->data().data()), image->step());
  cv::cvtColor(mat, mat, cv::COLOR_RGB2BGR);
  cv::resize(
      mat, mat,
      cv::Size(static_cast<int>(image->width() * ImageHandler::kImageScale),
               static_cast<int>(image->height() * ImageHandler::kImageScale)),
      0, 0, CV_INTER_LINEAR);

  std::unique_lock<std::mutex> lock(mutex_);
  cv::imencode(".jpg", mat, send_buffer_, std::vector<int>() /* params */);
  cvar_.notify_all();
}

template <>
void ImageHandler::OnImage(
    const std::shared_ptr<CompressedImage> &compressed_image) {
  std::vector<uint8_t> compressed_raw_data(compressed_image->data().begin(),
                                           compressed_image->data().end());
  cv::Mat mat_image = cv::imdecode(compressed_raw_data, CV_LOAD_IMAGE_COLOR);
  cv::cvtColor(mat_image, mat_image, cv::COLOR_RGB2BGR);

  std::unique_lock<std::mutex> lock(mutex_);
  cv::imencode(".jpg", mat_image, send_buffer_,
               std::vector<int>() /* params */);
  cvar_.notify_all();
}

void ImageHandler::OnImageFront(const std::shared_ptr<Image> &image) {
  if (FLAGS_use_navigation_mode) {
    OnImage(image);
  }
}

void ImageHandler::OnImageShort(const std::shared_ptr<CompressedImage> &image) {
  if (!FLAGS_use_navigation_mode) {
    OnImage(image);
  }
}

ImageHandler::ImageHandler()
    : requests_(0), node_(cyber::CreateNode("image_handler")) {
  node_->CreateReader<Image>(
      FLAGS_image_front_topic,
      [this](const std::shared_ptr<Image> &image) {
        OnImageFront(image);
      });

  node_->CreateReader<CompressedImage>(
      FLAGS_image_short_topic,
      [this](const std::shared_ptr<CompressedImage> &image) {
        OnImageShort(image);
      });
}

bool ImageHandler::handleGet(CivetServer *server, struct mg_connection *conn) {
  requests_++;

  mg_printf(conn,
            "HTTP/1.1 200 OK\r\n"
            "Connection: close\r\n"
            "Max-Age: 0\r\n"
            "Expires: 0\r\n"
            "Cache-Control: no-cache, no-store, must-revalidate, private\r\n"
            "Pragma: no-cache\r\n"
            "Content-Type: multipart/x-mixed-replace; "
            "boundary=--BoundaryString\r\n"
            "\r\n");

  std::vector<uchar> to_send;
  while (true) {
    {
      std::unique_lock<std::mutex> lock(mutex_);
      to_send = send_buffer_;
    }

    if (!to_send.empty()) {
      // Sends the image data
      mg_printf(conn,
                "--BoundaryString\r\n"
                "Content-type: image/jpeg\r\n"
                "Content-Length: %zu\r\n"
                "\r\n",
                to_send.size());

      if (mg_write(conn, &to_send[0], to_send.size()) <= 0) {
        requests_--;
        return false;
      }
      mg_printf(conn, "\r\n\r\n");
    }

    std::unique_lock<std::mutex> lock(mutex_);
    cvar_.wait(lock);
  }

  requests_--;
  return true;
}

}  // namespace dreamview
}  // namespace apollo
<commit_msg>Dreamview: remove redundant cvtColor<commit_after>/* Copyright 2017 The Apollo Authors. All Rights Reserved.

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 "modules/dreamview/backend/handlers/image_handler.h"

#include "cyber/common/log.h"
#include "modules/common/adapters/adapter_gflags.h"
#include "modules/common/configs/config_gflags.h"

#include "opencv2/opencv.hpp"

namespace apollo {
namespace dreamview {

using apollo::drivers::CompressedImage;
using apollo::drivers::Image;

constexpr double ImageHandler::kImageScale;

template <>
void ImageHandler::OnImage(const std::shared_ptr<Image> &image) {
  if (requests_ == 0) {
    return;
  }

  cv::Mat mat(image->height(), image->width(), CV_8UC3,
              const_cast<char *>(image->data().data()), image->step());
  cv::cvtColor(mat, mat, cv::COLOR_RGB2BGR);
  cv::resize(
      mat, mat,
      cv::Size(static_cast<int>(image->width() * ImageHandler::kImageScale),
               static_cast<int>(image->height() * ImageHandler::kImageScale)),
      0, 0, CV_INTER_LINEAR);

  std::unique_lock<std::mutex> lock(mutex_);
  cv::imencode(".jpg", mat, send_buffer_, std::vector<int>() /* params */);
  cvar_.notify_all();
}

template <>
void ImageHandler::OnImage(
    const std::shared_ptr<CompressedImage> &compressed_image) {
  std::vector<uint8_t> compressed_raw_data(compressed_image->data().begin(),
                                           compressed_image->data().end());
  cv::Mat mat_image = cv::imdecode(compressed_raw_data, CV_LOAD_IMAGE_COLOR);

  std::unique_lock<std::mutex> lock(mutex_);
  cv::imencode(".jpg", mat_image, send_buffer_,
               std::vector<int>() /* params */);
  cvar_.notify_all();
}

void ImageHandler::OnImageFront(const std::shared_ptr<Image> &image) {
  if (FLAGS_use_navigation_mode) {
    // Navigation mode
    OnImage(image);
  }
}

void ImageHandler::OnImageShort(const std::shared_ptr<CompressedImage> &image) {
  if (!FLAGS_use_navigation_mode) {
    // Regular mode
    OnImage(image);
  }
}

ImageHandler::ImageHandler()
    : requests_(0), node_(cyber::CreateNode("image_handler")) {
  node_->CreateReader<Image>(
      FLAGS_image_front_topic,
      [this](const std::shared_ptr<Image> &image) { OnImageFront(image); });

  node_->CreateReader<CompressedImage>(
      FLAGS_image_short_topic,
      [this](const std::shared_ptr<CompressedImage> &image) {
        OnImageShort(image);
      });
}

bool ImageHandler::handleGet(CivetServer *server, struct mg_connection *conn) {
  requests_++;

  mg_printf(conn,
            "HTTP/1.1 200 OK\r\n"
            "Connection: close\r\n"
            "Max-Age: 0\r\n"
            "Expires: 0\r\n"
            "Cache-Control: no-cache, no-store, must-revalidate, private\r\n"
            "Pragma: no-cache\r\n"
            "Content-Type: multipart/x-mixed-replace; "
            "boundary=--BoundaryString\r\n"
            "\r\n");

  std::vector<uchar> to_send;
  while (true) {
    {
      std::unique_lock<std::mutex> lock(mutex_);
      to_send = send_buffer_;
    }

    if (!to_send.empty()) {
      // Sends the image data
      mg_printf(conn,
                "--BoundaryString\r\n"
                "Content-type: image/jpeg\r\n"
                "Content-Length: %zu\r\n"
                "\r\n",
                to_send.size());

      if (mg_write(conn, &to_send[0], to_send.size()) <= 0) {
        requests_--;
        return false;
      }
      mg_printf(conn, "\r\n\r\n");
    }

    std::unique_lock<std::mutex> lock(mutex_);
    cvar_.wait(lock);
  }

  requests_--;
  return true;
}

}  // namespace dreamview
}  // namespace apollo
<|endoftext|>


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

#pragma hdrstop

#ifndef _SHL_HXX //autogen
#include <tools/shl.hxx>
#endif
#ifndef _STRING_HXX //autogen
#include <tools/string.hxx>
#endif
#ifndef _SVARRAY_HXX
#include <svtools/svstdarr.hxx>
#endif
#ifndef _SFX_PROGRESS_HXX //autogen
#include <sfx2/progress.hxx>
#endif
#ifndef _RESID_HXX //autogen
#include <vcl/resid.hxx>
#endif

#ifndef _SWDOCSH_HXX //autogen
#include <docsh.hxx>
#endif
#ifndef _SWMODULE_HXX //autogen
#include <swmodule.hxx>
#endif
#include "swtypes.hxx"

class SwDocShell;

struct SwProgress
{
    long nStartValue,
         nStartCount;
    SwDocShell  *pDocShell;
    SfxProgress *pProgress;
};

static SvPtrarr *pProgressContainer = 0;

SwProgress *lcl_SwFindProgress( SwDocShell *pDocShell )
{
    for ( USHORT i = 0; i < pProgressContainer->Count(); ++i )
    {
        SwProgress *pTmp = (SwProgress*)(*pProgressContainer)[i];
        if ( pTmp->pDocShell == pDocShell )
            return pTmp;
    }
    return 0;
}

void StartProgress( USHORT nMessResId, long nStartValue, long nEndValue,
                    SwDocShell *pDocShell )
{
    if( !SW_MOD()->IsEmbeddedLoadSave() )
    {
        SwProgress *pProgress = 0;

        if ( !pProgressContainer )
            pProgressContainer = new SvPtrarr( 2, 2 );
        else
        {
            if ( 0 != (pProgress = lcl_SwFindProgress( pDocShell )) )
                ++pProgress->nStartCount;
        }
        if ( !pProgress )
        {
            pProgress = new SwProgress;
            pProgress->pProgress = new SfxProgress( pDocShell,
                                                    SW_RESSTR(nMessResId),
                                                    nEndValue - nStartValue,
                                                    FALSE,
                                                    TRUE );
            pProgress->nStartCount = 1;
            pProgress->pDocShell = pDocShell;
            pProgressContainer->Insert( (void*)pProgress, 0 );
        }
        pProgress->nStartValue = nStartValue;
    }
}

void SetProgressState( long nPosition, SwDocShell *pDocShell )
{
    if( pProgressContainer && !SW_MOD()->IsEmbeddedLoadSave() )
    {
        SwProgress *pProgress = lcl_SwFindProgress( pDocShell );
        if ( pProgress )
            pProgress->pProgress->SetState(nPosition - pProgress->nStartValue);
    }
}

void EndProgress( SwDocShell *pDocShell )
{
    if( pProgressContainer && !SW_MOD()->IsEmbeddedLoadSave() )
    {
        SwProgress *pProgress = 0;
        USHORT i;
        for ( i = 0; i < pProgressContainer->Count(); ++i )
        {
            SwProgress *pTmp = (SwProgress*)(*pProgressContainer)[i];
            if ( pTmp->pDocShell == pDocShell )
            {
                pProgress = pTmp;
                break;
            }
        }

        if ( pProgress && 0 == --pProgress->nStartCount )
        {
            pProgress->pProgress->Stop();
            pProgressContainer->Remove( i );
            delete pProgress->pProgress;
            delete pProgress;
            if ( !pProgressContainer->Count() )
                delete pProgressContainer, pProgressContainer = 0;
        }
    }
}

void SetProgressText( USHORT nId, SwDocShell *pDocShell )
{
    if( pProgressContainer && !SW_MOD()->IsEmbeddedLoadSave() )
    {
        SwProgress *pProgress = lcl_SwFindProgress( pDocShell );
        if ( pProgress )
            pProgress->pProgress->SetStateText( 0, SW_RESSTR(nId) );
    }
}

void RescheduleProgress( SwDocShell *pDocShell )
{
    if( pProgressContainer && !SW_MOD()->IsEmbeddedLoadSave() )
    {
        SwProgress *pProgress = lcl_SwFindProgress( pDocShell );
        if ( pProgress )
            pProgress->pProgress->Reschedule();
    }
}

<commit_msg>INTEGRATION: CWS geordi2q10 (1.3.298); FILE MERGED 2003/11/27 12:40:15 rt 1.3.298.1: #111934#: join CWS os21<commit_after>/*************************************************************************
 *
 *  $RCSfile: mainwn.cxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: rt $ $Date: 2003-12-01 09:43:30 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#pragma hdrstop

#ifndef _SHL_HXX //autogen
#include <tools/shl.hxx>
#endif
#ifndef _STRING_HXX //autogen
#include <tools/string.hxx>
#endif
#ifndef _SVARRAY_HXX
#include <svtools/svstdarr.hxx>
#endif
#ifndef _SFX_PROGRESS_HXX //autogen
#include <sfx2/progress.hxx>
#endif
#ifndef _RESID_HXX //autogen
#include <vcl/resid.hxx>
#endif

#ifndef _SWDOCSH_HXX //autogen
#include <docsh.hxx>
#endif
#ifndef _SWMODULE_HXX //autogen
#include <swmodule.hxx>
#endif
#include "swtypes.hxx"

class SwDocShell;

struct SwProgress
{
    long nStartValue,
         nStartCount;
    SwDocShell  *pDocShell;
    SfxProgress *pProgress;
};

static SvPtrarr *pProgressContainer = 0;

SwProgress *lcl_SwFindProgress( SwDocShell *pDocShell )
{
    for ( USHORT i = 0; i < pProgressContainer->Count(); ++i )
    {
        SwProgress *pTmp = (SwProgress*)(*pProgressContainer)[i];
        if ( pTmp->pDocShell == pDocShell )
            return pTmp;
    }
    return 0;
}

void StartProgress( USHORT nMessResId, long nStartValue, long nEndValue,
                    SwDocShell *pDocShell )
{
    if( !SW_MOD()->IsEmbeddedLoadSave() )
    {
        SwProgress *pProgress = 0;

        if ( !pProgressContainer )
            pProgressContainer = new SvPtrarr( 2, 2 );
        else
        {
            if ( 0 != (pProgress = lcl_SwFindProgress( pDocShell )) )
                ++pProgress->nStartCount;
        }
        if ( !pProgress )
        {
            pProgress = new SwProgress;
            pProgress->pProgress = new SfxProgress( pDocShell,
                                                    SW_RESSTR(nMessResId),
                                                    nEndValue - nStartValue,
                                                    FALSE,
                                                    TRUE );
            pProgress->nStartCount = 1;
            pProgress->pDocShell = pDocShell;
            pProgressContainer->Insert( (void*)pProgress, 0 );
        }
        pProgress->nStartValue = nStartValue;
    }
}

void SetProgressState( long nPosition, SwDocShell *pDocShell )
{
    if( pProgressContainer && !SW_MOD()->IsEmbeddedLoadSave() )
    {
        SwProgress *pProgress = lcl_SwFindProgress( pDocShell );
        if ( pProgress )
            pProgress->pProgress->SetState(nPosition - pProgress->nStartValue);
    }
}

void EndProgress( SwDocShell *pDocShell )
{
    if( pProgressContainer && !SW_MOD()->IsEmbeddedLoadSave() )
    {
        SwProgress *pProgress = 0;
        USHORT i;
        for ( i = 0; i < pProgressContainer->Count(); ++i )
        {
            SwProgress *pTmp = (SwProgress*)(*pProgressContainer)[i];
            if ( pTmp->pDocShell == pDocShell )
            {
                pProgress = pTmp;
                break;
            }
        }

        if ( pProgress && 0 == --pProgress->nStartCount )
        {
            pProgress->pProgress->Stop();
            pProgressContainer->Remove( i );
            delete pProgress->pProgress;
            delete pProgress;
            //#112337# it may happen that the container has been removed
            //while rescheduling
            if ( pProgressContainer && !pProgressContainer->Count() )
                delete pProgressContainer, pProgressContainer = 0;
        }
    }
}

void SetProgressText( USHORT nId, SwDocShell *pDocShell )
{
    if( pProgressContainer && !SW_MOD()->IsEmbeddedLoadSave() )
    {
        SwProgress *pProgress = lcl_SwFindProgress( pDocShell );
        if ( pProgress )
            pProgress->pProgress->SetStateText( 0, SW_RESSTR(nId) );
    }
}

void RescheduleProgress( SwDocShell *pDocShell )
{
    if( pProgressContainer && !SW_MOD()->IsEmbeddedLoadSave() )
    {
        SwProgress *pProgress = lcl_SwFindProgress( pDocShell );
        if ( pProgress )
            pProgress->pProgress->Reschedule();
    }
}

<|endoftext|>


<commit_before>// ***************************************************************************
// FastaIndex.cpp (c) 2010 Erik Garrison <erik.garrison@bc.edu>
// Marth Lab, Department of Biology, Boston College
// All rights reserved.
// ---------------------------------------------------------------------------
// Last modified: 9 February 2010 (EG)
// ---------------------------------------------------------------------------

#include "Fasta.h"

FastaIndexEntry::FastaIndexEntry(string name, int length, long long offset, int line_blen, int line_len)
    : name(name)
    , length(length)
    , offset(offset)
    , line_blen(line_blen)
    , line_len(line_len)
{}

FastaIndexEntry::FastaIndexEntry(void) // empty constructor
{ clear(); }

FastaIndexEntry::~FastaIndexEntry(void)
{}

void FastaIndexEntry::clear(void)
{
    name = "";
    length = NULL;
    offset = -1;  // no real offset will ever be below 0, so this allows us to
                  // check if we have already recorded a real offset
    line_blen = NULL;
    line_len = NULL;
}

ostream& operator<<(ostream& output, const FastaIndexEntry& e) {
    output << e.name << "\t" << e.length << "\t" << e.offset << "\t" <<
        e.line_blen << "\t" << e.line_len;
    return output;  // for multiple << operators.
}

FastaIndex::FastaIndex(void)
{}

void FastaIndex::readIndexFile(string fname) {
    string line;
    long long linenum = 0;
    vector<string> fields;
    indexFile.open(fname.c_str(), ifstream::in);
    if (indexFile.is_open()) {
        while (getline (indexFile, line)) {
            ++linenum;
            fields.clear();
            // the fai format defined in samtools is tab-delimited, every line being:
            // fai->name[i], (int)x.len, (long long)x.offset, (int)x.line_blen, (int)x.line_len
            boost::split(fields, line, boost::is_any_of("\t")); // split on tab
            if (fields.size() == 5) {  // if we don't get enough fields then there is a problem with the file
                // note that fields[0] is the sequence name
                this->insert(pair<string, FastaIndexEntry>(fields[0],
                            FastaIndexEntry(fields[0], lexical_cast<int>(fields[1]),
                                                    lexical_cast<long long>(fields[2]),
                                                    lexical_cast<int>(fields[3]),
                                                    lexical_cast<int>(fields[4]))));
            } else {
                cerr << "Warning: malformed fasta index file " << fname <<
                    "does not have enough fields @ line " << linenum << endl;
                cerr << line << endl;
                exit(1);
            }
        }
    }
}

// for consistency this should be a class method
bool fastaIndexEntryCompare ( FastaIndexEntry a, FastaIndexEntry b) { return (a.offset<b.offset); }

ostream& operator<<(ostream& output, const FastaIndex& fastaIndex) {
    vector<FastaIndexEntry> sortedIndex;
    for(map<string, FastaIndexEntry>::const_iterator it = fastaIndex.begin(); it != fastaIndex.end(); ++it)
    {
        sortedIndex.push_back(it->second);
    }
    sort(sortedIndex.begin(), sortedIndex.end(), fastaIndexEntryCompare);
    for( vector<FastaIndexEntry>::iterator fit = sortedIndex.begin(); fit != sortedIndex.end(); ++fit) {
        output << *fit << endl;
    }
}

void FastaIndex::indexReference(string refname) {
    // overview:
    //  for line in the reference fasta file
    //  track byte offset from the start of the file
    //  if line is a fasta header, take the name and dump the last sequnece to the index
    //  if line is a sequence, add it to the current sequence
    cerr << "indexing fasta reference " << refname << endl;
    string line;
    FastaIndexEntry entry;  // an entry buffer used in processing
    entry.clear();
    int line_length = 0;
    long long offset = 0;  // byte offset from start of file
    ifstream refFile;
    refFile.open(refname.c_str());
    if (refFile.is_open()) {
        while (getline(refFile, line)) {
            line_length = line.length();
            if (line[0] == ';') {
                // fasta comment, skip
            } else if (line[0] == '+') {
                // fastq quality header
                getline(refFile, line);
                line_length = line.length();
                offset += line_length + 1;
                // get and don't handle the quality line
                getline(refFile, line);
                line_length = line.length();
            } else if (line[0] == '>' || line[0] == '@') { // fasta /fastq header
                // if we aren't on the first entry, push the last sequence into the index
                if (entry.name != "") {
                    flushEntryToIndex(entry);
                    entry.clear();
                }
                entry.name = line.substr(1, line_length - 1);
            } else { // we assume we have found a sequence line
                if (entry.offset == -1) // NB initially the offset is -1
                    entry.offset = offset;
                entry.length += line_length;
                // NOTE: samtools calls errors if the lines are different lengths; should we?
                // Is this a violation of the FASTA format spec?  Or is it just heavy-handed validation?
                //
                // Instead of calling foul if our lines have mismatched
                // lengths, here we report the *longest* line in the sequence.
                // For well-formatted fasta files, this should be the 'normal'
                // line length.
                entry.line_len = entry.line_len ? entry.line_len : line_length + 1;
                entry.line_blen = entry.line_len - 1;
            }
            offset += line_length + 1;
        }
        // we've hit the end of the fasta file!
        // flush the last entry
        flushEntryToIndex(entry);
    } else {
        cerr << "could not open reference file " << refname << " for indexing!" << endl;
        exit(1);
    }
}

void FastaIndex::flushEntryToIndex(FastaIndexEntry& entry) {
    this->insert(pair<string, FastaIndexEntry>(entry.name,
                FastaIndexEntry(entry.name, entry.length,
                                entry.offset, entry.line_blen,
                                entry.line_len)));

}

void FastaIndex::writeIndexFile(string fname) {
    cerr << "writing fasta index file " << fname << endl;
    ofstream file;
    file.open(fname.c_str());
    if (file.is_open()) {
        file << *this;
    } else {
        cerr << "could not open index file " << fname << " for writing!" << endl;
        exit(1);
    }
}

FastaIndex::~FastaIndex(void) {
    indexFile.close();
}

FastaIndexEntry FastaIndex::entry(string name) {
    return this->find(name)->second;
}

string FastaIndex::indexFileExtension() { return ".fai"; }

FastaReference::FastaReference(string reffilename) {
    filename = reffilename;
    file = fopen(filename.c_str(), "r");
    index = new FastaIndex();
    struct stat stFileInfo;
    string indexFileName = filename + index->indexFileExtension();
    // if we can find an index file, use it
    if(stat(indexFileName.c_str(), &stFileInfo) == 0) {
        index->readIndexFile(indexFileName);
    } else { // otherwise, read the reference and generate the index file in the cwd
        cerr << "index file " << indexFileName << " not found, generating..." << endl;
        index->indexReference(filename);
        index->writeIndexFile(indexFileName);
    }
}

FastaReference::~FastaReference(void) {
    fclose(file);
    delete index;
}

string FastaReference::getSequence(string seqname) {
    FastaIndexEntry entry = index->entry(seqname);
    char* seq = (char*) malloc (sizeof(char)*entry.length);
    fseek64(file, entry.offset, SEEK_SET);
    fread(seq, sizeof(char), entry.length, file);
    char* pbegin = seq;
    char* pend = seq + ((string)seq).size()/sizeof(char);
    pend = remove (pbegin, pend, '\n');
    string s = seq;
    s.resize((pend - pbegin)/sizeof(char));
    return s;
}

string FastaReference::sequenceNameStartingWith(string seqnameStart) {
    string teststr;
    string result = "";
    vector<string> fields;
    for(map<string, FastaIndexEntry>::const_iterator it = index->begin(); it != index->end(); ++it)
    {
        boost::split(fields, it->second.name, boost::is_any_of("\t ")); // split on ws
        // check if the first field is the same as our startseq
        teststr = fields.at(0);
        if (teststr == seqnameStart) {
            if (result == "") {
                result = it->second.name;
            } else {
                cerr << " is not unique in fasta index" << endl;
                return "";
            }
        }
    }
    if (result != "")
        return result;
    else
        return "";
}

string FastaReference::getSubSequence(string seqname, int start, int length) {
    FastaIndexEntry entry = index->entry(seqname);
    if (start < 0 || length < 1) {
        cerr << "Error: cannot construct subsequence with negative offset or length < 1" << endl;
        exit(1);
    }
    // we have to handle newlines
    // approach: count newlines before start
    //           count newlines by end of read
    //             subtracting newlines before start find count of embedded newlines
    int newlines_before = start > 0 ? (start - 1) / entry.line_blen : 0;
    int newlines_by_end = (start + length - 1) / entry.line_blen;
    int newlines_inside = newlines_by_end - newlines_before;
    /*
    cout << "start: " << start << " length: " << length << endl;
    cout << "newlines before: " << newlines_before << endl;
    cout << "newlines inside: " << newlines_inside << endl;
    */
    int seqlen = length + newlines_inside;
    char* seq = (char*) malloc (sizeof(char)*seqlen + 1);
    fseek64(file, (off_t) (entry.offset + newlines_before + start), SEEK_SET);
    fread(seq, sizeof(char), (off_t) seqlen, file);
    seq[seqlen] = '\0';
    string s = seq;
    boost::erase_all(s, "\n");
    return s;
}

long unsigned int FastaReference::sequenceLength(string seqname) {
    FastaIndexEntry entry = index->entry(seqname);
    int newlines_in_sequence = entry.length / entry.line_len;
    return entry.length - newlines_in_sequence;
}

<commit_msg>Fasta reader fix<commit_after>// ***************************************************************************
// FastaIndex.cpp (c) 2010 Erik Garrison <erik.garrison@bc.edu>
// Marth Lab, Department of Biology, Boston College
// All rights reserved.
// ---------------------------------------------------------------------------
// Last modified: 9 February 2010 (EG)
// ---------------------------------------------------------------------------

#include "Fasta.h"

FastaIndexEntry::FastaIndexEntry(string name, int length, long long offset, int line_blen, int line_len)
    : name(name)
    , length(length)
    , offset(offset)
    , line_blen(line_blen)
    , line_len(line_len)
{}

FastaIndexEntry::FastaIndexEntry(void) // empty constructor
{ clear(); }

FastaIndexEntry::~FastaIndexEntry(void)
{}

void FastaIndexEntry::clear(void)
{
    name = "";
    length = NULL;
    offset = -1;  // no real offset will ever be below 0, so this allows us to
                  // check if we have already recorded a real offset
    line_blen = NULL;
    line_len = NULL;
}

ostream& operator<<(ostream& output, const FastaIndexEntry& e) {
    output << e.name << "\t" << e.length << "\t" << e.offset << "\t" <<
        e.line_blen << "\t" << e.line_len;
    return output;  // for multiple << operators.
}

FastaIndex::FastaIndex(void)
{}

void FastaIndex::readIndexFile(string fname) {
    string line;
    long long linenum = 0;
    vector<string> fields;
    indexFile.open(fname.c_str(), ifstream::in);
    if (indexFile.is_open()) {
        while (getline (indexFile, line)) {
            ++linenum;
            fields.clear();
            // the fai format defined in samtools is tab-delimited, every line being:
            // fai->name[i], (int)x.len, (long long)x.offset, (int)x.line_blen, (int)x.line_len
            boost::split(fields, line, boost::is_any_of("\t")); // split on tab
            if (fields.size() == 5) {  // if we don't get enough fields then there is a problem with the file
                // note that fields[0] is the sequence name
                this->insert(pair<string, FastaIndexEntry>(fields[0],
                            FastaIndexEntry(fields[0], lexical_cast<int>(fields[1]),
                                                    lexical_cast<long long>(fields[2]),
                                                    lexical_cast<int>(fields[3]),
                                                    lexical_cast<int>(fields[4]))));
            } else {
                cerr << "Warning: malformed fasta index file " << fname <<
                    "does not have enough fields @ line " << linenum << endl;
                cerr << line << endl;
                exit(1);
            }
        }
    }
}

// for consistency this should be a class method
bool fastaIndexEntryCompare ( FastaIndexEntry a, FastaIndexEntry b) { return (a.offset<b.offset); }

ostream& operator<<(ostream& output, const FastaIndex& fastaIndex) {
    vector<FastaIndexEntry> sortedIndex;
    for(map<string, FastaIndexEntry>::const_iterator it = fastaIndex.begin(); it != fastaIndex.end(); ++it)
    {
        sortedIndex.push_back(it->second);
    }
    sort(sortedIndex.begin(), sortedIndex.end(), fastaIndexEntryCompare);
    for( vector<FastaIndexEntry>::iterator fit = sortedIndex.begin(); fit != sortedIndex.end(); ++fit) {
        output << *fit << endl;
    }
}

void FastaIndex::indexReference(string refname) {
    // overview:
    //  for line in the reference fasta file
    //  track byte offset from the start of the file
    //  if line is a fasta header, take the name and dump the last sequnece to the index
    //  if line is a sequence, add it to the current sequence
    cerr << "indexing fasta reference " << refname << endl;
    string line;
    FastaIndexEntry entry;  // an entry buffer used in processing
    entry.clear();
    int line_length = 0;
    long long offset = 0;  // byte offset from start of file
    long long line_number = 0; // current line number
    bool mismatchedLineLengths = false; // flag to indicate if our line length changes mid-file
                                        // this will be used to raise an error
                                        // if we have a line length change at
                                        // any line other than the last line in
                                        // the sequence
    bool emptyLine = false;  // flag to catch empty lines, which we allow for
                             // index generation only on the last line of the sequence
    ifstream refFile;
    refFile.open(refname.c_str());
    if (refFile.is_open()) {
        while (getline(refFile, line)) {
            ++line_number;
            line_length = line.length();
            if (line[0] == ';') {
                // fasta comment, skip
            } else if (line[0] == '+') {
                // fastq quality header
                getline(refFile, line);
                line_length = line.length();
                offset += line_length + 1;
                // get and don't handle the quality line
                getline(refFile, line);
                line_length = line.length();
            } else if (line[0] == '>' || line[0] == '@') { // fasta /fastq header
                // if we aren't on the first entry, push the last sequence into the index
                if (entry.name != "") {
                    mismatchedLineLengths = false; // reset line length error tracker for every new sequence
                    emptyLine = false;
                    flushEntryToIndex(entry);
                    entry.clear();
                }
                entry.name = line.substr(1, line_length - 1);
            } else { // we assume we have found a sequence line
                if (entry.offset == -1) // NB initially the offset is -1
                    entry.offset = offset;
                entry.length += line_length;
                if (entry.line_len) {
                    //entry.line_len = entry.line_len ? entry.line_len : line_length + 1;
                    if (mismatchedLineLengths || emptyLine) {
                        if (line_length == 0) {
                            emptyLine = true; // flag empty lines, raise error only if this is embedded in the sequence
                        } else {
                            if (emptyLine) {
                                cerr << "ERROR: embedded newline";
                            } else {
                                cerr << "ERROR: mismatched line lengths";
                            }
                            cerr << " at line " << line_number << " within sequence " << entry.name <<
                                endl << "File not suitable for fasta index generation." << endl;
                            exit(1);
                        }
                    }
                    // this flag is set here and checked on the next line
                    // because we may have reached the end of the sequence, in
                    // which case a mismatched line length is OK
                    if (entry.line_len != line_length + 1) {
                        mismatchedLineLengths = true;
                        if (line_length == 0) {
                            emptyLine = true; // flag empty lines, raise error only if this is embedded in the sequence
                        }
                    }
                } else {
                    entry.line_len = line_length + 1; // first line
                }
                entry.line_blen = entry.line_len - 1;
            }
            offset += line_length + 1;
        }
        // we've hit the end of the fasta file!
        // flush the last entry
        flushEntryToIndex(entry);
    } else {
        cerr << "could not open reference file " << refname << " for indexing!" << endl;
        exit(1);
    }
}

void FastaIndex::flushEntryToIndex(FastaIndexEntry& entry) {
    this->insert(pair<string, FastaIndexEntry>(entry.name,
                FastaIndexEntry(entry.name, entry.length,
                                entry.offset, entry.line_blen,
                                entry.line_len)));

}

void FastaIndex::writeIndexFile(string fname) {
    cerr << "writing fasta index file " << fname << endl;
    ofstream file;
    file.open(fname.c_str());
    if (file.is_open()) {
        file << *this;
    } else {
        cerr << "could not open index file " << fname << " for writing!" << endl;
        exit(1);
    }
}

FastaIndex::~FastaIndex(void) {
    indexFile.close();
}

FastaIndexEntry FastaIndex::entry(string name) {
    return this->find(name)->second;
}

string FastaIndex::indexFileExtension() { return ".fai"; }

FastaReference::FastaReference(string reffilename) {
    filename = reffilename;
    file = fopen(filename.c_str(), "r");
    index = new FastaIndex();
    struct stat stFileInfo;
    string indexFileName = filename + index->indexFileExtension();
    // if we can find an index file, use it
    if(stat(indexFileName.c_str(), &stFileInfo) == 0) {
        index->readIndexFile(indexFileName);
    } else { // otherwise, read the reference and generate the index file in the cwd
        cerr << "index file " << indexFileName << " not found, generating..." << endl;
        index->indexReference(filename);
        index->writeIndexFile(indexFileName);
    }
}

FastaReference::~FastaReference(void) {
    fclose(file);
    delete index;
}

string FastaReference::getSequence(string seqname) {
    FastaIndexEntry entry = index->entry(seqname);
    int newlines_in_sequence = entry.length / entry.line_blen;
    int total_length = newlines_in_sequence  + entry.length;
    char* seq = (char*) malloc (sizeof(char)*total_length);
    fseek64(file, entry.offset, SEEK_SET);
    fread(seq, sizeof(char), total_length, file);
    char* pbegin = seq;
    char* pend = seq + ((string)seq).size()/sizeof(char);
    pend = remove (pbegin, pend, '\n');
    // TODO check if this works for \r
    // pend = remove (pbegin, pend, '\r');
    string s = seq;
    s.resize((pend - pbegin)/sizeof(char));
    return s;
}

string FastaReference::sequenceNameStartingWith(string seqnameStart) {
    string teststr;
    string result = "";
    vector<string> fields;
    for(map<string, FastaIndexEntry>::const_iterator it = index->begin(); it != index->end(); ++it)
    {
        boost::split(fields, it->second.name, boost::is_any_of("\t ")); // split on ws
        // check if the first field is the same as our startseq
        teststr = fields.at(0);
        if (teststr == seqnameStart) {
            if (result == "") {
                result = it->second.name;
            } else {
                cerr << " is not unique in fasta index" << endl;
                return "";
            }
        }
    }
    if (result != "") {
        return result;
    } else {
        cerr << "could not find sequence named " << seqnameStart << endl;
        return ""; // XXX returning an empty string is a bad result; it should raise an error!!!
    }
}

string FastaReference::getSubSequence(string seqname, int start, int length) {
    FastaIndexEntry entry = index->entry(seqname);
    if (start < 0 || length < 1) {
        cerr << "Error: cannot construct subsequence with negative offset or length < 1" << endl;
        exit(1);
    }
    // we have to handle newlines
    // approach: count newlines before start
    //           count newlines by end of read
    //             subtracting newlines before start find count of embedded newlines
    int newlines_before = start > 0 ? (start - 1) / entry.line_blen : 0;
    int newlines_by_end = (start + length - 1) / entry.line_blen;
    int newlines_inside = newlines_by_end - newlines_before;
    /*
    cout << "start: " << start << " length: " << length << endl;
    cout << "newlines before: " << newlines_before << endl;
    cout << "newlines inside: " << newlines_inside << endl;
    */
    int seqlen = length + newlines_inside;
    char* seq = (char*) malloc (sizeof(char)*seqlen + 1);
    fseek64(file, (off_t) (entry.offset + newlines_before + start), SEEK_SET);
    fread(seq, sizeof(char), (off_t) seqlen, file);
    seq[seqlen] = '\0';
    string s = seq;
    boost::erase_all(s, "\n");
    return s;
}

long unsigned int FastaReference::sequenceLength(string seqname) {
    FastaIndexEntry entry = index->entry(seqname);
    return entry.length;
}

<|endoftext|>


<commit_before>/**
* \file main.cpp
* \brief test/demo program
* \author Arthur Brainville
*
* Annwvyn test program http://annwvyn.org/
*
*/

#include "stdafx.h"

//Annwvyn
#include <Annwvyn.h>
#include <Ann3DTextPlane.hpp>
#include "TestLevel.hpp"
#include "DemoLevel.hpp"
#include "DemoEvent.hpp"

using namespace std;
using namespace Annwvyn;

constexpr bool isRoomscale{ true };

void putGizmoOnHands()
{
	static volatile bool done[2] = { false, false };
	enum sideNames : size_t
	{
		left = 0x0,
		right = 0x1
	};

	for (auto side : { left, right })
	{
		if (!done[side])
		{
			if (auto controller = AnnGetVRRenderer()->getHandControllerArray()[side])
			{
				Ogre::v1::MeshPtr v1; Ogre::MeshPtr v2;
				if (side == left)
					v2 = AnnGetGameObjectManager()->getMesh("Hand_left.mesh", v1, v2);
				else
					v2 = AnnGetGameObjectManager()->getMesh("Hand_right.mesh", v1, v2);
				controller->attachModel(AnnGetEngine()->getSceneManager()->createItem(v2));
				done[side] = true;
			}
		}
	}
}

class QuitOnButtonListener : LISTENER
{
public:
	QuitOnButtonListener() : constructListener()
	{
	}

	///Quit app when button zero of left controller is pressed
	void HandControllerEvent(AnnHandControllerEvent e) override
	{
		auto controller = e.getController();
		if (controller->getSide() == AnnHandController::leftHandController)
			if (controller->hasBeenPressed(0))
				AnnGetEngine()->requestQuit();
	}
};

function<void()> debugHook;

AnnMain()
{
	OgreVRRender::setAntiAliasingLevel(16);
	AnnEngine::openConsole();

	AnnInit("AnnTest");

	//Init some player body parameters
	if (isRoomscale)
		AnnGetEngine()->initPlayerRoomscalePhysics();
	else
		AnnGetEngine()->initPlayerStandingPhysics();

	AnnGetEventManager()->useDefaultEventListener();
	AnnGetResourceManager()->addFileLocation("media/environment");
	AnnGetResourceManager()->addFileLocation("script");
	AnnGetResourceManager()->initResources();

	//create and load level objects
	AnnGetLevelManager()->addLevel(make_shared<DemoHub>());
	AnnGetLevelManager()->addLevel(make_shared<Demo0>());
	AnnGetLevelManager()->addLevel(make_shared<TestLevel>());
	AnnGetLevelManager()->addLevel(make_shared<DemoEvent>());

	AnnGetLevelManager()->addLevel(make_shared<AnnSplashLevel>("splash.png", AnnGetLevelManager()->getFirstLevelLoaded(), 1.f));

	//ask the level manager to perform a jump to the last level
	AnnGetLevelManager()->jump(AnnGetLevelManager()->getLastLevelLoaded());
	AnnDebug() << "Starting the render loop";

	debugHook = []()
	{
		putGizmoOnHands();
	};

	do
	{
		debugHook();
	} while (AnnGetEngine()->refresh());

	AnnQuit();

	return EXIT_SUCCESS;
}<commit_msg>put AA back to 8<commit_after>/**
* \file main.cpp
* \brief test/demo program
* \author Arthur Brainville
*
* Annwvyn test program http://annwvyn.org/
*
*/

#include "stdafx.h"

//Annwvyn
#include <Annwvyn.h>
#include <Ann3DTextPlane.hpp>
#include "TestLevel.hpp"
#include "DemoLevel.hpp"
#include "DemoEvent.hpp"

using namespace std;
using namespace Annwvyn;

constexpr bool isRoomscale{ true };

void putGizmoOnHands()
{
	static volatile bool done[2] = { false, false };
	enum sideNames : size_t
	{
		left = 0x0,
		right = 0x1
	};

	for (auto side : { left, right })
	{
		if (!done[side])
		{
			if (auto controller = AnnGetVRRenderer()->getHandControllerArray()[side])
			{
				Ogre::v1::MeshPtr v1; Ogre::MeshPtr v2;
				if (side == left)
					v2 = AnnGetGameObjectManager()->getMesh("Hand_left.mesh", v1, v2);
				else
					v2 = AnnGetGameObjectManager()->getMesh("Hand_right.mesh", v1, v2);
				controller->attachModel(AnnGetEngine()->getSceneManager()->createItem(v2));
				done[side] = true;
			}
		}
	}
}

class QuitOnButtonListener : LISTENER
{
public:
	QuitOnButtonListener() : constructListener()
	{
	}

	///Quit app when button zero of left controller is pressed
	void HandControllerEvent(AnnHandControllerEvent e) override
	{
		auto controller = e.getController();
		if (controller->getSide() == AnnHandController::leftHandController)
			if (controller->hasBeenPressed(0))
				AnnGetEngine()->requestQuit();
	}
};

function<void()> debugHook;

AnnMain()
{
	OgreVRRender::setAntiAliasingLevel(8);
	AnnEngine::openConsole();

	AnnInit("AnnTest");

	//Init some player body parameters
	if (isRoomscale)
		AnnGetEngine()->initPlayerRoomscalePhysics();
	else
		AnnGetEngine()->initPlayerStandingPhysics();

	AnnGetEventManager()->useDefaultEventListener();
	AnnGetResourceManager()->addFileLocation("media/environment");
	AnnGetResourceManager()->addFileLocation("script");
	AnnGetResourceManager()->initResources();

	//create and load level objects
	AnnGetLevelManager()->addLevel(make_shared<DemoHub>());
	AnnGetLevelManager()->addLevel(make_shared<Demo0>());
	AnnGetLevelManager()->addLevel(make_shared<TestLevel>());
	AnnGetLevelManager()->addLevel(make_shared<DemoEvent>());

	AnnGetLevelManager()->addLevel(make_shared<AnnSplashLevel>("splash.png", AnnGetLevelManager()->getFirstLevelLoaded(), 1.f));

	//ask the level manager to perform a jump to the last level
	AnnGetLevelManager()->jump(AnnGetLevelManager()->getLastLevelLoaded());
	AnnDebug() << "Starting the render loop";

	debugHook = []()
	{
		putGizmoOnHands();
	};

	do
	{
		debugHook();
	} while (AnnGetEngine()->refresh());

	AnnQuit();

	return EXIT_SUCCESS;
}<|endoftext|>


<commit_before>#include <iostream>
#include <vector>
#include <set>
#include <map>
#include <sstream>

#include "stream_iterator.hpp"
#include "templateio.hpp"
#include "profile.hpp"

using namespace std;

//============================================================================
// Logic Language Parser.
//
// A simple parser for a Prolog like language.

//----------------------------------------------------------------------------
// Syntactic Structure.
//
// A global set of names keeps string comparisons for atoms and varibles to
// a single iterator (pointer) comparison. A single type is used for atoms
// and structs, which is combined with a variable type in an expression
// supertype. Clauses combine heads and goals, and keep track of repeated
// variables in the head for efficient post-unification cycle checking.

using name_t = set<string>::const_iterator;

struct type_expression {
    virtual ostream& operator<< (ostream& out) const = 0;
};

struct type_variable : public type_expression {
    name_t const name;

    type_variable(name_t n) : name(n) {}

    virtual ostream& operator<< (ostream& out) const override {
        out << *name;
        return out;
    }
};

struct type_struct : public type_expression {
    name_t const name;
    vector<type_expression*> const args;

    template <typename As>
    type_struct(name_t n, As&& as) : name(n), args(forward<As>(as)) {}

    ostream& operator<< (ostream& out) const override {
        out << *name << "(";
        for (auto i = args.cbegin(); i != args.cend(); ++i) {
            (*i)->operator<<(out);
            auto j = i;
            if (++j != args.end()) {
                out << ", ";
            }
        }
        out << ")";
        return out;
    }
};

ostream& operator<< (ostream& out, type_expression* exp) {
    exp->operator<<(out);
    return out;
}

struct clause {
    type_struct* const head;
    vector<type_struct*> const impl;
    set<type_variable*> const reps;

    template <typename Is, typename Rs>
    clause(type_struct* h, Is&& is, Rs&& rs) : head(h), impl(forward<Is>(is)),
        reps(forward<Rs>(rs)) {}
};

ostream& operator<< (ostream& out, clause* cls) {
    cls->head->operator<<(out);
    auto f = cls->impl.cbegin();
    auto const l = cls->impl.cend();
    if (f != l) {
        out << " :-" << endl;
        for (auto i = f; i != l; ++i) {
            out << "\t";
            (*i)->operator<<(out);
            auto j = i;
            if (++j != l) {
                out << "," << endl;
            }
        }
    }
    out << ".";

    auto g = cls->reps.cbegin();
    auto const m = cls->reps.cend();
    if (g != m) {
        out << " [";
        for (auto i = g; i != m; ++i) {
            (*i)->operator<<(out);
            auto j = i;
            if (++j != m) {
                out << ", ";
            }
        }
        out << "]";
    }
    out << endl;

    return out;
}

//----------------------------------------------------------------------------
// Parser State
//
// Making this uncopyable prevents backtracking being used, as the 'attempt'
// combinator will try and make a copy of the inherited attribute for
// backtracking. This can be seen as a constraint on the parser (to ensure
// performance) or a safety measure to make sure we deal with copying if we
// want backtracking.

using var_t = map<string const*, type_variable*>::const_iterator;

struct parser_state {
    set<string> names; // global name table
    map<string const*, type_variable*> variables;
    set<type_variable*> repeated;
    set<type_variable*> repeated_in_goal;

    parser_state() {};
    parser_state(parser_state const&) = delete;
    parser_state& operator= (parser_state const&) = delete;

    name_t get_name(string const& name) {
        name_t const n = names.find(name);
        if (n == names.end()) {
            return names.insert(name).first;
        } else {
            return n;
        }
    }
};

//----------------------------------------------------------------------------
// Grammar
//
// Function objects get passed the results of the sub-parsers, along with the
// inherited attribute. As the parser-combinators are templated, the inherited
// attribute is whatever type is passed as the final argument to the parser.

struct return_variable {
    return_variable() {}
    void operator() (type_variable** res, string const& name, parser_state* st) const {
        name_t const n = st->get_name(name);
        var_t i = st->variables.find(&(*n));
        if (i == st->variables.end()) {
            type_variable* const var = new type_variable(n);
            st->variables.insert(make_pair(&(*n), var));
            *res = var;
        } else {
            st->repeated.insert(i->second);
            *res = i->second;
        }
    }
} const return_variable;

struct return_args {
    return_args() {}
    void operator() (vector<type_expression*>* res, int n, type_variable* var, type_struct* str, parser_state*) const {
        switch(n) {
            case 0:
                res->push_back(var);
                break;
            case 1:
                res->push_back(str);
                break;
        }
    }
} const return_args;

struct return_struct {
    return_struct() {}
    void operator() (type_struct** res, string const& name, vector<type_expression*>& args, parser_state* st) const {
        name_t n = st->get_name(name);
        *res = new type_struct(n, args);
    }
} const return_struct;

struct return_head {
    return_head() {}
    void operator() (type_struct** res, type_struct* str, parser_state* st) const {
        *res = str;
        st->repeated_in_goal = st->repeated;
    }
} const return_head;

struct return_goal {
    return_goal() {}
    void operator() (vector<type_struct*>* res, type_struct* impl, parser_state*) const {
        res->push_back(impl);
    }
} const return_goal;

struct return_clause {
    return_clause() {}
    void operator() (vector<clause*>* res, type_struct* head, vector<type_struct*>& impl, parser_state* st) const {
        res->push_back(new clause(head, impl, st->repeated_in_goal));
        st->variables.clear();
        st->repeated.clear();
        st->repeated_in_goal.clear();
    }
} const return_clause;

struct return_goals {
    return_goals() {}
    void operator() (vector<clause*>* res, vector<type_struct*>& impl, parser_state* st) const {
        vector<type_expression*> vars;
        for (auto v : st->variables) {
            vars.push_back(v.second);
        }
        res->push_back(new clause(
            new type_struct(st->get_name("goal"), vars), impl, set<type_variable*> {}
        ));

        st->variables.clear();
        st->repeated.clear();
        st->repeated_in_goal.clear();
    }
} const return_goals;

//----------------------------------------------------------------------------
// Parser
//
// The parsers and user grammar are all stateless, so can be const objects and
// still thread safe. The final composed parser is a regular proceedure, all state
// is either in the state object passed in, or in the returned values.

using expression_handle = pstream_handle<string, parser_state>;

auto const atom_tok = tokenise(some(accept(is_lower)) && many(accept(is_alnum || is_char('_'))));
auto const var_tok = tokenise(some(accept(is_upper || is_char('_'))) && many(accept(is_alnum)));
auto const open_tok = tokenise(accept(is_char('(')));
auto const close_tok = tokenise(accept(is_char(')')));
auto const sep_tok = tokenise(accept(is_char(',')));
auto const impl_tok = tokenise(accept_str(":-"));
auto const end_tok = tokenise(accept(is_char('.')));
auto const comment_tok = tokenise(accept(is_char('#')) && many(accept(is_print)) && accept(is_char('\n')));

pstream_handle<type_struct*, parser_state> const structure(pstream_handle<type_struct*, parser_state> const s) {
    return all(return_struct, atom_tok,
        option(discard(open_tok)
        && sep_by(any(return_args, all(return_variable, var_tok), s), discard(sep_tok))
        && discard(close_tok)));
}

pstream_handle<type_struct*, parser_state> const goal = structure(reference("structure", goal));

auto const clause = all(return_clause, all(return_head, goal),
    option(discard(impl_tok) && sep_by(all(return_goal, goal), discard(sep_tok))) && discard(end_tok))
    || discard(impl_tok) && all(return_goals, sep_by(all(return_goal, goal), discard(sep_tok)) && discard(end_tok))
    || discard(comment_tok);

struct expression_parser;

template <typename Range>
int parse(Range const &r) {
    auto const parser = first_token && some(clause);
    decltype(parser)::result_type a {};
    typename Range::iterator i = r.first;
    parser_state st;

    profile<expression_parser> p;
    if (parser(i, r, &a, &st)) {
        cout << "OK" << endl;
    } else {
        cout << "FAIL" << endl;
    }

    cout << a << endl;

    return i - r.first;
}

//----------------------------------------------------------------------------
// The stream_range allows file iterators to be used like random_iterators
// and abstracts the difference between C++ stdlib streams and file_vectors.

int main(int const argc, char const *argv[]) {
    if (argc < 1) {
        cerr << "no input files" << endl;
    } else {
        for (int i = 1; i < argc; ++i) {
            profile<expression_parser>::reset();
            stream_range in(argv[i]);
            cout << argv[i] << endl;
            int const chars_read = parse(in);
            double const mb_per_s = static_cast<double>(chars_read) / static_cast<double>(profile<expression_parser>::report());
            cout << "parsed: " << mb_per_s << "MB/s" << endl;
        }
    }
}
<commit_msg>fix typo<commit_after>#include <iostream>
#include <vector>
#include <set>
#include <map>
#include <sstream>

#include "stream_iterator.hpp"
#include "templateio.hpp"
#include "profile.hpp"

using namespace std;

//============================================================================
// Logic Language Parser.
//
// A simple parser for a Prolog like language.

//----------------------------------------------------------------------------
// Syntactic Structure.
//
// A global set of names keeps string comparisons for atoms and varibles to
// a single iterator (pointer) comparison. A single type is used for atoms
// and structs, which is combined with a variable type in an expression
// supertype. Clauses combine heads and goals, and keep track of repeated
// variables in the head for efficient post-unification cycle checking.

using name_t = set<string>::const_iterator;

struct type_expression {
    virtual ostream& operator<< (ostream& out) const = 0;
};

struct type_variable : public type_expression {
    name_t const name;

    type_variable(name_t n) : name(n) {}

    virtual ostream& operator<< (ostream& out) const override {
        out << *name;
        return out;
    }
};

struct type_struct : public type_expression {
    name_t const name;
    vector<type_expression*> const args;

    template <typename As>
    type_struct(name_t n, As&& as) : name(n), args(forward<As>(as)) {}

    ostream& operator<< (ostream& out) const override {
        out << *name << "(";
        for (auto i = args.cbegin(); i != args.cend(); ++i) {
            (*i)->operator<<(out);
            auto j = i;
            if (++j != args.end()) {
                out << ", ";
            }
        }
        out << ")";
        return out;
    }
};

ostream& operator<< (ostream& out, type_expression* exp) {
    exp->operator<<(out);
    return out;
}

struct clause {
    type_struct* const head;
    vector<type_struct*> const impl;
    set<type_variable*> const reps;

    template <typename Is, typename Rs>
    clause(type_struct* h, Is&& is, Rs&& rs) : head(h), impl(forward<Is>(is)),
        reps(forward<Rs>(rs)) {}
};

ostream& operator<< (ostream& out, clause* cls) {
    cls->head->operator<<(out);
    auto f = cls->impl.cbegin();
    auto const l = cls->impl.cend();
    if (f != l) {
        out << " :-" << endl;
        for (auto i = f; i != l; ++i) {
            out << "\t";
            (*i)->operator<<(out);
            auto j = i;
            if (++j != l) {
                out << "," << endl;
            }
        }
    }
    out << ".";

    auto g = cls->reps.cbegin();
    auto const m = cls->reps.cend();
    if (g != m) {
        out << " [";
        for (auto i = g; i != m; ++i) {
            (*i)->operator<<(out);
            auto j = i;
            if (++j != m) {
                out << ", ";
            }
        }
        out << "]";
    }
    out << endl;

    return out;
}

//----------------------------------------------------------------------------
// Parser State
//
// Making this uncopyable prevents backtracking being used, as the 'attempt'
// combinator will try and make a copy of the inherited attribute for
// backtracking. This can be seen as a constraint on the parser (to ensure
// performance) or a safety measure to make sure we deal with copying if we
// want backtracking.

using var_t = map<string const*, type_variable*>::const_iterator;

struct parser_state {
    set<string> names; // global name table
    map<string const*, type_variable*> variables;
    set<type_variable*> repeated;
    set<type_variable*> repeated_in_goal;

    parser_state() {};
    parser_state(parser_state const&) = delete;
    parser_state& operator= (parser_state const&) = delete;

    name_t get_name(string const& name) {
        name_t const n = names.find(name);
        if (n == names.end()) {
            return names.insert(name).first;
        } else {
            return n;
        }
    }
};

//----------------------------------------------------------------------------
// Grammar
//
// Function objects get passed the results of the sub-parsers, along with the
// inherited attribute. As the parser-combinators are templated, the inherited
// attribute is whatever type is passed as the final argument to the parser.

struct return_variable {
    return_variable() {}
    void operator() (type_variable** res, string const& name, parser_state* st) const {
        name_t const n = st->get_name(name);
        var_t i = st->variables.find(&(*n));
        if (i == st->variables.end()) {
            type_variable* const var = new type_variable(n);
            st->variables.insert(make_pair(&(*n), var));
            *res = var;
        } else {
            st->repeated.insert(i->second);
            *res = i->second;
        }
    }
} const return_variable;

struct return_args {
    return_args() {}
    void operator() (vector<type_expression*>* res, int n, type_variable* var, type_struct* str, parser_state*) const {
        switch(n) {
            case 0:
                res->push_back(var);
                break;
            case 1:
                res->push_back(str);
                break;
        }
    }
} const return_args;

struct return_struct {
    return_struct() {}
    void operator() (type_struct** res, string const& name, vector<type_expression*>& args, parser_state* st) const {
        name_t n = st->get_name(name);
        *res = new type_struct(n, args);
    }
} const return_struct;

struct return_head {
    return_head() {}
    void operator() (type_struct** res, type_struct* str, parser_state* st) const {
        *res = str;
        st->repeated_in_goal = st->repeated;
    }
} const return_head;

struct return_goal {
    return_goal() {}
    void operator() (vector<type_struct*>* res, type_struct* impl, parser_state*) const {
        res->push_back(impl);
    }
} const return_goal;

struct return_clause {
    return_clause() {}
    void operator() (vector<clause*>* res, type_struct* head, vector<type_struct*>& impl, parser_state* st) const {
        res->push_back(new clause(head, impl, st->repeated_in_goal));
        st->variables.clear();
        st->repeated.clear();
        st->repeated_in_goal.clear();
    }
} const return_clause;

struct return_goals {
    return_goals() {}
    void operator() (vector<clause*>* res, vector<type_struct*>& impl, parser_state* st) const {
        vector<type_expression*> vars;
        for (auto v : st->variables) {
            vars.push_back(v.second);
        }
        res->push_back(new clause(
            new type_struct(st->get_name("goal"), vars), impl, set<type_variable*> {}
        ));

        st->variables.clear();
        st->repeated.clear();
        st->repeated_in_goal.clear();
    }
} const return_goals;

//----------------------------------------------------------------------------
// Parser
//
// The parsers and user grammar are all stateless, so can be const objects and
// still thread safe. The final composed parser is a regular procedure, all state
// is either in the state object passed in, or in the returned values.

using expression_handle = pstream_handle<string, parser_state>;

auto const atom_tok = tokenise(some(accept(is_lower)) && many(accept(is_alnum || is_char('_'))));
auto const var_tok = tokenise(some(accept(is_upper || is_char('_'))) && many(accept(is_alnum)));
auto const open_tok = tokenise(accept(is_char('(')));
auto const close_tok = tokenise(accept(is_char(')')));
auto const sep_tok = tokenise(accept(is_char(',')));
auto const impl_tok = tokenise(accept_str(":-"));
auto const end_tok = tokenise(accept(is_char('.')));
auto const comment_tok = tokenise(accept(is_char('#')) && many(accept(is_print)) && accept(is_char('\n')));

pstream_handle<type_struct*, parser_state> const structure(pstream_handle<type_struct*, parser_state> const s) {
    return all(return_struct, atom_tok,
        option(discard(open_tok)
        && sep_by(any(return_args, all(return_variable, var_tok), s), discard(sep_tok))
        && discard(close_tok)));
}

pstream_handle<type_struct*, parser_state> const goal = structure(reference("structure", goal));

auto const clause = all(return_clause, all(return_head, goal),
    option(discard(impl_tok) && sep_by(all(return_goal, goal), discard(sep_tok))) && discard(end_tok))
    || discard(impl_tok) && all(return_goals, sep_by(all(return_goal, goal), discard(sep_tok)) && discard(end_tok))
    || discard(comment_tok);

struct expression_parser;

template <typename Range>
int parse(Range const &r) {
    auto const parser = first_token && some(clause);
    decltype(parser)::result_type a {};
    typename Range::iterator i = r.first;
    parser_state st;

    profile<expression_parser> p;
    if (parser(i, r, &a, &st)) {
        cout << "OK" << endl;
    } else {
        cout << "FAIL" << endl;
    }

    cout << a << endl;

    return i - r.first;
}

//----------------------------------------------------------------------------
// The stream_range allows file iterators to be used like random_iterators
// and abstracts the difference between C++ stdlib streams and file_vectors.

int main(int const argc, char const *argv[]) {
    if (argc < 1) {
        cerr << "no input files" << endl;
    } else {
        for (int i = 1; i < argc; ++i) {
            profile<expression_parser>::reset();
            stream_range in(argv[i]);
            cout << argv[i] << endl;
            int const chars_read = parse(in);
            double const mb_per_s = static_cast<double>(chars_read) / static_cast<double>(profile<expression_parser>::report());
            cout << "parsed: " << mb_per_s << "MB/s" << endl;
        }
    }
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: edtwin.hxx,v $
 *
 *  $Revision: 1.24 $
 *
 *  last change: $Author: vg $ $Date: 2006-03-14 09:38:13 $
 *
 *  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
 *
 ************************************************************************/
#ifndef _EDTWIN_HXX
#define _EDTWIN_HXX

#ifndef _LINK_HXX
#include <tools/link.hxx>
#endif
#ifndef _TIMER_HXX
#include <vcl/timer.hxx>
#endif
#ifndef _WINDOW_HXX
#include <vcl/window.hxx>
#endif
#ifndef _TRANSFER_HXX
#include <svtools/transfer.hxx>
#endif

#ifndef _SWEVENT_HXX
#include <swevent.hxx>
#endif

#define _SVSTDARR_STRINGSISORTDTOR
#include <svtools/svstdarr.hxx>

class   SwWrtShell;
class   SwView;
class   SwRect;
class   SwDrawBase;
class   ViewShell;
class   SwAnchorMarker;
class   SdrViewUserMarker;
class   SdrObject;
class   SwShadowCursor;
class   DataChangedEvent;
class   SvxAutoCorrCfg;
class   SvxAutoCorrect;
class   SwPaM;
struct  SwApplyTemplate;
struct  QuickHelpData;

/*--------------------------------------------------------------------
    Beschreibung:   Eingabe-Fenster
 --------------------------------------------------------------------*/

class SwEditWin: public Window,
                public DropTargetHelper, public DragSourceHelper
{
friend void     ScrollMDI(ViewShell* pVwSh, const SwRect&,
                          USHORT nRangeX, USHORT nRangeY);
friend BOOL     IsScrollMDI(ViewShell* pVwSh, const SwRect&);

friend void     SizeNotify(ViewShell* pVwSh, const Size &);

friend void     PageNumNotify(  ViewShell* pVwSh,
                                USHORT nPhyNum,
                                USHORT nVirtNum,
                                const String& rPg );

    static  QuickHelpData* pQuickHlpData;

    static  BOOL    bReplaceQuote;
    static  long    nDDStartPosX, nDDStartPosY;

    static  Color   aTextColor;     //Textfarbe, fuer die Giesskanne
    static  BOOL    bTransparentBackColor; // Hintergrund transparent
    static  Color   aTextBackColor; //Texthintergrundfarbe, fuer die Giesskanne

    /*
     * Timer und Handler fuer das Weiterscrollen, wenn der
     * Mauspointer innerhalb eines Drag-Vorgangs ausserhalb des
     * EditWin stehen bleibt.  In regelmaessigen Intervallen wird
     * die Selektion in Richtung der Mausposition vergroessert.
     */
    AutoTimer       aTimer;
    // Timer fuer verschachtelte KeyInputs (z.B. fuer Tabellen)
    Timer           aKeyInputTimer;
    // timer for ANY-KeyInut question without a following KeyInputEvent
    Timer           aKeyInputFlushTimer;

    String          aInBuffer;
    LanguageType    eBufferLanguage;
    Point           aStartPos;
    Point           aMovePos;
    Point           aRszMvHdlPt;
    Timer           aTemplateTimer;

    // Type/Objecte ueber dem der MousePointer steht
    SwCallMouseEvent aSaveCallEvent;

    SwApplyTemplate     *pApplyTempl;
    SwAnchorMarker      *pAnchorMarker; // zum Verschieben eines Ankers

    SdrViewUserMarker   *pUserMarker;
    SdrObject           *pUserMarkerObj;
    SwShadowCursor      *pShadCrsr;
    Point               *pRowColumnSelectionStart; // save position where table row/column selection has been started

    SwView         &rView;

    int             aActHitType;    // aktueller Mauspointer

    ULONG           nDropFormat;    //Format aus dem letzten QueryDrop
    USHORT          nDropAction;    //Action aus dem letzten QueryDrop
    USHORT          nDropDestination;   //Ziel aus dem letzten QueryDrop

    UINT16          eDrawMode;
    UINT16          eBezierMode;
    UINT16          nInsFrmColCount; //Spaltenzahl fuer interaktiven Rahmen
    BOOL            bLinkRemoved    : 1,
                    bMBPressed      : 1,
                    bInsDraw        : 1,
                    bInsFrm         : 1,
                    bIsInMove       : 1,
                    bIsInDrag       : 1, //StartExecuteDrag nich doppelt ausfuehren
                    bOldIdle        : 1, //Zum abschalten des Idle'ns
                    bOldIdleSet     : 1, //waehrend QeueryDrop
                    bTblInsDelMode  : 1, //
                    bTblIsInsMode   : 1, //
                    bTblIsColMode   : 1, //
                    bChainMode      : 1, //Rahmen verbinden
                    bWasShdwCrsr    : 1, //ShadowCrsr war im MouseButtonDown an
                    bLockInput      : 1, //Lock waehrend die Rechenleiste aktiv ist
                    bIsRowDrag      : 1; //selection of rows is used, in combination with pRowColumnSelectionStart

    USHORT          nKS_NUMDOWN_Count; // #i23725#
    USHORT          nKS_NUMINDENTINC_Count;

    void            LeaveArea(const Point &);
    void            JustifyAreaTimer();
    inline void     EnterArea();

    void            RstMBDownFlags();

    void            ChangeFly( BYTE nDir, BOOL bWeb = FALSE );
    void            ChangeDrawing( BYTE nDir );

    BOOL            EnterDrawMode(const MouseEvent& rMEvt, const Point& aDocPos);
    BOOL            RulerColumnDrag( SwView& , const MouseEvent& rMEvt, BOOL bVerticalMode);

    //Hilfsfunktionen fuer D&D
    void            DropCleanup();
    void            CleanupDropUserMarker();
    USHORT          GetDropDestination( const Point& rPixPnt,
                                        SdrObject ** ppObj = 0 );
    //select the object/cursor at the mouse position of the context menu request
    BOOL            SelectMenuPosition(SwWrtShell& rSh, const Point& rMousePos );

    /*
     * Handler fuer das Weiterscrollen, wenn der Mauspointer innerhalb eines
     * Drag-Vorgangs ausserhalb des EditWin stehen bleibt. In regelmaessigen
     * Intervallen wird die Selektion in Richtung der Mausposition
     * vergroessert.
     */
    DECL_LINK( TimerHandler, Timer * );
    void            StartDDTimer();
    void            StopDDTimer(SwWrtShell *, const Point &);
    DECL_LINK( DDHandler, Timer * );

    // timer for ANY-KeyInut question without a following KeyInputEvent
    DECL_LINK( KeyInputFlushHandler, Timer * );

    // Timer fuer verschachtelte KeyInputs (z.B. fuer Tabellen)
    DECL_LINK( KeyInputTimerHandler, Timer * );

    // Timer fuer das ApplyTemplates per Maus (verkapptes Drag&Drop)
    DECL_LINK( TemplateTimerHdl, Timer* );

protected:

    virtual void    DataChanged( const DataChangedEvent& );
    virtual void    Paint( const Rectangle& rRect );
    virtual void    KeyInput(const KeyEvent &rKEvt);

    virtual void    GetFocus();
    virtual void    LoseFocus();

    virtual void    MouseMove(const MouseEvent& rMEvt);
    virtual void    MouseButtonDown(const MouseEvent& rMEvt);
    virtual void    MouseButtonUp(const MouseEvent& rMEvt);
    virtual void    RequestHelp(const HelpEvent& rEvt);

    virtual void    Command( const CommandEvent& rCEvt );

                                // Drag & Drop Interface
    virtual sal_Int8    AcceptDrop( const AcceptDropEvent& rEvt );
    virtual sal_Int8    ExecuteDrop( const ExecuteDropEvent& rEvt );
    virtual void        StartDrag( sal_Int8 nAction, const Point& rPosPixel );

    void    ShowAutoTextCorrectQuickHelp( const String& rWord, SvxAutoCorrCfg* pACfg,
                                SvxAutoCorrect* pACorr, sal_Bool bFromIME = sal_False );
public:

    void            UpdatePointer(const Point &, USHORT nButtons = 0);

    BOOL            IsDrawSelMode();
    BOOL            IsDrawAction()                  { return (bInsDraw); }
    void            SetDrawAction(BOOL bFlag)       { bInsDraw = bFlag; }
    inline UINT16   GetDrawMode(BOOL bBuf = FALSE) const { return eDrawMode; }
    inline void     SetDrawMode(UINT16 eDrwMode)    { eDrawMode = eDrwMode; }
    void            StdDrawMode(USHORT nSlotId);
    BOOL            IsFrmAction()                   { return (bInsFrm); }
    inline UINT16   GetBezierMode()                 { return eBezierMode; }
    void            SetBezierMode(UINT16 eBezMode)  { eBezierMode = eBezMode; }
    void            EnterDrawTextMode(const Point& aDocPos); // DrawTextEditMode einschalten
    void            InsFrm(USHORT nCols);
    void            StopInsFrm();
    UINT16          GetFrmColCount() const {return nInsFrmColCount;} //Spaltenzahl fuer interaktiven Rahmen

    void            SetChainMode( BOOL bOn );
    BOOL            IsChainMode() const             { return bChainMode; }

    void            FlushInBuffer();
    BOOL            IsInputSequenceChecking( const String &rText, const SwPaM& rCrsr ) const;

    static  void    SetReplaceQuote(BOOL bOn = TRUE) { bReplaceQuote = bOn; }
    static  BOOL    IsReplaceQuote() { return bReplaceQuote; }

    void             SetApplyTemplate(const SwApplyTemplate &);
    SwApplyTemplate* GetApplyTemplate() const { return pApplyTempl; }

    void            StartExecuteDrag();
    void            DragFinished();
    USHORT          GetDropAction() const { return nDropAction; }
    ULONG           GetDropFormat() const { return nDropFormat; }

    Color           GetTextColor() { return aTextColor; }
    void            SetTextColor(const Color& rCol ) { aTextColor = rCol; }

    Color           GetTextBackColor()
                                            { return aTextBackColor; }
    void            SetTextBackColor(const Color& rCol )
                                            { aTextBackColor = rCol; }
    void            SetTextBackColorTransparent(BOOL bSet)
                                    { bTransparentBackColor = bSet; }
    BOOL            IsTextBackColorTransparent()
                                    { return bTransparentBackColor; }
    void            LockKeyInput(BOOL bSet){bLockInput = bSet;}

    const SwView &GetView() const { return rView; }
          SwView &GetView()       { return rView; }

    virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible > CreateAccessible();

    // Tipfenster loeschen
    static void ClearTip();

    static inline long GetDDStartPosX() { return nDDStartPosX; }
    static inline long GetDDStartPosY() { return nDDStartPosY; }

    static void _InitStaticData();
    static void _FinitStaticData();

    //#i3370# remove quick help to prevent saving of autocorrection suggestions
    void StopQuickHelp();

    // --> OD 2005-02-18 #i42921# - add parameter <bVerticalMode>
    BOOL RulerMarginDrag( SwView& rView,
                                     const MouseEvent& rMEvt,
                                     const bool bVerticalMode );
    // <--

    SwEditWin(Window *pParent, SwView &);
    virtual ~SwEditWin();
};

#endif

<commit_msg>INTEGRATION: CWS tl18 (1.24.38); FILE MERGED 2006/04/19 14:05:41 tl 1.24.38.1: #i64467# applying function name change to be consistent with naming in svx<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: edtwin.hxx,v $
 *
 *  $Revision: 1.25 $
 *
 *  last change: $Author: rt $ $Date: 2006-05-05 08:09:06 $
 *
 *  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
 *
 ************************************************************************/
#ifndef _EDTWIN_HXX
#define _EDTWIN_HXX

#ifndef _LINK_HXX
#include <tools/link.hxx>
#endif
#ifndef _TIMER_HXX
#include <vcl/timer.hxx>
#endif
#ifndef _WINDOW_HXX
#include <vcl/window.hxx>
#endif
#ifndef _TRANSFER_HXX
#include <svtools/transfer.hxx>
#endif

#ifndef _SWEVENT_HXX
#include <swevent.hxx>
#endif

#define _SVSTDARR_STRINGSISORTDTOR
#include <svtools/svstdarr.hxx>

class   SwWrtShell;
class   SwView;
class   SwRect;
class   SwDrawBase;
class   ViewShell;
class   SwAnchorMarker;
class   SdrViewUserMarker;
class   SdrObject;
class   SwShadowCursor;
class   DataChangedEvent;
class   SvxAutoCorrCfg;
class   SvxAutoCorrect;
class   SwPaM;
struct  SwApplyTemplate;
struct  QuickHelpData;

/*--------------------------------------------------------------------
    Beschreibung:   Eingabe-Fenster
 --------------------------------------------------------------------*/

class SwEditWin: public Window,
                public DropTargetHelper, public DragSourceHelper
{
friend void     ScrollMDI(ViewShell* pVwSh, const SwRect&,
                          USHORT nRangeX, USHORT nRangeY);
friend BOOL     IsScrollMDI(ViewShell* pVwSh, const SwRect&);

friend void     SizeNotify(ViewShell* pVwSh, const Size &);

friend void     PageNumNotify(  ViewShell* pVwSh,
                                USHORT nPhyNum,
                                USHORT nVirtNum,
                                const String& rPg );

    static  QuickHelpData* pQuickHlpData;

    static  BOOL    bReplaceQuote;
    static  long    nDDStartPosX, nDDStartPosY;

    static  Color   aTextColor;     //Textfarbe, fuer die Giesskanne
    static  BOOL    bTransparentBackColor; // Hintergrund transparent
    static  Color   aTextBackColor; //Texthintergrundfarbe, fuer die Giesskanne

    /*
     * Timer und Handler fuer das Weiterscrollen, wenn der
     * Mauspointer innerhalb eines Drag-Vorgangs ausserhalb des
     * EditWin stehen bleibt.  In regelmaessigen Intervallen wird
     * die Selektion in Richtung der Mausposition vergroessert.
     */
    AutoTimer       aTimer;
    // Timer fuer verschachtelte KeyInputs (z.B. fuer Tabellen)
    Timer           aKeyInputTimer;
    // timer for ANY-KeyInut question without a following KeyInputEvent
    Timer           aKeyInputFlushTimer;

    String          aInBuffer;
    LanguageType    eBufferLanguage;
    Point           aStartPos;
    Point           aMovePos;
    Point           aRszMvHdlPt;
    Timer           aTemplateTimer;

    // Type/Objecte ueber dem der MousePointer steht
    SwCallMouseEvent aSaveCallEvent;

    SwApplyTemplate     *pApplyTempl;
    SwAnchorMarker      *pAnchorMarker; // zum Verschieben eines Ankers

    SdrViewUserMarker   *pUserMarker;
    SdrObject           *pUserMarkerObj;
    SwShadowCursor      *pShadCrsr;
    Point               *pRowColumnSelectionStart; // save position where table row/column selection has been started

    SwView         &rView;

    int             aActHitType;    // aktueller Mauspointer

    ULONG           nDropFormat;    //Format aus dem letzten QueryDrop
    USHORT          nDropAction;    //Action aus dem letzten QueryDrop
    USHORT          nDropDestination;   //Ziel aus dem letzten QueryDrop

    UINT16          eDrawMode;
    UINT16          eBezierMode;
    UINT16          nInsFrmColCount; //Spaltenzahl fuer interaktiven Rahmen
    BOOL            bLinkRemoved    : 1,
                    bMBPressed      : 1,
                    bInsDraw        : 1,
                    bInsFrm         : 1,
                    bIsInMove       : 1,
                    bIsInDrag       : 1, //StartExecuteDrag nich doppelt ausfuehren
                    bOldIdle        : 1, //Zum abschalten des Idle'ns
                    bOldIdleSet     : 1, //waehrend QeueryDrop
                    bTblInsDelMode  : 1, //
                    bTblIsInsMode   : 1, //
                    bTblIsColMode   : 1, //
                    bChainMode      : 1, //Rahmen verbinden
                    bWasShdwCrsr    : 1, //ShadowCrsr war im MouseButtonDown an
                    bLockInput      : 1, //Lock waehrend die Rechenleiste aktiv ist
                    bIsRowDrag      : 1; //selection of rows is used, in combination with pRowColumnSelectionStart

    USHORT          nKS_NUMDOWN_Count; // #i23725#
    USHORT          nKS_NUMINDENTINC_Count;

    void            LeaveArea(const Point &);
    void            JustifyAreaTimer();
    inline void     EnterArea();

    void            RstMBDownFlags();

    void            ChangeFly( BYTE nDir, BOOL bWeb = FALSE );
    void            ChangeDrawing( BYTE nDir );

    BOOL            EnterDrawMode(const MouseEvent& rMEvt, const Point& aDocPos);
    BOOL            RulerColumnDrag( SwView& , const MouseEvent& rMEvt, BOOL bVerticalMode);

    //Hilfsfunktionen fuer D&D
    void            DropCleanup();
    void            CleanupDropUserMarker();
    USHORT          GetDropDestination( const Point& rPixPnt,
                                        SdrObject ** ppObj = 0 );
    //select the object/cursor at the mouse position of the context menu request
    BOOL            SelectMenuPosition(SwWrtShell& rSh, const Point& rMousePos );

    /*
     * Handler fuer das Weiterscrollen, wenn der Mauspointer innerhalb eines
     * Drag-Vorgangs ausserhalb des EditWin stehen bleibt. In regelmaessigen
     * Intervallen wird die Selektion in Richtung der Mausposition
     * vergroessert.
     */
    DECL_LINK( TimerHandler, Timer * );
    void            StartDDTimer();
    void            StopDDTimer(SwWrtShell *, const Point &);
    DECL_LINK( DDHandler, Timer * );

    // timer for ANY-KeyInut question without a following KeyInputEvent
    DECL_LINK( KeyInputFlushHandler, Timer * );

    // Timer fuer verschachtelte KeyInputs (z.B. fuer Tabellen)
    DECL_LINK( KeyInputTimerHandler, Timer * );

    // Timer fuer das ApplyTemplates per Maus (verkapptes Drag&Drop)
    DECL_LINK( TemplateTimerHdl, Timer* );

protected:

    virtual void    DataChanged( const DataChangedEvent& );
    virtual void    Paint( const Rectangle& rRect );
    virtual void    KeyInput(const KeyEvent &rKEvt);

    virtual void    GetFocus();
    virtual void    LoseFocus();

    virtual void    MouseMove(const MouseEvent& rMEvt);
    virtual void    MouseButtonDown(const MouseEvent& rMEvt);
    virtual void    MouseButtonUp(const MouseEvent& rMEvt);
    virtual void    RequestHelp(const HelpEvent& rEvt);

    virtual void    Command( const CommandEvent& rCEvt );

                                // Drag & Drop Interface
    virtual sal_Int8    AcceptDrop( const AcceptDropEvent& rEvt );
    virtual sal_Int8    ExecuteDrop( const ExecuteDropEvent& rEvt );
    virtual void        StartDrag( sal_Int8 nAction, const Point& rPosPixel );

    void    ShowAutoTextCorrectQuickHelp( const String& rWord, SvxAutoCorrCfg* pACfg,
                                SvxAutoCorrect* pACorr, sal_Bool bFromIME = sal_False );
public:

    void            UpdatePointer(const Point &, USHORT nButtons = 0);

    BOOL            IsDrawSelMode();
    BOOL            IsDrawAction()                  { return (bInsDraw); }
    void            SetDrawAction(BOOL bFlag)       { bInsDraw = bFlag; }
    inline UINT16   GetDrawMode(BOOL bBuf = FALSE) const { return eDrawMode; }
    inline void     SetDrawMode(UINT16 eDrwMode)    { eDrawMode = eDrwMode; }
    void            StdDrawMode(USHORT nSlotId);
    BOOL            IsFrmAction()                   { return (bInsFrm); }
    inline UINT16   GetBezierMode()                 { return eBezierMode; }
    void            SetBezierMode(UINT16 eBezMode)  { eBezierMode = eBezMode; }
    void            EnterDrawTextMode(const Point& aDocPos); // DrawTextEditMode einschalten
    void            InsFrm(USHORT nCols);
    void            StopInsFrm();
    UINT16          GetFrmColCount() const {return nInsFrmColCount;} //Spaltenzahl fuer interaktiven Rahmen

    void            SetChainMode( BOOL bOn );
    BOOL            IsChainMode() const             { return bChainMode; }

    void            FlushInBuffer();
    BOOL            IsInputSequenceCheckingRequired( const String &rText, const SwPaM& rCrsr ) const;

    static  void    SetReplaceQuote(BOOL bOn = TRUE) { bReplaceQuote = bOn; }
    static  BOOL    IsReplaceQuote() { return bReplaceQuote; }

    void             SetApplyTemplate(const SwApplyTemplate &);
    SwApplyTemplate* GetApplyTemplate() const { return pApplyTempl; }

    void            StartExecuteDrag();
    void            DragFinished();
    USHORT          GetDropAction() const { return nDropAction; }
    ULONG           GetDropFormat() const { return nDropFormat; }

    Color           GetTextColor() { return aTextColor; }
    void            SetTextColor(const Color& rCol ) { aTextColor = rCol; }

    Color           GetTextBackColor()
                                            { return aTextBackColor; }
    void            SetTextBackColor(const Color& rCol )
                                            { aTextBackColor = rCol; }
    void            SetTextBackColorTransparent(BOOL bSet)
                                    { bTransparentBackColor = bSet; }
    BOOL            IsTextBackColorTransparent()
                                    { return bTransparentBackColor; }
    void            LockKeyInput(BOOL bSet){bLockInput = bSet;}

    const SwView &GetView() const { return rView; }
          SwView &GetView()       { return rView; }

    virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible > CreateAccessible();

    // Tipfenster loeschen
    static void ClearTip();

    static inline long GetDDStartPosX() { return nDDStartPosX; }
    static inline long GetDDStartPosY() { return nDDStartPosY; }

    static void _InitStaticData();
    static void _FinitStaticData();

    //#i3370# remove quick help to prevent saving of autocorrection suggestions
    void StopQuickHelp();

    // --> OD 2005-02-18 #i42921# - add parameter <bVerticalMode>
    BOOL RulerMarginDrag( SwView& rView,
                                     const MouseEvent& rMEvt,
                                     const bool bVerticalMode );
    // <--

    SwEditWin(Window *pParent, SwView &);
    virtual ~SwEditWin();
};

#endif

<|endoftext|>