<commit_before>/*************************************************************************
 *
 *  $RCSfile: paragr.cxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: hr $ $Date: 2004-05-10 15:44:14 $
 *
 *  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): _______________________________________
 *
 *
 ************************************************************************/

#include <svx/editdata.hxx>

#pragma hdrstop

#include <svx/dialogs.hrc>
#include "eetext.hxx"
#include <svx/eeitem.hxx>
//CHINA001 #include <svx/tabstpge.hxx>

//CHINA001 #ifndef _SVX_PARAGRPH_HXX //autogen
//CHINA001 #include <svx/paragrph.hxx>
//CHINA001 #endif
#ifndef _SVTOOLS_CJKOPTIONS_HXX
#include <svtools/cjkoptions.hxx>
#endif
#include <svx/flagsdef.hxx> //CHINA001
#include "paragr.hxx"
#include "sdresid.hxx"

/*************************************************************************
|*
|* Konstruktor des Tab-Dialogs: Fuegt die Seiten zum Dialog hinzu
|*
\************************************************************************/

SdParagraphDlg::SdParagraphDlg( Window* pParent, const SfxItemSet* pAttr ) :
        SfxTabDialog        ( pParent, SdResId( TAB_PARAGRAPH ), pAttr ),
        rOutAttrs           ( *pAttr )
{
    FreeResource();

    AddTabPage( RID_SVXPAGE_STD_PARAGRAPH );//CHINA001 AddTabPage( RID_SVXPAGE_STD_PARAGRAPH, SvxStdParagraphTabPage::Create, 0);

    SvtCJKOptions aCJKOptions;
    if( aCJKOptions.IsAsianTypographyEnabled() )
        AddTabPage( RID_SVXPAGE_PARA_ASIAN);//CHINA001 AddTabPage( RID_SVXPAGE_PARA_ASIAN, SvxAsianTabPage::Create,0);
    else
        RemoveTabPage( RID_SVXPAGE_PARA_ASIAN );

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

#ifdef SD_DLLIMPLEMENTATION
#undef SD_DLLIMPLEMENTATION
#endif

#include <svx/editdata.hxx>

#pragma hdrstop

#include <svx/dialogs.hrc>
#include "eetext.hxx"
#include <svx/eeitem.hxx>
//CHINA001 #include <svx/tabstpge.hxx>

//CHINA001 #ifndef _SVX_PARAGRPH_HXX //autogen
//CHINA001 #include <svx/paragrph.hxx>
//CHINA001 #endif
#ifndef _SVTOOLS_CJKOPTIONS_HXX
#include <svtools/cjkoptions.hxx>
#endif
#include <svx/flagsdef.hxx> //CHINA001
#include "paragr.hxx"
#include "sdresid.hxx"

/*************************************************************************
|*
|* Konstruktor des Tab-Dialogs: Fuegt die Seiten zum Dialog hinzu
|*
\************************************************************************/

SdParagraphDlg::SdParagraphDlg( Window* pParent, const SfxItemSet* pAttr ) :
        SfxTabDialog        ( pParent, SdResId( TAB_PARAGRAPH ), pAttr ),
        rOutAttrs           ( *pAttr )
{
    FreeResource();

    AddTabPage( RID_SVXPAGE_STD_PARAGRAPH );//CHINA001 AddTabPage( RID_SVXPAGE_STD_PARAGRAPH, SvxStdParagraphTabPage::Create, 0);

    SvtCJKOptions aCJKOptions;
    if( aCJKOptions.IsAsianTypographyEnabled() )
        AddTabPage( RID_SVXPAGE_PARA_ASIAN);//CHINA001 AddTabPage( RID_SVXPAGE_PARA_ASIAN, SvxAsianTabPage::Create,0);
    else
        RemoveTabPage( RID_SVXPAGE_PARA_ASIAN );

    AddTabPage( RID_SVXPAGE_ALIGN_PARAGRAPH );//CHINA001 ddTabPage( RID_SVXPAGE_ALIGN_PARAGRAPH, SvxParaAlignTabPage::Create,0);
    AddTabPage( RID_SVXPAGE_TABULATOR );//CHINA001 AddTabPage( RID_SVXPAGE_TABULATOR, SvxTabulatorTabPage::Create, 0);
}
<|endoftext|>


<commit_before>/*
   For more information, please see: http://software.sci.utah.edu

   The MIT License

   Copyright (c) 2011 Scientific Computing and Imaging Institute,
   University of Utah.

   Permission is hereby granted, free of charge, to any person obtaining a
   copy of this software and associated documentation files (the "Software"),
   to deal in the Software without restriction, including without limitation
   the rights to use, copy, modify, merge, publish, distribute, sublicense,
   and/or sell copies of the Software, and to permit persons to whom the
   Software is furnished to do so, subject to the following conditions:

   The above copyright notice and this permission notice shall be included
   in all copies or substantial portions of the Software.

   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
   OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
   THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
   LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
   FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
   DEALINGS IN THE SOFTWARE.
*/
#include "StdDefines.h"
#include <aio.h>
#include <assert.h>
#include <cstring>
#include <errno.h>
#ifndef NDEBUG
# include <iostream>
# define DEBUG(s) do { std::cerr << s << "\n"; } while(0)
#else
# define DEBUG(s) do { /* nothing, debug msg removed. */ } while(0)
#endif
#include <stdexcept>
#include <vector>
#include "LargeFileAIO.h"

/// searches for a request among a list of outstanding AIO ops.  The given
/// offset is intended to be exact (i.e. this won't apply header offsets).
static struct aiocb* find_request(const LargeFileAIO::Reqs& reqs,
                                  boost::uint64_t offset, size_t len);

LargeFileAIO::LargeFileAIO(const std::string fn,
                           std::ios_base::openmode mode,
                           boost::uint64_t header_size,
                           boost::uint64_t /* length */) :
  LargeFileFD(fn, mode, header_size), writes_copied(true)
{
  this->open(mode);
}
LargeFileAIO::LargeFileAIO(const std::wstring fn,
                           std::ios_base::openmode mode,
                           boost::uint64_t header_size,
                           boost::uint64_t /* length */) :
  LargeFileFD(fn, mode, header_size), writes_copied(true)
{
  this->open(mode);
}

LargeFileAIO::~LargeFileAIO()
{
  this->close();
}

namespace {
  template<typename T> struct DeleteArray {
    void operator()(const T* t) const { delete[] t; }
  };
  // hack.  This only works here because we know we are always allocating
  // bytes, even though our interface requires us to shove them into a const
  // void*.
  template<> struct DeleteArray<const void> {
    void operator()(const void* t) const {
      delete[] static_cast<const char*>(t);
    }
  };
}

std::tr1::shared_ptr<const void> LargeFileAIO::rd(boost::uint64_t offset,
                                                  size_t len)
{
  struct aiocb *cb;

  // first, try to find this request among our list of outstanding requests.
  const boost::uint64_t real_offset = offset + this->header_size;
  cb = find_request(this->control, real_offset, len);
  if(NULL == cb) {
    if((cb = submit_new_request(real_offset, len)) == NULL) {
      DEBUG("could not submit new request."); // .. so just bail.
      return std::tr1::shared_ptr<const void>();
    }
  }
  const struct aiocb* const cblist[1] = { cb };
  {
    int susp=0;
    do {
      susp = aio_suspend(cblist, 1, NULL);
    } while(susp == -1 && errno==EINTR);
  }

  assert(aio_error(cb) == 0);
#ifndef NDEBUG
  ssize_t bytes = aio_return(cb);
  assert(bytes == static_cast<ssize_t>(len));
#else
  aio_return(cb);
#endif
  // both our control block and our data buffer are dynamically allocated.
  // Make sure they'll both get freed up; control block now, and the data will
  // be the return shared_ptr, so it's that ptr's responsibility to clean it
  // up.
  std::tr1::shared_ptr<const void> mem = this->control.find(cb)->second;
  delete cb;
  this->control.erase(cb);
  return mem;
}

/// notifies the object that we're going to need the following data soon.
/// Many implementations will prefetch this data when it knows this.
void LargeFileAIO::enqueue(boost::uint64_t offset, size_t len)
{
  if(len == 0) { return; }
  struct aiocb* cb;

  // hint at the FD level.  Not terribly important; the kernel will get the
  // read request in just a second, when we submit.  But it might be able to
  // read a page or two before we get to submitting the request -- especially
  // if we happen to get put to sleep between now and then.
  LargeFileFD::enqueue(offset, len);

  // do they already have such a request outstanding?
  const boost::uint64_t real_offset = offset + this->header_size;
  cb = find_request(this->control, real_offset, len);
  if(cb != NULL) {
    DEBUG("request already exists... ignoring it.");
    return;
  }

  submit_new_request(real_offset, len);
}

void LargeFileAIO::wr(const std::tr1::shared_ptr<const void>& data,
                      boost::uint64_t offset,
                      size_t len)
{
  if(len == 0) { return; }

  flush_writes(); // only allow one pending write..

  struct aiocb* cb = new struct aiocb;
  ::memset(cb, 0, sizeof(struct aiocb));

  cb->aio_fildes = this->fd;
  cb->aio_offset = offset + this->header_size;
  cb->aio_nbytes = len;

  std::tr1::shared_ptr<const void> saved_data;
  if(writes_copied) {
    // allocate a new buffer and hold on to that.
    int8_t* buf = new int8_t[len];
    ::memcpy(buf, data.get(), len);
    const void* bufv = static_cast<const void*>(buf);
    saved_data = std::tr1::shared_ptr<const void>(bufv,
                                                  DeleteArray<const void>());
  } else {
    saved_data = std::tr1::shared_ptr<const void>(data);
  }
  // cast away the const.  We know the AIO op won't modify the data anyway --
  // it's a write operation.
  cb->aio_buf = const_cast<void*>(saved_data.get());
  {
    struct sigevent sigev;
    ::memset(&sigev, 0, sizeof(struct sigevent));
    sigev.sigev_notify = SIGEV_NONE;
    cb->aio_sigevent = sigev;
  }
  cb->aio_lio_opcode = LIO_WRITE;

  if(aio_write(cb) != 0) {
    DEBUG("aio_write failed, errno=" << errno);
    switch(errno) {
      case EAGAIN:
        throw std::ios_base::failure("temporary lack of resources");
        break;
      case ENOSYS:
        throw std::ios_base::failure("AIO not implemented on this platform.");
        break;
      case EBADF:
        throw std::ios_base::failure("invalid file descriptor.");
        break;
      case EINVAL:
        throw std::ios_base::failure("offset or reqprio was invalid.");
        break;
    }
    return;
  }

  // make sure we hold on to the memory.
  this->control.insert(std::make_pair(cb, saved_data));
}

static void wait_on(struct aiocb* cb) {
  const struct aiocb* const cblist[1] = { cb };
  int rv = 0;
  do {
    rv = aio_suspend(cblist, 1, NULL);
  } while(rv == -1 && errno == EINTR);
  assert(rv == 0);
  rv = aio_error(cb);
  assert(rv != EINPROGRESS);
  assert(rv != ECANCELED);
  rv = aio_return(cb);
  assert(rv != EINVAL);
}

void LargeFileAIO::copy_writes(bool copy) { this->writes_copied = copy; }

void LargeFileAIO::close()
{
  if(!this->is_open()) { return; }

  // if there were pending reads... who cares.  But pending writes?  We need to
  // wait on those and make sure they finish.
  this->flush_writes();

  // okay.  anything left in there isn't important.  just cancel all of 'em.
  if(aio_cancel(this->fd, NULL) == EBADF) {
    throw std::out_of_range("bad file descriptor");
  }

  // all of those aiocb* were dynamically allocated.  free them up.
  for(Reqs::const_iterator i = this->control.begin();
      i != this->control.end(); ++i) {
    // _return on them first; the library might be waiting for us to do that
    // before it frees up internal resources.
#ifndef NDEBUG
    ssize_t rv = aio_return(i->first);
    assert(rv != EINVAL);
#else
    aio_return(i->first);
#endif
    delete i->first;
  }
  // we don't worry about the shared_ptr's -- they'll clean themselves up
  // automagically.
  this->control.clear();
  LargeFileFD::close();
}

struct aiocb* LargeFileAIO::submit_new_request(boost::uint64_t offset,
                                               size_t len)
{
  struct aiocb* cb = new struct aiocb;
  ::memset(cb, 0, sizeof(struct aiocb));

  cb->aio_fildes = this->fd;
  cb->aio_offset = offset;
  std::tr1::shared_ptr<void> data(new int8_t[len], DeleteArray<int8_t>());
  cb->aio_buf = data.get();
  cb->aio_nbytes = len;
  {
    struct sigevent sigev;
    ::memset(&sigev, 0, sizeof(struct sigevent));
    sigev.sigev_notify = SIGEV_NONE;
    cb->aio_sigevent = sigev;
  }
  cb->aio_lio_opcode = LIO_READ;

  if(aio_read(cb) == -1) {
    delete cb;
    switch(errno) {
      case EAGAIN:
        throw std::ios_base::failure("temporary lack of resources.");
        break;
      case ENOSYS:
        throw std::ios_base::failure("AIO not implemented on this platform");
        break;
      case EBADF:
        throw std::ios_base::failure("invalid file descriptor.");
        break;
      case EINVAL:
        throw std::ios_base::failure("offset or reqprio is invalid.");
        break;
    }
    return NULL;
  }
  this->control.insert(std::make_pair(cb, data));
  return cb;
}

/// searches for a request among a list of outstanding AIO ops.  The given
/// offset is intended to be exact (i.e. this won't apply header offsets).
static struct aiocb*
find_request(
  const LargeFileAIO::Reqs& reqs,
  boost::uint64_t offset,
  size_t len)
{
  for(LargeFileAIO::Reqs::const_iterator i = reqs.begin(); i != reqs.end(); ++i)
  {
    if(static_cast<boost::uint64_t>(i->first->aio_offset) == offset &&
       i->first->aio_nbytes == len) {
      return i->first;
    }
  }
  return NULL;
}

// flushes any pending writes by waiting on them.
void LargeFileAIO::flush_writes()
{
  Reqs::const_iterator i = this->control.begin();
  while(i != this->control.end()) {
    if(i->first->aio_lio_opcode == LIO_WRITE) {
      wait_on(i->first);
      delete i->first;
#ifdef DETECTED_OS_APPLE
      /// @todo FIXME apple's tr1 is broken again, at least on 10.5.  We no
      /// longer support 10.5 anyway, so test on 10.6.  It's probably still
      /// broken on 10.6; we should fix the define so it is a bit more
      /// specific, instead of just blacklisting apple.
      this->control.erase(i);
      ++i;
#else
      i = this->control.erase(i);
#endif
    } else {
      ++i;
    }
  }
}
<commit_msg>aio: improve debug messages when suspend fails.<commit_after>/*
   For more information, please see: http://software.sci.utah.edu

   The MIT License

   Copyright (c) 2011 Scientific Computing and Imaging Institute,
   University of Utah.

   Permission is hereby granted, free of charge, to any person obtaining a
   copy of this software and associated documentation files (the "Software"),
   to deal in the Software without restriction, including without limitation
   the rights to use, copy, modify, merge, publish, distribute, sublicense,
   and/or sell copies of the Software, and to permit persons to whom the
   Software is furnished to do so, subject to the following conditions:

   The above copyright notice and this permission notice shall be included
   in all copies or substantial portions of the Software.

   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
   OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
   THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
   LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
   FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
   DEALINGS IN THE SOFTWARE.
*/
#include "StdDefines.h"
#include <aio.h>
#include <assert.h>
#include <cstring>
#include <errno.h>
#ifndef NDEBUG
# include <iostream>
# define DEBUG(...) do { std::cerr << __VA_ARGS__ << "\n"; } while(0)
#else
# define DEBUG(...) do { /* nothing, debug msg removed. */ } while(0)
#endif
#include <stdexcept>
#include <vector>
#include "LargeFileAIO.h"

/// searches for a request among a list of outstanding AIO ops.  The given
/// offset is intended to be exact (i.e. this won't apply header offsets).
static struct aiocb* find_request(const LargeFileAIO::Reqs& reqs,
                                  boost::uint64_t offset, size_t len);

LargeFileAIO::LargeFileAIO(const std::string fn,
                           std::ios_base::openmode mode,
                           boost::uint64_t header_size,
                           boost::uint64_t /* length */) :
  LargeFileFD(fn, mode, header_size), writes_copied(true)
{
  this->open(mode);
}
LargeFileAIO::LargeFileAIO(const std::wstring fn,
                           std::ios_base::openmode mode,
                           boost::uint64_t header_size,
                           boost::uint64_t /* length */) :
  LargeFileFD(fn, mode, header_size), writes_copied(true)
{
  this->open(mode);
}

LargeFileAIO::~LargeFileAIO()
{
  this->close();
}

namespace {
  template<typename T> struct DeleteArray {
    void operator()(const T* t) const { delete[] t; }
  };
  // hack.  This only works here because we know we are always allocating
  // bytes, even though our interface requires us to shove them into a const
  // void*.
  template<> struct DeleteArray<const void> {
    void operator()(const void* t) const {
      delete[] static_cast<const char*>(t);
    }
  };
}

std::tr1::shared_ptr<const void> LargeFileAIO::rd(boost::uint64_t offset,
                                                  size_t len)
{
  struct aiocb *cb;

  // first, try to find this request among our list of outstanding requests.
  const boost::uint64_t real_offset = offset + this->header_size;
  cb = find_request(this->control, real_offset, len);
  if(NULL == cb) {
    if((cb = submit_new_request(real_offset, len)) == NULL) {
      DEBUG("could not submit new request."); // .. so just bail.
      return std::tr1::shared_ptr<const void>();
    }
  }
  const struct aiocb* const cblist[1] = { cb };
  {
    int susp=0;
    do {
      susp = aio_suspend(cblist, 1, NULL);
    } while(susp == -1 && errno==EINTR);
  }

#ifndef NDEBUG
  int e = aio_error(cb);
  if(e != 0) {
    DEBUG("aio incomplete! aio_error(" << cb << ") = " << e);
  }
  ssize_t bytes = aio_return(cb);
  assert(bytes == static_cast<ssize_t>(len));
#else
  aio_return(cb);
#endif
  // both our control block and our data buffer are dynamically allocated.
  // Make sure they'll both get freed up; control block now, and the data will
  // be the return shared_ptr, so it's that ptr's responsibility to clean it
  // up.
  std::tr1::shared_ptr<const void> mem = this->control.find(cb)->second;
  delete cb;
  this->control.erase(cb);
  return mem;
}

/// notifies the object that we're going to need the following data soon.
/// Many implementations will prefetch this data when it knows this.
void LargeFileAIO::enqueue(boost::uint64_t offset, size_t len)
{
  if(len == 0) { return; }
  struct aiocb* cb;

  // hint at the FD level.  Not terribly important; the kernel will get the
  // read request in just a second, when we submit.  But it might be able to
  // read a page or two before we get to submitting the request -- especially
  // if we happen to get put to sleep between now and then.
  LargeFileFD::enqueue(offset, len);

  // do they already have such a request outstanding?
  const boost::uint64_t real_offset = offset + this->header_size;
  cb = find_request(this->control, real_offset, len);
  if(cb != NULL) {
    DEBUG("request already exists... ignoring it.");
    return;
  }

  submit_new_request(real_offset, len);
}

void LargeFileAIO::wr(const std::tr1::shared_ptr<const void>& data,
                      boost::uint64_t offset,
                      size_t len)
{
  if(len == 0) { return; }

  flush_writes(); // only allow one pending write..

  struct aiocb* cb = new struct aiocb;
  ::memset(cb, 0, sizeof(struct aiocb));

  cb->aio_fildes = this->fd;
  cb->aio_offset = offset + this->header_size;
  cb->aio_nbytes = len;

  std::tr1::shared_ptr<const void> saved_data;
  if(writes_copied) {
    // allocate a new buffer and hold on to that.
    int8_t* buf = new int8_t[len];
    ::memcpy(buf, data.get(), len);
    const void* bufv = static_cast<const void*>(buf);
    saved_data = std::tr1::shared_ptr<const void>(bufv,
                                                  DeleteArray<const void>());
  } else {
    saved_data = std::tr1::shared_ptr<const void>(data);
  }
  // cast away the const.  We know the AIO op won't modify the data anyway --
  // it's a write operation.
  cb->aio_buf = const_cast<void*>(saved_data.get());
  {
    struct sigevent sigev;
    ::memset(&sigev, 0, sizeof(struct sigevent));
    sigev.sigev_notify = SIGEV_NONE;
    cb->aio_sigevent = sigev;
  }
  cb->aio_lio_opcode = LIO_WRITE;

  if(aio_write(cb) != 0) {
    DEBUG("aio_write failed, errno=" << errno);
    switch(errno) {
      case EAGAIN:
        throw std::ios_base::failure("temporary lack of resources");
        break;
      case ENOSYS:
        throw std::ios_base::failure("AIO not implemented on this platform.");
        break;
      case EBADF:
        throw std::ios_base::failure("invalid file descriptor.");
        break;
      case EINVAL:
        throw std::ios_base::failure("offset or reqprio was invalid.");
        break;
    }
    return;
  }

  // make sure we hold on to the memory.
  this->control.insert(std::make_pair(cb, saved_data));
}

static void wait_on(struct aiocb* cb) {
  const struct aiocb* const cblist[1] = { cb };
  int rv = 0;
  do {
    rv = aio_suspend(cblist, 1, NULL);
  } while(rv == -1 && errno == EINTR);
  assert(rv == 0);
  rv = aio_error(cb);
  assert(rv != EINPROGRESS);
  assert(rv != ECANCELED);
  rv = aio_return(cb);
  assert(rv != EINVAL);
}

void LargeFileAIO::copy_writes(bool copy) { this->writes_copied = copy; }

void LargeFileAIO::close()
{
  if(!this->is_open()) { return; }

  // if there were pending reads... who cares.  But pending writes?  We need to
  // wait on those and make sure they finish.
  this->flush_writes();

  // okay.  anything left in there isn't important.  just cancel all of 'em.
  if(aio_cancel(this->fd, NULL) == EBADF) {
    throw std::out_of_range("bad file descriptor");
  }

  // all of those aiocb* were dynamically allocated.  free them up.
  for(Reqs::const_iterator i = this->control.begin();
      i != this->control.end(); ++i) {
    // _return on them first; the library might be waiting for us to do that
    // before it frees up internal resources.
#ifndef NDEBUG
    ssize_t rv = aio_return(i->first);
    assert(rv != EINVAL);
#else
    aio_return(i->first);
#endif
    delete i->first;
  }
  // we don't worry about the shared_ptr's -- they'll clean themselves up
  // automagically.
  this->control.clear();
  LargeFileFD::close();
}

struct aiocb* LargeFileAIO::submit_new_request(boost::uint64_t offset,
                                               size_t len)
{
  struct aiocb* cb = new struct aiocb;
  ::memset(cb, 0, sizeof(struct aiocb));

  cb->aio_fildes = this->fd;
  cb->aio_offset = offset;
  std::tr1::shared_ptr<void> data(new int8_t[len], DeleteArray<int8_t>());
  cb->aio_buf = data.get();
  cb->aio_nbytes = len;
  {
    struct sigevent sigev;
    ::memset(&sigev, 0, sizeof(struct sigevent));
    sigev.sigev_notify = SIGEV_NONE;
    cb->aio_sigevent = sigev;
  }
  cb->aio_lio_opcode = LIO_READ;

  if(aio_read(cb) == -1) {
    delete cb;
    switch(errno) {
      case EAGAIN:
        throw std::ios_base::failure("temporary lack of resources.");
        break;
      case ENOSYS:
        throw std::ios_base::failure("AIO not implemented on this platform");
        break;
      case EBADF:
        throw std::ios_base::failure("invalid file descriptor.");
        break;
      case EINVAL:
        throw std::ios_base::failure("offset or reqprio is invalid.");
        break;
    }
    return NULL;
  }
  this->control.insert(std::make_pair(cb, data));
  return cb;
}

/// searches for a request among a list of outstanding AIO ops.  The given
/// offset is intended to be exact (i.e. this won't apply header offsets).
static struct aiocb*
find_request(
  const LargeFileAIO::Reqs& reqs,
  boost::uint64_t offset,
  size_t len)
{
  for(LargeFileAIO::Reqs::const_iterator i = reqs.begin(); i != reqs.end(); ++i)
  {
    if(static_cast<boost::uint64_t>(i->first->aio_offset) == offset &&
       i->first->aio_nbytes == len) {
      return i->first;
    }
  }
  return NULL;
}

// flushes any pending writes by waiting on them.
void LargeFileAIO::flush_writes()
{
  Reqs::const_iterator i = this->control.begin();
  while(i != this->control.end()) {
    if(i->first->aio_lio_opcode == LIO_WRITE) {
      wait_on(i->first);
      delete i->first;
#ifdef DETECTED_OS_APPLE
      /// @todo FIXME apple's tr1 is broken again, at least on 10.5.  We no
      /// longer support 10.5 anyway, so test on 10.6.  It's probably still
      /// broken on 10.6; we should fix the define so it is a bit more
      /// specific, instead of just blacklisting apple.
      this->control.erase(i);
      ++i;
#else
      i = this->control.erase(i);
#endif
    } else {
      ++i;
    }
  }
}
<|endoftext|>


<commit_before>#include <stdlib.h>
#include <cstdio>

#include "mesh.h"
#include "block.h"
#include "name.h"
#include "attr.h"
#include "util.h"

#ifdef WIN32
#include "awdw32.h"
#else
#include <unistd.h>
#endif

AWDSubMesh::AWDSubMesh()
{
    this->first_stream = NULL;
    this->last_stream = NULL;
    this->next = NULL;
}

AWDSubMesh::~AWDSubMesh()
{
    AWDDataStream *cur;

    cur = this->first_stream;
    while (cur) {
        AWDDataStream *next = cur->next;
        cur->next = NULL;
        delete cur;
        cur = next;
    }

    this->first_stream = NULL;
    this->last_stream = NULL;
}

void
AWDSubMesh::add_stream(AWD_mesh_str_type type, AWD_str_ptr data, awd_uint32 num_elements)
{
    AWDMeshDataStream *str;

    str = new AWDMeshDataStream((awd_uint8)type, data, num_elements);

    if (this->first_stream == NULL) {
        this->first_stream = str;
    }
    else {
        this->last_stream->next = str;
    }

    this->last_stream = str;
    this->last_stream->next = NULL;
}

AWDMeshData::AWDMeshData(const char *name, awd_uint16 name_len) :
    AWDBlock(MESH_DATA),
    AWDNamedElement(name, name_len),
    AWDAttrElement()
{
    this->first_sub = NULL;
    this->last_sub = NULL;
    this->bind_mtx = NULL;
    this->num_subs = 0;
}

AWDMeshData::~AWDMeshData()
{
    AWDSubMesh *cur;

    cur = this->first_sub;
    while (cur) {
        AWDSubMesh *next = cur->next;
        cur->next = NULL;
        delete cur;
        cur = next;
    }

    if (this->bind_mtx) {
        free(this->bind_mtx);
        this->bind_mtx = NULL;
    }

    this->first_sub = NULL;
    this->last_sub = NULL;
}

void
AWDMeshData::add_sub_mesh(AWDSubMesh *sub)
{
    if (this->first_sub == NULL) {
        this->first_sub = sub;
    }
    else {
        this->last_sub->next = sub;
    }

    this->num_subs++;
    this->last_sub = sub;
}

int
AWDMeshData::get_num_subs()
{
    return this->num_subs;
}

AWDSubMesh *
AWDMeshData::get_sub_at(int idx)
{
    if (idx < this->num_subs) {
        int cur_idx;
        AWDSubMesh *cur;

        cur_idx = 0;
        cur = this->first_sub;
        while (cur) {
            if (cur_idx == idx)
                return cur;

            cur_idx++;
            cur = cur->next;
        }
    }

    return NULL;
}

awd_float64 *
AWDMeshData::get_bind_mtx()
{
    return this->bind_mtx;
}

void
AWDMeshData::set_bind_mtx(awd_float64 *bind_mtx)
{
    this->bind_mtx = bind_mtx;
}

awd_uint32
AWDMeshData::calc_body_length(bool wide_geom, bool wide_mtx)
{
    AWDSubMesh *sub;
    awd_uint32 mesh_len;

    // Calculate length of entire mesh
    // data (not block header)
    mesh_len = sizeof(awd_uint16); // Num subs
    mesh_len += sizeof(awd_uint16) + this->get_name_length();
    mesh_len += this->calc_attr_length(true,true, wide_geom, wide_mtx);
    sub = this->first_sub;
    while (sub) {
        AWDDataStream *str;

        // add size of sub-mesh length
        mesh_len += 4;

        str = sub->first_stream;
        while (str) {
            mesh_len += 5 + str->get_length(wide_geom);

            str = str->next;
        }

        sub = sub->next;
    }

    return mesh_len;
}

void
AWDMeshData::prepare_write()
{
    if (this->bind_mtx) {
        AWD_attr_val_ptr bind_val;

        bind_val.f64 = this->bind_mtx;
        this->properties->set(PROP_MD_BIND_MTX, bind_val, 16*sizeof(awd_float64), AWD_ATTR_MTX4);
    }
}

void
AWDMeshData::write_body(int fd, bool wide_geom, bool wide_mtx)
{
    awd_uint16 num_subs_be;
    AWDSubMesh *sub;

    // Write name and sub count
    num_subs_be = UI16(this->num_subs);
    awdutil_write_varstr(fd, this->get_name(), this->get_name_length());
    write(fd, &num_subs_be, sizeof(awd_uint16));

    // Write list of optional properties
    this->properties->write_attributes(fd, wide_geom, wide_mtx);

    // Write all sub-meshes
    sub = this->first_sub;
    while (sub) {
        AWDDataStream *str;
        awd_uint32 sub_len;

        sub_len = 0;
        str = sub->first_stream;
        while (str) {
            sub_len += (str->get_length(wide_geom) + 5);

            str = str->next;
        }

        // Verify byte-order
        sub_len = UI32(sub_len);

        // Write sub-mesh header
        write(fd, &sub_len, sizeof(awd_uint32));

        str = sub->first_stream;
        while(str) {
            str->write_stream(fd, wide_geom);

            str = str->next;
        }

        sub = sub->next;
    }

    // Write list of user attributes
    this->user_attributes->write_attributes(fd, wide_geom, wide_mtx);
}

AWDMeshInst::AWDMeshInst(const char *name, awd_uint16 name_len, AWDMeshData *data) :
    AWDSceneBlock(MESH_INSTANCE, name, name_len, NULL)
{
    this->set_data(data);
    this->materials = new AWDBlockList();
}

AWDMeshInst::AWDMeshInst(const char *name, awd_uint16 name_len, AWDMeshData *data, awd_float64 *mtx) :
    AWDSceneBlock(MESH_INSTANCE, name, name_len, mtx)
{
    this->set_data(data);
    this->materials = new AWDBlockList();
}

AWDMeshInst::~AWDMeshInst()
{
}

void
AWDMeshInst::add_material(AWDSimpleMaterial *material)
{
    this->materials->force_append(material);
}

AWDMeshData *
AWDMeshInst::get_data()
{
    return this->data;
}

void
AWDMeshInst::set_data(AWDMeshData *data)
{
    this->data = data;
}

awd_uint32
AWDMeshInst::calc_body_length(bool wide_geom, bool wide_mtx)
{
    return 136 + sizeof(awd_uint16) + (this->materials->get_num_blocks() * sizeof(awd_baddr))
        + sizeof(awd_uint16) + this->get_name_length() + this->calc_attr_length(true,true, wide_geom,wide_mtx);
}

void
AWDMeshInst::write_body(int fd, bool wide_geom, bool wide_mtx)
{
    AWDBlock *block;
    AWDBlockIterator *it;
    awd_baddr data_addr;
    awd_uint16 num_materials;

    this->write_scene_common(fd, wide_mtx);

    // Write mesh data address
    data_addr = UI32(this->data->get_addr());
    write(fd, &data_addr, sizeof(awd_uint32));

    // Write materials list. First write material count, and then
    // iterate over materials block list and write all addresses
    printf("material count: %d\n", this->materials->get_num_blocks());
    num_materials = UI16((awd_uint16)this->materials->get_num_blocks());
    write(fd, &num_materials, sizeof(awd_uint16));
    it = new AWDBlockIterator(this->materials);
    while ((block = it->next()) != NULL) {
        awd_baddr addr = UI32(block->get_addr());
        write(fd, &addr, sizeof(awd_baddr));
    }

    this->properties->write_attributes(fd, wide_geom, wide_mtx);
    this->user_attributes->write_attributes(fd, wide_geom, wide_mtx);
}
<commit_msg>Fixed bug in mesh instance (was ignoring wide_mtx in calc_body_size())<commit_after>#include <stdlib.h>
#include <cstdio>

#include "mesh.h"
#include "block.h"
#include "name.h"
#include "attr.h"
#include "util.h"

#ifdef WIN32
#include "awdw32.h"
#else
#include <unistd.h>
#endif

AWDSubMesh::AWDSubMesh()
{
    this->first_stream = NULL;
    this->last_stream = NULL;
    this->next = NULL;
}

AWDSubMesh::~AWDSubMesh()
{
    AWDDataStream *cur;

    cur = this->first_stream;
    while (cur) {
        AWDDataStream *next = cur->next;
        cur->next = NULL;
        delete cur;
        cur = next;
    }

    this->first_stream = NULL;
    this->last_stream = NULL;
}

void
AWDSubMesh::add_stream(AWD_mesh_str_type type, AWD_str_ptr data, awd_uint32 num_elements)
{
    AWDMeshDataStream *str;

    str = new AWDMeshDataStream((awd_uint8)type, data, num_elements);

    if (this->first_stream == NULL) {
        this->first_stream = str;
    }
    else {
        this->last_stream->next = str;
    }

    this->last_stream = str;
    this->last_stream->next = NULL;
}

AWDMeshData::AWDMeshData(const char *name, awd_uint16 name_len) :
    AWDBlock(MESH_DATA),
    AWDNamedElement(name, name_len),
    AWDAttrElement()
{
    this->first_sub = NULL;
    this->last_sub = NULL;
    this->bind_mtx = NULL;
    this->num_subs = 0;
}

AWDMeshData::~AWDMeshData()
{
    AWDSubMesh *cur;

    cur = this->first_sub;
    while (cur) {
        AWDSubMesh *next = cur->next;
        cur->next = NULL;
        delete cur;
        cur = next;
    }

    if (this->bind_mtx) {
        free(this->bind_mtx);
        this->bind_mtx = NULL;
    }

    this->first_sub = NULL;
    this->last_sub = NULL;
}

void
AWDMeshData::add_sub_mesh(AWDSubMesh *sub)
{
    if (this->first_sub == NULL) {
        this->first_sub = sub;
    }
    else {
        this->last_sub->next = sub;
    }

    this->num_subs++;
    this->last_sub = sub;
}

int
AWDMeshData::get_num_subs()
{
    return this->num_subs;
}

AWDSubMesh *
AWDMeshData::get_sub_at(int idx)
{
    if (idx < this->num_subs) {
        int cur_idx;
        AWDSubMesh *cur;

        cur_idx = 0;
        cur = this->first_sub;
        while (cur) {
            if (cur_idx == idx)
                return cur;

            cur_idx++;
            cur = cur->next;
        }
    }

    return NULL;
}

awd_float64 *
AWDMeshData::get_bind_mtx()
{
    return this->bind_mtx;
}

void
AWDMeshData::set_bind_mtx(awd_float64 *bind_mtx)
{
    this->bind_mtx = bind_mtx;
}

awd_uint32
AWDMeshData::calc_body_length(bool wide_geom, bool wide_mtx)
{
    AWDSubMesh *sub;
    awd_uint32 mesh_len;

    // Calculate length of entire mesh
    // data (not block header)
    mesh_len = sizeof(awd_uint16); // Num subs
    mesh_len += sizeof(awd_uint16) + this->get_name_length();
    mesh_len += this->calc_attr_length(true,true, wide_geom, wide_mtx);
    sub = this->first_sub;
    while (sub) {
        AWDDataStream *str;

        // add size of sub-mesh length
        mesh_len += 4;

        str = sub->first_stream;
        while (str) {
            mesh_len += 5 + str->get_length(wide_geom);

            str = str->next;
        }

        sub = sub->next;
    }

    return mesh_len;
}

void
AWDMeshData::prepare_write()
{
    if (this->bind_mtx) {
        AWD_attr_val_ptr bind_val;

        bind_val.f64 = this->bind_mtx;
        this->properties->set(PROP_MD_BIND_MTX, bind_val, 16*sizeof(awd_float64), AWD_ATTR_MTX4);
    }
}

void
AWDMeshData::write_body(int fd, bool wide_geom, bool wide_mtx)
{
    awd_uint16 num_subs_be;
    AWDSubMesh *sub;

    // Write name and sub count
    num_subs_be = UI16(this->num_subs);
    awdutil_write_varstr(fd, this->get_name(), this->get_name_length());
    write(fd, &num_subs_be, sizeof(awd_uint16));

    // Write list of optional properties
    this->properties->write_attributes(fd, wide_geom, wide_mtx);

    // Write all sub-meshes
    sub = this->first_sub;
    while (sub) {
        AWDDataStream *str;
        awd_uint32 sub_len;

        sub_len = 0;
        str = sub->first_stream;
        while (str) {
            sub_len += (str->get_length(wide_geom) + 5);

            str = str->next;
        }

        // Verify byte-order
        sub_len = UI32(sub_len);

        // Write sub-mesh header
        write(fd, &sub_len, sizeof(awd_uint32));

        str = sub->first_stream;
        while(str) {
            str->write_stream(fd, wide_geom);

            str = str->next;
        }

        sub = sub->next;
    }

    // Write list of user attributes
    this->user_attributes->write_attributes(fd, wide_geom, wide_mtx);
}

AWDMeshInst::AWDMeshInst(const char *name, awd_uint16 name_len, AWDMeshData *data) :
    AWDSceneBlock(MESH_INSTANCE, name, name_len, NULL)
{
    this->set_data(data);
    this->materials = new AWDBlockList();
}

AWDMeshInst::AWDMeshInst(const char *name, awd_uint16 name_len, AWDMeshData *data, awd_float64 *mtx) :
    AWDSceneBlock(MESH_INSTANCE, name, name_len, mtx)
{
    this->set_data(data);
    this->materials = new AWDBlockList();
}

AWDMeshInst::~AWDMeshInst()
{
}

void
AWDMeshInst::add_material(AWDSimpleMaterial *material)
{
    this->materials->force_append(material);
}

AWDMeshData *
AWDMeshInst::get_data()
{
    return this->data;
}

void
AWDMeshInst::set_data(AWDMeshData *data)
{
    this->data = data;
}

awd_uint32
AWDMeshInst::calc_body_length(bool wide_geom, bool wide_mtx)
{
    return 8 + MTX4_SIZE(wide_mtx) + sizeof(awd_uint16) + (this->materials->get_num_blocks() * sizeof(awd_baddr))
        + sizeof(awd_uint16) + this->get_name_length() + this->calc_attr_length(true,true, wide_geom,wide_mtx);
}

void
AWDMeshInst::write_body(int fd, bool wide_geom, bool wide_mtx)
{
    AWDBlock *block;
    AWDBlockIterator *it;
    awd_baddr data_addr;
    awd_uint16 num_materials;

    this->write_scene_common(fd, wide_mtx);

    // Write mesh data address
    data_addr = UI32(this->data->get_addr());
    write(fd, &data_addr, sizeof(awd_uint32));

    // Write materials list. First write material count, and then
    // iterate over materials block list and write all addresses
    printf("material count: %d\n", this->materials->get_num_blocks());
    num_materials = UI16((awd_uint16)this->materials->get_num_blocks());
    write(fd, &num_materials, sizeof(awd_uint16));
    it = new AWDBlockIterator(this->materials);
    while ((block = it->next()) != NULL) {
        awd_baddr addr = UI32(block->get_addr());
        write(fd, &addr, sizeof(awd_baddr));
    }

    this->properties->write_attributes(fd, wide_geom, wide_mtx);
    this->user_attributes->write_attributes(fd, wide_geom, wide_mtx);
}
<|endoftext|>


<commit_before>#include "flare_text_editor_widget.hpp"

#include <FL/fl_ask.H>
#include <FL/Fl.H>

namespace Flare {

    void Text_Editor_Widget::BufferCallback(int pos, int add, int del, int styled, const char* deleted_text){

        // I do not know if we can really trust this
        // to be true, but we rely on it for now.
#ifndef NDEBUG
        if((del>0) && (add>0)) fl_alert("Whoops!\nWe both added and deleted? What?");
        if((pos<0)) fl_alert("Whoops!\nPosition is negative?");
        if((add<0)) fl_alert("Whoops!\nNumber of added chars is negative?");
        if((del<0)) fl_alert("Whoops!\nNumber of deleted chars is negative?");
#endif
        if(add==0 && del==0){
           // style_buffer->unselect();
            return;
        }

        if(canary>0u){ return; }
        canary++;

        if((!future.empty()) || history.empty()){
            future.clear();

            struct diff that = {
                ((add>0)  ?
                    (buffer()->text_range(pos, pos+add)) :
                    (strdup(deleted_text))),
                pos,
                add,
                del
            };

            history.push_back(that);
        }
        else{
            struct diff & top = history.back();
            if(add>0 && top.add>0 && top.pos+top.add==pos){

                char *t = buffer()->text_range(pos, pos+add);
                top.text = (char *)realloc(top.text,top.add+add+1);
                memcpy(top.text+top.add, t, add+1);
                top.add+=add;
                free(t);
            }
            else if(del>0 && top.del>0 && top.pos==pos-del){
                top.text = (char *)realloc(top.text, top.del+del+1);
                memcpy(top.text+top.del, deleted_text, del+1);
                top.del+=del;
            }
            else{
                struct diff that = {
                    ((add>0)  ?
                        (buffer()->text_range(pos, pos+add)) :
                        (strdup(deleted_text))),
                    pos,
                    add,
                    del
                };
                history.push_back(that);
            }
        }
        canary--;
    }

    void Text_Editor_Widget::undo(){
        if(canary>0u) return;
        if(history.empty()) return;
        canary++;

        struct diff op = history.pop();
        if(op.del>0){
            buffer()->insert(op.pos, op.text);
        }
        else{
            buffer()->remove(op.pos, op.pos+op.add);
        }

        future.push_back(op);

        canary--;
    }

    void Text_Editor_Widget::redo(){
        if(canary>0u) return;
        if(future.empty()) return;
        canary++;

        struct diff op = future.pop();
        if(op.add>0){
            buffer()->insert(op.pos, op.text);
        }
        else{
            buffer()->remove(op.pos, op.pos+op.del);
        }

        history.push_back(op);

        canary--;
    }

    void Text_Editor_Widget::removeTabChars(int index){
        const int start_of_line = line_start(index);
        // If the start of the line is the same as the tab character, remove it.
        bool starts_with_tab = true;
        for(size_t i = 0; i < tab.length(); i++){
            if(tab[i] != mBuffer->char_at(start_of_line + i)){
                starts_with_tab = false;
                break;
            }
        }
        if(starts_with_tab){
            mBuffer->remove(start_of_line, start_of_line + tab.length());
        }
        // Otherwise, if the tab char is an actual tab, as many spaces as possible
        // up to 4 from the start of the line.
        else if(tab.length() == 1 && tab[0] == '\t'){
            int num_spaces = 0;
            for(size_t i = 0; i < 4; i++){
                if(mBuffer->char_at(start_of_line + i) == ' '){
                    num_spaces++;
                }
                else
                    break;
            }
            if(num_spaces)
                mBuffer->remove(start_of_line, start_of_line + num_spaces);
        }
        // Finally, if none of that worked, if the line starts with a space or a tab, remove it.
        else{
            const char c = mBuffer->char_at(start_of_line);
            if(c == ' ' || c == '\t'){
                mBuffer->remove(start_of_line, 1);
            }
        }
    }

    int Text_Editor_Widget::handle(int e){
        if(!has_set_font){
            textfont(FL_COURIER);
            has_set_font = true;
        }
        if(e==FL_KEYDOWN){
            int event_len = Fl::event_length();
            const char *event_str = Fl::event_text();
            const bool shift_is_pressed = Fl::event_state() & FL_SHIFT;

            if(event_len == 0 && Fl::get_key(FL_Tab)){
                event_str = "\t";
                event_len = 1;
            }

            printf("Event Length: %i  \tShift: %i\n", event_len, shift_is_pressed);
            if(event_len!=1) return Fl_Text_Editor::handle(e);
            const char first_char = *event_str;
            if(first_char=='\t'){
                const Fl_Text_Selection * const selection = mBuffer->primary_selection();
                if(!selection->selected()){
                    if(shift_is_pressed){
                        removeTabChars(insert_position());
                    }
                    else{
                        // If there are no lines selected and shift isn't pressed, just insert
                        // the defined tab character(s).
                        insert(tab.c_str());
                    }
                }
                else{
                    int line_start_pos = line_start(selection->start());

                    while(line_start_pos<selection->end()){

                        if(shift_is_pressed)
                            removeTabChars(line_start_pos);
                        else
                            mBuffer->insert(line_start_pos, tab.c_str());

                        line_start_pos = line_end(line_start_pos, true);

                        while((mBuffer->char_at(line_start_pos)=='\n') || (mBuffer->char_at(line_start_pos+1)=='\n')){
                            line_start_pos++;
                        }

                    }
                }
                return 1;
            }
            else if(first_char=='\n' || first_char=='\r'){
                std::string whitespace;
                char ucs_buffer[5];

                if((insert_position()>=1) && (line_start(insert_position())!=insert_position())){

                    int start = line_start(insert_position()-1);

                    // Advance until we hit a newline, we hit the current insert position, or we are no longer on a whitespace character.
                    // NOTE! `fl_nonspacing' is backwards--the same as `isspace'. So why is it NON-spacing? I have no idea.
                    while((mBuffer->byte_at(start)!='\n') && (mBuffer->byte_at(start)!='\r') &&
                        (start < insert_position()) && (fl_nonspacing(mBuffer->char_at(start)))){

                        if(mBuffer->char_at(start)<0x80){
                            whitespace += mBuffer->byte_at(start);
                            start++;
                        }
                        else{ // TODO: Test this block.
                            int len = fl_utf8encode(mBuffer->char_at(start), ucs_buffer);
                            ucs_buffer[len] = '\0';
                            whitespace += ucs_buffer;
                            start+=len;
                        }
                    }
                }
                insert("\n");

                if(!whitespace.empty()) insert(whitespace.c_str());

                if(mBuffer->selected()){
                    mBuffer->remove_selection();
                }

                return 1;
            }
        }
        return Fl_Text_Editor::handle(e);
    }

}
<commit_msg>Remove debug printing<commit_after>#include "flare_text_editor_widget.hpp"

#include <FL/fl_ask.H>
#include <FL/Fl.H>

namespace Flare {

    void Text_Editor_Widget::BufferCallback(int pos, int add, int del, int styled, const char* deleted_text){

        // I do not know if we can really trust this
        // to be true, but we rely on it for now.
#ifndef NDEBUG
        if((del>0) && (add>0)) fl_alert("Whoops!\nWe both added and deleted? What?");
        if((pos<0)) fl_alert("Whoops!\nPosition is negative?");
        if((add<0)) fl_alert("Whoops!\nNumber of added chars is negative?");
        if((del<0)) fl_alert("Whoops!\nNumber of deleted chars is negative?");
#endif
        if(add==0 && del==0){
           // style_buffer->unselect();
            return;
        }

        if(canary>0u){ return; }
        canary++;

        if((!future.empty()) || history.empty()){
            future.clear();

            struct diff that = {
                ((add>0)  ?
                    (buffer()->text_range(pos, pos+add)) :
                    (strdup(deleted_text))),
                pos,
                add,
                del
            };

            history.push_back(that);
        }
        else{
            struct diff & top = history.back();
            if(add>0 && top.add>0 && top.pos+top.add==pos){

                char *t = buffer()->text_range(pos, pos+add);
                top.text = (char *)realloc(top.text,top.add+add+1);
                memcpy(top.text+top.add, t, add+1);
                top.add+=add;
                free(t);
            }
            else if(del>0 && top.del>0 && top.pos==pos-del){
                top.text = (char *)realloc(top.text, top.del+del+1);
                memcpy(top.text+top.del, deleted_text, del+1);
                top.del+=del;
            }
            else{
                struct diff that = {
                    ((add>0)  ?
                        (buffer()->text_range(pos, pos+add)) :
                        (strdup(deleted_text))),
                    pos,
                    add,
                    del
                };
                history.push_back(that);
            }
        }
        canary--;
    }

    void Text_Editor_Widget::undo(){
        if(canary>0u) return;
        if(history.empty()) return;
        canary++;

        struct diff op = history.pop();
        if(op.del>0){
            buffer()->insert(op.pos, op.text);
        }
        else{
            buffer()->remove(op.pos, op.pos+op.add);
        }

        future.push_back(op);

        canary--;
    }

    void Text_Editor_Widget::redo(){
        if(canary>0u) return;
        if(future.empty()) return;
        canary++;

        struct diff op = future.pop();
        if(op.add>0){
            buffer()->insert(op.pos, op.text);
        }
        else{
            buffer()->remove(op.pos, op.pos+op.del);
        }

        history.push_back(op);

        canary--;
    }

    void Text_Editor_Widget::removeTabChars(int index){
        const int start_of_line = line_start(index);
        // If the start of the line is the same as the tab character, remove it.
        bool starts_with_tab = true;
        for(size_t i = 0; i < tab.length(); i++){
            if(tab[i] != mBuffer->char_at(start_of_line + i)){
                starts_with_tab = false;
                break;
            }
        }
        if(starts_with_tab){
            mBuffer->remove(start_of_line, start_of_line + tab.length());
        }
        // Otherwise, if the tab char is an actual tab, as many spaces as possible
        // up to 4 from the start of the line.
        else if(tab.length() == 1 && tab[0] == '\t'){
            int num_spaces = 0;
            for(size_t i = 0; i < 4; i++){
                if(mBuffer->char_at(start_of_line + i) == ' '){
                    num_spaces++;
                }
                else
                    break;
            }
            if(num_spaces)
                mBuffer->remove(start_of_line, start_of_line + num_spaces);
        }
        // Finally, if none of that worked, if the line starts with a space or a tab, remove it.
        else{
            const char c = mBuffer->char_at(start_of_line);
            if(c == ' ' || c == '\t'){
                mBuffer->remove(start_of_line, 1);
            }
        }
    }

    int Text_Editor_Widget::handle(int e){
        if(!has_set_font){
            textfont(FL_COURIER);
            has_set_font = true;
        }
        if(e==FL_KEYDOWN){
            int event_len = Fl::event_length();
            const char *event_str = Fl::event_text();
            const bool shift_is_pressed = Fl::event_state() & FL_SHIFT;

            if(event_len == 0 && Fl::get_key(FL_Tab)){
                event_str = "\t";
                event_len = 1;
            }
            if(event_len!=1) return Fl_Text_Editor::handle(e);
            const char first_char = *event_str;
            if(first_char=='\t'){
                const Fl_Text_Selection * const selection = mBuffer->primary_selection();
                if(!selection->selected()){
                    if(shift_is_pressed){
                        removeTabChars(insert_position());
                    }
                    else{
                        // If there are no lines selected and shift isn't pressed, just insert
                        // the defined tab character(s).
                        insert(tab.c_str());
                    }
                }
                else{
                    int line_start_pos = line_start(selection->start());

                    while(line_start_pos<selection->end()){

                        if(shift_is_pressed)
                            removeTabChars(line_start_pos);
                        else
                            mBuffer->insert(line_start_pos, tab.c_str());

                        line_start_pos = line_end(line_start_pos, true);

                        while((mBuffer->char_at(line_start_pos)=='\n') || (mBuffer->char_at(line_start_pos+1)=='\n')){
                            line_start_pos++;
                        }

                    }
                }
                return 1;
            }
            else if(first_char=='\n' || first_char=='\r'){
                std::string whitespace;
                char ucs_buffer[5];

                if((insert_position()>=1) && (line_start(insert_position())!=insert_position())){

                    int start = line_start(insert_position()-1);

                    // Advance until we hit a newline, we hit the current insert position, or we are no longer on a whitespace character.
                    // NOTE! `fl_nonspacing' is backwards--the same as `isspace'. So why is it NON-spacing? I have no idea.
                    while((mBuffer->byte_at(start)!='\n') && (mBuffer->byte_at(start)!='\r') &&
                        (start < insert_position()) && (fl_nonspacing(mBuffer->char_at(start)))){

                        if(mBuffer->char_at(start)<0x80){
                            whitespace += mBuffer->byte_at(start);
                            start++;
                        }
                        else{ // TODO: Test this block.
                            int len = fl_utf8encode(mBuffer->char_at(start), ucs_buffer);
                            ucs_buffer[len] = '\0';
                            whitespace += ucs_buffer;
                            start+=len;
                        }
                    }
                }
                insert("\n");

                if(!whitespace.empty()) insert(whitespace.c_str());

                if(mBuffer->selected()){
                    mBuffer->remove_selection();
                }

                return 1;
            }
        }
        return Fl_Text_Editor::handle(e);
    }

}
<|endoftext|>


<commit_before>// Copyright 2015-2019 Elviss Strazdins. All rights reserved.

#include "core/Setup.h"

#if OUZEL_COMPILE_DIRECT3D11

#include "D3D11DepthStencilState.hpp"
#include "D3D11RenderDevice.hpp"

namespace ouzel
{
    namespace graphics
    {
        namespace d3d11
        {
            static D3D11_COMPARISON_FUNC getCompareFunction(CompareFunction compareFunction)
            {
                switch (compareFunction)
                {
                    case CompareFunction::NeverPass: return D3D11_COMPARISON_NEVER;
                    case CompareFunction::PassIfLess: return D3D11_COMPARISON_LESS;
                    case CompareFunction::PassIfEqual: return D3D11_COMPARISON_EQUAL;
                    case CompareFunction::LessEqual: return D3D11_COMPARISON_LESS_EQUAL;
                    case CompareFunction::PassIfPassIfGreater: return D3D11_COMPARISON_GREATER;
                    case CompareFunction::PassIfNotEqual: return D3D11_COMPARISON_NOT_EQUAL;
                    case CompareFunction::PassIfGreaterEqual: return D3D11_COMPARISON_GREATER_EQUAL;
                    case CompareFunction::AlwaysPass: return D3D11_COMPARISON_ALWAYS;
                    default: return D3D11_COMPARISON_NEVER;
                }
            }

            static D3D11_STENCIL_OP getStencilOperation(StencilOperation stencilOperation)
            {
                switch (stencilOperation)
                {
                    case StencilOperation::Keep: return D3D11_STENCIL_OP_KEEP;
                    case StencilOperation::Zero: return D3D11_STENCIL_OP_ZERO;
                    case StencilOperation::Replace: return D3D11_STENCIL_OP_REPLACE;
                    case StencilOperation::IncrementClamp: return D3D11_STENCIL_OP_INCR_SAT;
                    case StencilOperation::DecrementClamp: return D3D11_STENCIL_OP_DECR_SAT;
                    case StencilOperation::Invert: return D3D11_STENCIL_OP_INVERT;
                    case StencilOperation::IncrementWrap: return D3D11_STENCIL_OP_INCR;
                    case StencilOperation::DecrementWrap: return D3D11_STENCIL_OP_DECR;
                    default: return D3D11_STENCIL_OP_KEEP;
                }
            }

            DepthStencilState::DepthStencilState(RenderDevice& initRenderDevice,
                                                 bool initDepthTest,
                                                 bool initDepthWrite,
                                                 CompareFunction initCompareFunction,
                                                 bool initStencilEnabled,
                                                 uint32_t initStencilReadMask,
                                                 uint32_t initStencilWriteMask,
                                                 StencilOperation initFrontFaceStencilFailureOperation,
                                                 StencilOperation initFrontFaceStencilDepthFailureOperation,
                                                 StencilOperation initFrontFaceStencilPassOperation,
                                                 CompareFunction initFrontFaceStencilCompareFunction,
                                                 StencilOperation initBackFaceStencilFailureOperation,
                                                 StencilOperation initBackFaceStencilDepthFailureOperation,
                                                 StencilOperation initBackFaceStencilPassOperation,
                                                 CompareFunction initBackFaceStencilCompareFunction):
                RenderResource(initRenderDevice)
            {
                D3D11_DEPTH_STENCIL_DESC depthStencilStateDesc;
                depthStencilStateDesc.DepthEnable = initDepthTest ? TRUE : FALSE;
                depthStencilStateDesc.DepthWriteMask = initDepthWrite ? D3D11_DEPTH_WRITE_MASK_ALL : D3D11_DEPTH_WRITE_MASK_ZERO;
                depthStencilStateDesc.DepthFunc = getCompareFunction(initCompareFunction);
                depthStencilStateDesc.StencilEnable = initStencilEnabled ? TRUE : FALSE;
                depthStencilStateDesc.StencilReadMask = static_cast<UINT8>(initStencilReadMask);
                depthStencilStateDesc.StencilWriteMask = static_cast<UINT8>(initStencilWriteMask);
                depthStencilStateDesc.FrontFace.StencilFailOp = getStencilOperation(initFrontFaceStencilFailureOperation);
                depthStencilStateDesc.FrontFace.StencilDepthFailOp = getStencilOperation(initFrontFaceStencilDepthFailureOperation);
                depthStencilStateDesc.FrontFace.StencilPassOp = getStencilOperation(initFrontFaceStencilPassOperation);
                depthStencilStateDesc.FrontFace.StencilFunc = getCompareFunction(initFrontFaceStencilCompareFunction);
                depthStencilStateDesc.BackFace.StencilFailOp = getStencilOperation(initBackFaceStencilFailureOperation);
                depthStencilStateDesc.BackFace.StencilDepthFailOp = getStencilOperation(initBackFaceStencilDepthFailureOperation);
                depthStencilStateDesc.BackFace.StencilPassOp = getStencilOperation(initBackFaceStencilPassOperation);
                depthStencilStateDesc.BackFace.StencilFunc = getCompareFunction(initBackFaceStencilCompareFunction);

                HRESULT hr;
                if (FAILED(hr = renderDevice.getDevice()->CreateDepthStencilState(&depthStencilStateDesc, &depthStencilState)))
                    throw std::system_error(hr, errorCategory, "Failed to create Direct3D 11 depth stencil state");
            }

            DepthStencilState::~DepthStencilState()
            {
                if (depthStencilState) depthStencilState->Release();
            }
        } // namespace d3d11
    } // namespace graphics
} // namespace ouzel

#endif
<commit_msg>Fix the D3D11 renderer<commit_after>// Copyright 2015-2019 Elviss Strazdins. All rights reserved.

#include "core/Setup.h"

#if OUZEL_COMPILE_DIRECT3D11

#include "D3D11DepthStencilState.hpp"
#include "D3D11RenderDevice.hpp"

namespace ouzel
{
    namespace graphics
    {
        namespace d3d11
        {
            static D3D11_COMPARISON_FUNC getCompareFunction(CompareFunction compareFunction)
            {
                switch (compareFunction)
                {
                    case CompareFunction::NeverPass: return D3D11_COMPARISON_NEVER;
                    case CompareFunction::PassIfLess: return D3D11_COMPARISON_LESS;
                    case CompareFunction::PassIfEqual: return D3D11_COMPARISON_EQUAL;
                    case CompareFunction::PassIfLessEqual: return D3D11_COMPARISON_LESS_EQUAL;
                    case CompareFunction::PassIfPassIfGreater: return D3D11_COMPARISON_GREATER;
                    case CompareFunction::PassIfNotEqual: return D3D11_COMPARISON_NOT_EQUAL;
                    case CompareFunction::PassIfGreaterEqual: return D3D11_COMPARISON_GREATER_EQUAL;
                    case CompareFunction::AlwaysPass: return D3D11_COMPARISON_ALWAYS;
                    default: return D3D11_COMPARISON_NEVER;
                }
            }

            static D3D11_STENCIL_OP getStencilOperation(StencilOperation stencilOperation)
            {
                switch (stencilOperation)
                {
                    case StencilOperation::Keep: return D3D11_STENCIL_OP_KEEP;
                    case StencilOperation::Zero: return D3D11_STENCIL_OP_ZERO;
                    case StencilOperation::Replace: return D3D11_STENCIL_OP_REPLACE;
                    case StencilOperation::IncrementClamp: return D3D11_STENCIL_OP_INCR_SAT;
                    case StencilOperation::DecrementClamp: return D3D11_STENCIL_OP_DECR_SAT;
                    case StencilOperation::Invert: return D3D11_STENCIL_OP_INVERT;
                    case StencilOperation::IncrementWrap: return D3D11_STENCIL_OP_INCR;
                    case StencilOperation::DecrementWrap: return D3D11_STENCIL_OP_DECR;
                    default: return D3D11_STENCIL_OP_KEEP;
                }
            }

            DepthStencilState::DepthStencilState(RenderDevice& initRenderDevice,
                                                 bool initDepthTest,
                                                 bool initDepthWrite,
                                                 CompareFunction initCompareFunction,
                                                 bool initStencilEnabled,
                                                 uint32_t initStencilReadMask,
                                                 uint32_t initStencilWriteMask,
                                                 StencilOperation initFrontFaceStencilFailureOperation,
                                                 StencilOperation initFrontFaceStencilDepthFailureOperation,
                                                 StencilOperation initFrontFaceStencilPassOperation,
                                                 CompareFunction initFrontFaceStencilCompareFunction,
                                                 StencilOperation initBackFaceStencilFailureOperation,
                                                 StencilOperation initBackFaceStencilDepthFailureOperation,
                                                 StencilOperation initBackFaceStencilPassOperation,
                                                 CompareFunction initBackFaceStencilCompareFunction):
                RenderResource(initRenderDevice)
            {
                D3D11_DEPTH_STENCIL_DESC depthStencilStateDesc;
                depthStencilStateDesc.DepthEnable = initDepthTest ? TRUE : FALSE;
                depthStencilStateDesc.DepthWriteMask = initDepthWrite ? D3D11_DEPTH_WRITE_MASK_ALL : D3D11_DEPTH_WRITE_MASK_ZERO;
                depthStencilStateDesc.DepthFunc = getCompareFunction(initCompareFunction);
                depthStencilStateDesc.StencilEnable = initStencilEnabled ? TRUE : FALSE;
                depthStencilStateDesc.StencilReadMask = static_cast<UINT8>(initStencilReadMask);
                depthStencilStateDesc.StencilWriteMask = static_cast<UINT8>(initStencilWriteMask);
                depthStencilStateDesc.FrontFace.StencilFailOp = getStencilOperation(initFrontFaceStencilFailureOperation);
                depthStencilStateDesc.FrontFace.StencilDepthFailOp = getStencilOperation(initFrontFaceStencilDepthFailureOperation);
                depthStencilStateDesc.FrontFace.StencilPassOp = getStencilOperation(initFrontFaceStencilPassOperation);
                depthStencilStateDesc.FrontFace.StencilFunc = getCompareFunction(initFrontFaceStencilCompareFunction);
                depthStencilStateDesc.BackFace.StencilFailOp = getStencilOperation(initBackFaceStencilFailureOperation);
                depthStencilStateDesc.BackFace.StencilDepthFailOp = getStencilOperation(initBackFaceStencilDepthFailureOperation);
                depthStencilStateDesc.BackFace.StencilPassOp = getStencilOperation(initBackFaceStencilPassOperation);
                depthStencilStateDesc.BackFace.StencilFunc = getCompareFunction(initBackFaceStencilCompareFunction);

                HRESULT hr;
                if (FAILED(hr = renderDevice.getDevice()->CreateDepthStencilState(&depthStencilStateDesc, &depthStencilState)))
                    throw std::system_error(hr, errorCategory, "Failed to create Direct3D 11 depth stencil state");
            }

            DepthStencilState::~DepthStencilState()
            {
                if (depthStencilState) depthStencilState->Release();
            }
        } // namespace d3d11
    } // namespace graphics
} // namespace ouzel

#endif
<|endoftext|>


<commit_before>#include "output.h"
#include "buffer_pool.h"
#include "compress.h"
#include "cso.h"

namespace maxcso {

// TODO: Tune, less may be better.
static const size_t QUEUE_SIZE = 128;

Output::Output(uv_loop_t *loop, const Task &task)
	: loop_(loop), flags_(task.flags), state_(STATE_INIT), srcSize_(-1), index_(nullptr) {
	for (size_t i = 0; i < QUEUE_SIZE; ++i) {
		freeSectors_.push_back(new Sector(task.flags));
	}
}

Output::~Output() {
	for (Sector *sector : freeSectors_) {
		delete sector;
	}
	for (auto pair : pendingSectors_) {
		delete pair.second;
	}
	freeSectors_.clear();
	pendingSectors_.clear();

	delete [] index_;
	index_ = nullptr;
}

void Output::SetFile(uv_file file, int64_t srcSize) {
	file_ = file;
	srcSize_ = srcSize;
	srcPos_ = 0;

	const uint32_t sectors = static_cast<uint32_t>(srcSize >> SECTOR_SHIFT);
	// Start after the header and index, which we'll fill in later.
	index_ = new uint32_t[sectors + 1];
	// Start after the end of the index data and header.
	dstPos_ = sizeof(CSOHeader) + (sectors + 1) * sizeof(uint32_t);

	// TODO: We might be able to optimize shift better by running through the data.
	// That would require either a second pass or keeping the entire result in RAM.
	// For now, just take worst case (all blocks stored uncompressed.)
	int64_t worstSize = dstPos_ + srcSize;
	shift_ = 0;
	for (int i = 62; i >= 31; --i) {
		int64_t max = 1LL << i;
		if (worstSize >= max) {
			// This means we need i + 1 bits to store the position.
			// We have to shift enough off to fit into 31.
			shift_ = i + 1 - 31;
			break;
		}
	}

	// If the shift is above 11, the padding could make it need more space.
	// But that would be > 4 TB anyway, so let's not worry about it.
	align_ = 1 << shift_;
	Align(dstPos_);

	state_ |= STATE_HAS_FILE;
}

int32_t Output::Align(int64_t &pos) {
	uint32_t off = static_cast<uint32_t>(pos % align_);
	if (off != 0) {
		pos += align_ - off;
		return align_ - off;
	}
	return 0;
}

void Output::Enqueue(int64_t pos, uint8_t *buffer) {
	Sector *sector = freeSectors_.back();
	freeSectors_.pop_back();

	// We might not compress all blocks.
	const bool tryCompress = ShouldCompress(pos, buffer);

	// Sector takes ownership of buffer either way.
	if (tryCompress) {
		sector->Process(loop_, pos, buffer, [this, sector](bool status, const char *reason) {
			HandleReadySector(sector);
		});
	} else {
		sector->Reserve(pos, buffer);
		HandleReadySector(sector);
	}
}

void Output::HandleReadySector(Sector *sector) {
	if (sector != nullptr) {
		if (srcPos_ != sector->Pos()) {
			// We're not there yet in the file stream.  Queue this, get to it later.
			pendingSectors_[sector->Pos()] = sector;
			return;
		}
	} else {
		// If no sector was provided, we're looking at the first in the queue.
		if (pendingSectors_.empty()) {
			return;
		}
		sector = pendingSectors_.begin()->second;
		if (srcPos_ != sector->Pos()) {
			return;
		}

		// Remove it from the queue, and then run with it.
		pendingSectors_.erase(pendingSectors_.begin());
	}

	// Check for any sectors that immediately follow the one we're writing.
	// We'll just write them all together.
	std::vector<Sector *> sectors;
	sectors.push_back(sector);
	// TODO: Try other numbers.
	static const size_t MAX_BUFS = 8;
	int64_t nextPos = srcPos_ + SECTOR_SIZE;
	auto it = pendingSectors_.find(nextPos);
	while (it != pendingSectors_.end()) {
		sectors.push_back(it->second);
		pendingSectors_.erase(it);
		nextPos += SECTOR_SIZE;
		it = pendingSectors_.find(nextPos);

		// Don't do more than 4 at a time.
		if (sectors.size() >= MAX_BUFS) {
			break;
		}
	}

	int64_t dstPos = dstPos_;
	uv_buf_t bufs[MAX_BUFS * 2];
	unsigned int nbufs = 0;
	static char padding[2048] = {0};
	for (size_t i = 0; i < sectors.size(); ++i) {
		bufs[nbufs++] = uv_buf_init(reinterpret_cast<char *>(sectors[i]->BestBuffer()), sectors[i]->BestSize());

		// Update the index.
		const int32_t s = static_cast<int32_t>(sectors[i]->Pos() >> SECTOR_SHIFT);
		index_[s] = static_cast<int32_t>(dstPos >> shift_);
		if (!sectors[i]->Compressed()) {
			index_[s] |= CSO_INDEX_UNCOMPRESSED;
		}

		dstPos += sectors[i]->BestSize();
		int32_t padSize = Align(dstPos);
		if (padSize != 0) {
			// We need uv to write the padding out as well.
			bufs[nbufs++] = uv_buf_init(padding, padSize);
		}
	}

	// If we're working on the last sectors, then the index is ready to write.
	if (nextPos == srcSize_) {
		// Update the final index entry.
		const int32_t s = static_cast<int32_t>(srcSize_ >> SECTOR_SHIFT);
		index_[s] = static_cast<int32_t>(dstPos >> shift_);

		state_ |= STATE_INDEX_READY;
		Flush();
	}

	const int64_t totalWrite = dstPos - dstPos_;
	uv_.fs_write(loop_, sector->WriteReq(), file_, bufs, nbufs, dstPos_, [this, sectors, nextPos, totalWrite](uv_fs_t *req) {
		for (Sector *sector : sectors) {
			sector->Release();
			freeSectors_.push_back(sector);
		}

		if (req->result != totalWrite) {
			finish_(false, "Data could not be written to output file");
			uv_fs_req_cleanup(req);
			return;
		}
		uv_fs_req_cleanup(req);

		srcPos_ = nextPos;
		dstPos_ += totalWrite;

		progress_(srcPos_, srcSize_, dstPos_);

		if (nextPos == srcSize_) {
			state_ |= STATE_DATA_WRITTEN;
			CheckFinish();
		} else {
			// Check if there's more data to write out.
			HandleReadySector(nullptr);
		}
	});
}

bool Output::ShouldCompress(int64_t pos, uint8_t *buffer) {
	if (flags_ & TASKFLAG_FORCE_ALL) {
		return true;
	}

	if (pos == 16 * SECTOR_SIZE) {
		// This is the volume descriptor.
		// TODO: Could read it in and map all the directory structures.
		// Would just need to keep  a list, assuming they are sequential, we'd get most of them.
		return false;
	}
	// TODO
	return true;
}

bool Output::QueueFull() {
	return freeSectors_.empty();
}

void Output::OnProgress(OutputCallback callback) {
	progress_ = callback;
}

void Output::OnFinish(OutputFinishCallback callback) {
	finish_ = callback;
}

void Output::Flush() {
	if (!(state_ & STATE_INDEX_READY)) {
		finish_(false, "Flush called before index finalized");
		return;
	}

	CSOHeader *header = new CSOHeader;
	memcpy(header->magic, CSO_MAGIC, sizeof(header->magic));
	header->header_size = sizeof(CSOHeader);
	header->uncompressed_size = srcSize_;
	header->sector_size = SECTOR_SIZE;
	header->version = 1;
	header->index_shift = shift_;
	header->unused[0] = 0;
	header->unused[1] = 0;

	const uint32_t sectors = static_cast<uint32_t>(srcSize_ >> SECTOR_SHIFT);

	uv_buf_t bufs[2];
	bufs[0] = uv_buf_init(reinterpret_cast<char *>(header), sizeof(CSOHeader));
	bufs[1] = uv_buf_init(reinterpret_cast<char *>(index_), (sectors + 1) * sizeof(uint32_t));
	const size_t totalBytes = sizeof(CSOHeader) + (sectors + 1) * sizeof(uint32_t);
	uv_.fs_write(loop_, &flush_, file_, bufs, 2, 0, [this, header, totalBytes](uv_fs_t *req) {
		if (req->result != totalBytes) {
			finish_(false, "Unable to write header data");
		} else {
			state_ |= STATE_INDEX_WRITTEN;
			CheckFinish();
		}
		uv_fs_req_cleanup(req);
		delete header;
	});
}

void Output::CheckFinish() {
	if ((state_ & STATE_INDEX_WRITTEN) && (state_ & STATE_DATA_WRITTEN)) {
		finish_(true, nullptr);
	}
}

};
<commit_msg>Disable the leading sector optimization.<commit_after>#include "output.h"
#include "buffer_pool.h"
#include "compress.h"
#include "cso.h"

namespace maxcso {

// TODO: Tune, less may be better.
static const size_t QUEUE_SIZE = 128;

Output::Output(uv_loop_t *loop, const Task &task)
	: loop_(loop), flags_(task.flags), state_(STATE_INIT), srcSize_(-1), index_(nullptr) {
	for (size_t i = 0; i < QUEUE_SIZE; ++i) {
		freeSectors_.push_back(new Sector(task.flags));
	}
}

Output::~Output() {
	for (Sector *sector : freeSectors_) {
		delete sector;
	}
	for (auto pair : pendingSectors_) {
		delete pair.second;
	}
	freeSectors_.clear();
	pendingSectors_.clear();

	delete [] index_;
	index_ = nullptr;
}

void Output::SetFile(uv_file file, int64_t srcSize) {
	file_ = file;
	srcSize_ = srcSize;
	srcPos_ = 0;

	const uint32_t sectors = static_cast<uint32_t>(srcSize >> SECTOR_SHIFT);
	// Start after the header and index, which we'll fill in later.
	index_ = new uint32_t[sectors + 1];
	// Start after the end of the index data and header.
	dstPos_ = sizeof(CSOHeader) + (sectors + 1) * sizeof(uint32_t);

	// TODO: We might be able to optimize shift better by running through the data.
	// That would require either a second pass or keeping the entire result in RAM.
	// For now, just take worst case (all blocks stored uncompressed.)
	int64_t worstSize = dstPos_ + srcSize;
	shift_ = 0;
	for (int i = 62; i >= 31; --i) {
		int64_t max = 1LL << i;
		if (worstSize >= max) {
			// This means we need i + 1 bits to store the position.
			// We have to shift enough off to fit into 31.
			shift_ = i + 1 - 31;
			break;
		}
	}

	// If the shift is above 11, the padding could make it need more space.
	// But that would be > 4 TB anyway, so let's not worry about it.
	align_ = 1 << shift_;
	Align(dstPos_);

	state_ |= STATE_HAS_FILE;
}

int32_t Output::Align(int64_t &pos) {
	uint32_t off = static_cast<uint32_t>(pos % align_);
	if (off != 0) {
		pos += align_ - off;
		return align_ - off;
	}
	return 0;
}

void Output::Enqueue(int64_t pos, uint8_t *buffer) {
	Sector *sector = freeSectors_.back();
	freeSectors_.pop_back();

	// We might not compress all blocks.
	const bool tryCompress = ShouldCompress(pos, buffer);

	// Sector takes ownership of buffer either way.
	if (tryCompress) {
		sector->Process(loop_, pos, buffer, [this, sector](bool status, const char *reason) {
			HandleReadySector(sector);
		});
	} else {
		sector->Reserve(pos, buffer);
		HandleReadySector(sector);
	}
}

void Output::HandleReadySector(Sector *sector) {
	if (sector != nullptr) {
		if (srcPos_ != sector->Pos()) {
			// We're not there yet in the file stream.  Queue this, get to it later.
			pendingSectors_[sector->Pos()] = sector;
			return;
		}
	} else {
		// If no sector was provided, we're looking at the first in the queue.
		if (pendingSectors_.empty()) {
			return;
		}
		sector = pendingSectors_.begin()->second;
		if (srcPos_ != sector->Pos()) {
			return;
		}

		// Remove it from the queue, and then run with it.
		pendingSectors_.erase(pendingSectors_.begin());
	}

	// Check for any sectors that immediately follow the one we're writing.
	// We'll just write them all together.
	std::vector<Sector *> sectors;
	sectors.push_back(sector);
	// TODO: Try other numbers.
	static const size_t MAX_BUFS = 8;
	int64_t nextPos = srcPos_ + SECTOR_SIZE;
	auto it = pendingSectors_.find(nextPos);
	while (it != pendingSectors_.end()) {
		sectors.push_back(it->second);
		pendingSectors_.erase(it);
		nextPos += SECTOR_SIZE;
		it = pendingSectors_.find(nextPos);

		// Don't do more than 4 at a time.
		if (sectors.size() >= MAX_BUFS) {
			break;
		}
	}

	int64_t dstPos = dstPos_;
	uv_buf_t bufs[MAX_BUFS * 2];
	unsigned int nbufs = 0;
	static char padding[2048] = {0};
	for (size_t i = 0; i < sectors.size(); ++i) {
		bufs[nbufs++] = uv_buf_init(reinterpret_cast<char *>(sectors[i]->BestBuffer()), sectors[i]->BestSize());

		// Update the index.
		const int32_t s = static_cast<int32_t>(sectors[i]->Pos() >> SECTOR_SHIFT);
		index_[s] = static_cast<int32_t>(dstPos >> shift_);
		if (!sectors[i]->Compressed()) {
			index_[s] |= CSO_INDEX_UNCOMPRESSED;
		}

		dstPos += sectors[i]->BestSize();
		int32_t padSize = Align(dstPos);
		if (padSize != 0) {
			// We need uv to write the padding out as well.
			bufs[nbufs++] = uv_buf_init(padding, padSize);
		}
	}

	// If we're working on the last sectors, then the index is ready to write.
	if (nextPos == srcSize_) {
		// Update the final index entry.
		const int32_t s = static_cast<int32_t>(srcSize_ >> SECTOR_SHIFT);
		index_[s] = static_cast<int32_t>(dstPos >> shift_);

		state_ |= STATE_INDEX_READY;
		Flush();
	}

	const int64_t totalWrite = dstPos - dstPos_;
	uv_.fs_write(loop_, sector->WriteReq(), file_, bufs, nbufs, dstPos_, [this, sectors, nextPos, totalWrite](uv_fs_t *req) {
		for (Sector *sector : sectors) {
			sector->Release();
			freeSectors_.push_back(sector);
		}

		if (req->result != totalWrite) {
			finish_(false, "Data could not be written to output file");
			uv_fs_req_cleanup(req);
			return;
		}
		uv_fs_req_cleanup(req);

		srcPos_ = nextPos;
		dstPos_ += totalWrite;

		progress_(srcPos_, srcSize_, dstPos_);

		if (nextPos == srcSize_) {
			state_ |= STATE_DATA_WRITTEN;
			CheckFinish();
		} else {
			// Check if there's more data to write out.
			HandleReadySector(nullptr);
		}
	});
}

bool Output::ShouldCompress(int64_t pos, uint8_t *buffer) {
	if (flags_ & TASKFLAG_FORCE_ALL) {
		return true;
	}

	if (pos == 16 * SECTOR_SIZE) {
		// This is the volume descriptor.
		// TODO: Could read it in and map all the directory structures.
		// Would just need to keep  a list, assuming they are sequential, we'd get most of them.
		// TODO: This doesn't really seem to help anyone.  Rethink.
		//return false;
	}
	// TODO
	return true;
}

bool Output::QueueFull() {
	return freeSectors_.empty();
}

void Output::OnProgress(OutputCallback callback) {
	progress_ = callback;
}

void Output::OnFinish(OutputFinishCallback callback) {
	finish_ = callback;
}

void Output::Flush() {
	if (!(state_ & STATE_INDEX_READY)) {
		finish_(false, "Flush called before index finalized");
		return;
	}

	CSOHeader *header = new CSOHeader;
	memcpy(header->magic, CSO_MAGIC, sizeof(header->magic));
	header->header_size = sizeof(CSOHeader);
	header->uncompressed_size = srcSize_;
	header->sector_size = SECTOR_SIZE;
	header->version = 1;
	header->index_shift = shift_;
	header->unused[0] = 0;
	header->unused[1] = 0;

	const uint32_t sectors = static_cast<uint32_t>(srcSize_ >> SECTOR_SHIFT);

	uv_buf_t bufs[2];
	bufs[0] = uv_buf_init(reinterpret_cast<char *>(header), sizeof(CSOHeader));
	bufs[1] = uv_buf_init(reinterpret_cast<char *>(index_), (sectors + 1) * sizeof(uint32_t));
	const size_t totalBytes = sizeof(CSOHeader) + (sectors + 1) * sizeof(uint32_t);
	uv_.fs_write(loop_, &flush_, file_, bufs, 2, 0, [this, header, totalBytes](uv_fs_t *req) {
		if (req->result != totalBytes) {
			finish_(false, "Unable to write header data");
		} else {
			state_ |= STATE_INDEX_WRITTEN;
			CheckFinish();
		}
		uv_fs_req_cleanup(req);
		delete header;
	});
}

void Output::CheckFinish() {
	if ((state_ & STATE_INDEX_WRITTEN) && (state_ & STATE_DATA_WRITTEN)) {
		finish_(true, nullptr);
	}
}

};
<|endoftext|>


<commit_before>e0c8e7ee-4b02-11e5-b74c-28cfe9171a43<commit_msg>Really doesn't crash if X, now<commit_after>e0d8c807-4b02-11e5-bc82-28cfe9171a43<|endoftext|>