<commit_before>/*
 * Distributed memory pool in shared memory.
 *
 * author: Max Kellermann <mk@cm4all.com>
 */

#include "dpool.hxx"
#include "dchunk.hxx"
#include "shm.hxx"

#include <inline/compiler.h>
#include <inline/poison.h>

#include <boost/interprocess/sync/interprocess_mutex.hpp>
#include <boost/interprocess/sync/scoped_lock.hpp>

#include <assert.h>

struct dpool {
    struct shm *const shm;
    mutable boost::interprocess::interprocess_mutex mutex;

    /**
     * Counts the number of d_free() calls.  After a certain number of
     * calls, we assume that the pool is "fragmented" and the session
     * shall be duplicated to a new pool.
     */
    unsigned free_counter = 0;

    DpoolChunk first_chunk;

    explicit dpool(struct shm &_shm);
    ~dpool();

    void *Allocate(size_t size) throw(std::bad_alloc);
    void Free(const void *p);

private:
    gcc_pure
    DpoolChunk *FindChunk(const void *p);
};

dpool::dpool(struct shm &_shm)
    :shm(&_shm),
     first_chunk(shm_page_size(shm) - sizeof(*this) +
                 sizeof(first_chunk.data))
{
    assert(shm_page_size(shm) >= sizeof(*this));

    list_init(&first_chunk.siblings);
}

dpool::~dpool()
{
    assert(shm != nullptr);

    DpoolChunk *chunk, *n;
    for (chunk = (DpoolChunk *)first_chunk.siblings.next;
         chunk != &first_chunk; chunk = n) {
        n = (DpoolChunk *)chunk->siblings.next;

        chunk->Destroy(*shm);
    }
}

struct dpool *
dpool_new(struct shm &shm)
{
    return NewFromShm<struct dpool>(&shm, 1, shm);
}

void
dpool_destroy(struct dpool *pool)
{
    assert(pool != nullptr);

    DeleteFromShm(pool->shm, pool);
}

bool
dpool_is_fragmented(const struct dpool &pool)
{
    return pool.free_counter >= 256;
}

inline void *
dpool::Allocate(size_t size) throw(std::bad_alloc)
{
    assert(shm != nullptr);

    /* we could theoretically allow larger allocations by using
       multiple consecutive chunks, but we don't implement that
       because our current use cases should not need to allocate such
       large structures */
    if (size > first_chunk.GetTotalSize())
        throw std::bad_alloc();

    boost::interprocess::scoped_lock<boost::interprocess::interprocess_mutex> scoped_lock(mutex);

    /* find a chunk with enough room */

    auto *chunk = &first_chunk;
    do {
        void *p = chunk->Allocate(size);
        if (p != nullptr)
            return p;

        chunk = (DpoolChunk *)chunk->siblings.next;
    } while (chunk != &first_chunk);

    /* none found; try to allocate a new chunk */

    chunk = DpoolChunk::New(*shm, first_chunk.siblings);
    if (chunk == nullptr)
        throw std::bad_alloc();

    void *p = chunk->Allocate(size);
    assert(p != nullptr);
    return p;
}

void *
d_malloc(struct dpool &pool, size_t size)
    throw(std::bad_alloc)
{
    return pool.Allocate(size);
}

inline DpoolChunk *
dpool::FindChunk(const void *p)
{
    if (first_chunk.Contains(p))
        return &first_chunk;

    for (auto *chunk = (DpoolChunk *)first_chunk.siblings.next;
         chunk != &first_chunk;
         chunk = (DpoolChunk *)chunk->siblings.next) {
        if (chunk->Contains(p))
            return chunk;
    }

    return nullptr;
}

inline void
dpool::Free(const void *p)
{
    boost::interprocess::scoped_lock<boost::interprocess::interprocess_mutex> scoped_lock(mutex);

    ++free_counter;

    auto *chunk = FindChunk(p);
    assert(chunk != nullptr);

    chunk->Free(const_cast<void *>(p));

    if (chunk->IsEmpty() && chunk != &first_chunk) {
        /* the chunk is completely empty; release it to the SHM
           object */
        list_remove(&chunk->siblings);
        chunk->Destroy(*shm);
    }
}

void
d_free(struct dpool &pool, const void *p)
{
    pool.Free(p);
}
<commit_msg>shm/dpool: suppress alignment warnings<commit_after>/*
 * Distributed memory pool in shared memory.
 *
 * author: Max Kellermann <mk@cm4all.com>
 */

#include "dpool.hxx"
#include "dchunk.hxx"
#include "shm.hxx"

#include <inline/compiler.h>
#include <inline/poison.h>

#include <boost/interprocess/sync/interprocess_mutex.hpp>
#include <boost/interprocess/sync/scoped_lock.hpp>

#include <assert.h>

struct dpool {
    struct shm *const shm;
    mutable boost::interprocess::interprocess_mutex mutex;

    /**
     * Counts the number of d_free() calls.  After a certain number of
     * calls, we assume that the pool is "fragmented" and the session
     * shall be duplicated to a new pool.
     */
    unsigned free_counter = 0;

    DpoolChunk first_chunk;

    explicit dpool(struct shm &_shm);
    ~dpool();

    void *Allocate(size_t size) throw(std::bad_alloc);
    void Free(const void *p);

private:
    gcc_pure
    DpoolChunk *FindChunk(const void *p);
};

dpool::dpool(struct shm &_shm)
    :shm(&_shm),
     first_chunk(shm_page_size(shm) - sizeof(*this) +
                 sizeof(first_chunk.data))
{
    assert(shm_page_size(shm) >= sizeof(*this));

    list_init(&first_chunk.siblings);
}

dpool::~dpool()
{
    assert(shm != nullptr);

    DpoolChunk *chunk, *n;
    for (chunk = (DpoolChunk *)(void *)first_chunk.siblings.next;
         chunk != &first_chunk; chunk = n) {
        n = (DpoolChunk *)(void *)chunk->siblings.next;

        chunk->Destroy(*shm);
    }
}

struct dpool *
dpool_new(struct shm &shm)
{
    return NewFromShm<struct dpool>(&shm, 1, shm);
}

void
dpool_destroy(struct dpool *pool)
{
    assert(pool != nullptr);

    DeleteFromShm(pool->shm, pool);
}

bool
dpool_is_fragmented(const struct dpool &pool)
{
    return pool.free_counter >= 256;
}

inline void *
dpool::Allocate(size_t size) throw(std::bad_alloc)
{
    assert(shm != nullptr);

    /* we could theoretically allow larger allocations by using
       multiple consecutive chunks, but we don't implement that
       because our current use cases should not need to allocate such
       large structures */
    if (size > first_chunk.GetTotalSize())
        throw std::bad_alloc();

    boost::interprocess::scoped_lock<boost::interprocess::interprocess_mutex> scoped_lock(mutex);

    /* find a chunk with enough room */

    auto *chunk = &first_chunk;
    do {
        void *p = chunk->Allocate(size);
        if (p != nullptr)
            return p;

        chunk = (DpoolChunk *)(void *)chunk->siblings.next;
    } while (chunk != &first_chunk);

    /* none found; try to allocate a new chunk */

    chunk = DpoolChunk::New(*shm, first_chunk.siblings);
    if (chunk == nullptr)
        throw std::bad_alloc();

    void *p = chunk->Allocate(size);
    assert(p != nullptr);
    return p;
}

void *
d_malloc(struct dpool &pool, size_t size)
    throw(std::bad_alloc)
{
    return pool.Allocate(size);
}

inline DpoolChunk *
dpool::FindChunk(const void *p)
{
    if (first_chunk.Contains(p))
        return &first_chunk;

    for (auto *chunk = (DpoolChunk *)(void *)first_chunk.siblings.next;
         chunk != &first_chunk;
         chunk = (DpoolChunk *)(void *)chunk->siblings.next) {
        if (chunk->Contains(p))
            return chunk;
    }

    return nullptr;
}

inline void
dpool::Free(const void *p)
{
    boost::interprocess::scoped_lock<boost::interprocess::interprocess_mutex> scoped_lock(mutex);

    ++free_counter;

    auto *chunk = FindChunk(p);
    assert(chunk != nullptr);

    chunk->Free(const_cast<void *>(p));

    if (chunk->IsEmpty() && chunk != &first_chunk) {
        /* the chunk is completely empty; release it to the SHM
           object */
        list_remove(&chunk->siblings);
        chunk->Destroy(*shm);
    }
}

void
d_free(struct dpool &pool, const void *p)
{
    pool.Free(p);
}
<|endoftext|>


<commit_before>/*************************************************
 * Copyright © 2015, afr-consulting GmbH         *
 *                                               *
 * See the file COPYING for copying permissions. *
 *************************************************/

#include <cxxutils/singleton.hxx>

namespace cxxutils
{
    std::string const singleton_error::already_exists = "A singleton instance already exists.";
    std::string const singleton_error::unexpected = "Something really bad and unexplanable happened.";
    std::string const singleton_error::access_non_existent = "Trying to access non-existent singleton instance.";

    singleton_error::singleton_error(std::string const & what_arg)
        : std::runtime_error(what_arg)
    {
    }

    singleton_error::singleton_error(char const * what_arg)
        : std::runtime_error(what_arg)
    {
    }
}
<commit_msg>Update singleton.cxx<commit_after>/*************************************************
 * Copyright © 2015, afr-consulting GmbH         *
 *                                               *
 * See the file COPYING for copying permissions. *
 *************************************************/

#include <cxxutils/singleton.hxx>

namespace cxxutils
{
    std::string const singleton_error::already_exists = "A singleton instance already exists.";
    std::string const singleton_error::unexpected = "Something really bad and unexplainable happened.";
    std::string const singleton_error::access_non_existent = "Trying to access non-existent singleton instance.";

    singleton_error::singleton_error(std::string const & what_arg)
        : std::runtime_error(what_arg)
    {
    }

    singleton_error::singleton_error(char const * what_arg)
        : std::runtime_error(what_arg)
    {
    }
}
<|endoftext|>


<commit_before>//===-- ubsan_flags.cc ----------------------------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// Runtime flags for UndefinedBehaviorSanitizer.
//
//===----------------------------------------------------------------------===//

#include "ubsan_platform.h"
#if CAN_SANITIZE_UB
#include "ubsan_flags.h"
#include "sanitizer_common/sanitizer_common.h"
#include "sanitizer_common/sanitizer_flags.h"
#include "sanitizer_common/sanitizer_flag_parser.h"

namespace __ubsan {

const char *MaybeCallUbsanDefaultOptions() {
  return (&__ubsan_default_options) ? __ubsan_default_options() : "";
}

Flags ubsan_flags;

void Flags::SetDefaults() {
#define UBSAN_FLAG(Type, Name, DefaultValue, Description) Name = DefaultValue;
#include "ubsan_flags.inc"
#undef UBSAN_FLAG
}

void RegisterUbsanFlags(FlagParser *parser, Flags *f) {
#define UBSAN_FLAG(Type, Name, DefaultValue, Description) \
  RegisterFlag(parser, #Name, Description, &f->Name);
#include "ubsan_flags.inc"
#undef UBSAN_FLAG
}

void InitializeFlags() {
  SetCommonFlagsDefaults();
  {
    CommonFlags cf;
    cf.CopyFrom(*common_flags());
    cf.print_summary = false;
    OverrideCommonFlags(cf);
  }

  Flags *f = flags();
  f->SetDefaults();

  FlagParser parser;
  RegisterCommonFlags(&parser);
  RegisterUbsanFlags(&parser, f);

  // Override from user-specified string.
  parser.ParseString(MaybeCallUbsanDefaultOptions());
  // Override from environment variable.
  parser.ParseString(GetEnv("UBSAN_OPTIONS"));
  InitializeCommonFlags();
  if (Verbosity()) ReportUnrecognizedFlags();

  if (common_flags()->help) parser.PrintFlagDescriptions();
}

}  // namespace __ubsan

SANITIZER_INTERFACE_WEAK_DEF(const char *, __ubsan_default_options, void) {
  return "";
}

#endif  // CAN_SANITIZE_UB
<commit_msg>Let ubsan search UBSAN_SYMBOLIZER_PATH for llvm-symbolizer<commit_after>//===-- ubsan_flags.cc ----------------------------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// Runtime flags for UndefinedBehaviorSanitizer.
//
//===----------------------------------------------------------------------===//

#include "ubsan_platform.h"
#if CAN_SANITIZE_UB
#include "ubsan_flags.h"
#include "sanitizer_common/sanitizer_common.h"
#include "sanitizer_common/sanitizer_flags.h"
#include "sanitizer_common/sanitizer_flag_parser.h"

namespace __ubsan {

const char *MaybeCallUbsanDefaultOptions() {
  return (&__ubsan_default_options) ? __ubsan_default_options() : "";
}

Flags ubsan_flags;

void Flags::SetDefaults() {
#define UBSAN_FLAG(Type, Name, DefaultValue, Description) Name = DefaultValue;
#include "ubsan_flags.inc"
#undef UBSAN_FLAG
}

void RegisterUbsanFlags(FlagParser *parser, Flags *f) {
#define UBSAN_FLAG(Type, Name, DefaultValue, Description) \
  RegisterFlag(parser, #Name, Description, &f->Name);
#include "ubsan_flags.inc"
#undef UBSAN_FLAG
}

void InitializeFlags() {
  SetCommonFlagsDefaults();
  {
    CommonFlags cf;
    cf.CopyFrom(*common_flags());
    cf.print_summary = false;
    cf.external_symbolizer_path = GetEnv("UBSAN_SYMBOLIZER_PATH");
    OverrideCommonFlags(cf);
  }

  Flags *f = flags();
  f->SetDefaults();

  FlagParser parser;
  RegisterCommonFlags(&parser);
  RegisterUbsanFlags(&parser, f);

  // Override from user-specified string.
  parser.ParseString(MaybeCallUbsanDefaultOptions());
  // Override from environment variable.
  parser.ParseString(GetEnv("UBSAN_OPTIONS"));
  InitializeCommonFlags();
  if (Verbosity()) ReportUnrecognizedFlags();

  if (common_flags()->help) parser.PrintFlagDescriptions();
}

}  // namespace __ubsan

SANITIZER_INTERFACE_WEAK_DEF(const char *, __ubsan_default_options, void) {
  return "";
}

#endif  // CAN_SANITIZE_UB
<|endoftext|>


<commit_before>/*
 * Copyright 2012 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include "GrTypes.h"
#include "SkThread.h"       // for sk_atomic_inc

// This used to be a global scope, but we got a warning about unused variable
// so we moved it into here. We just want it to compile, so we can test the
// static asserts.
static inline void dummy_function_to_avoid_unused_var_warning() {
    GrCacheID::Key kAssertKey;
    GR_STATIC_ASSERT(sizeof(kAssertKey.fData8) == sizeof(kAssertKey.fData32));
    GR_STATIC_ASSERT(sizeof(kAssertKey.fData8) == sizeof(kAssertKey.fData64));
    GR_STATIC_ASSERT(sizeof(kAssertKey.fData8) == sizeof(kAssertKey));
}

GrCacheID::Domain GrCacheID::GenerateDomain() {
    static int32_t gNextDomain = kInvalid_Domain + 1;

    int32_t domain = sk_atomic_inc(&gNextDomain);
    if (domain >= 1 << (8 * sizeof(Domain))) {
        GrCrash("Too many Cache Domains");
    }

    return static_cast<Domain>(domain);
}
<commit_msg>hide the static-assert block altogether, until we can find a construct that doesn't have warngs on mac or windows<commit_after>/*
 * Copyright 2012 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include "GrTypes.h"
#include "SkThread.h"       // for sk_atomic_inc

// Well, the dummy_ "fix" caused a warning on windows, so hiding all of it
// until we can find a universal fix.
#if 0
// This used to be a global scope, but we got a warning about unused variable
// so we moved it into here. We just want it to compile, so we can test the
// static asserts.
static inline void dummy_function_to_avoid_unused_var_warning() {
    GrCacheID::Key kAssertKey;
    GR_STATIC_ASSERT(sizeof(kAssertKey.fData8) == sizeof(kAssertKey.fData32));
    GR_STATIC_ASSERT(sizeof(kAssertKey.fData8) == sizeof(kAssertKey.fData64));
    GR_STATIC_ASSERT(sizeof(kAssertKey.fData8) == sizeof(kAssertKey));
}
#endif

GrCacheID::Domain GrCacheID::GenerateDomain() {
    static int32_t gNextDomain = kInvalid_Domain + 1;

    int32_t domain = sk_atomic_inc(&gNextDomain);
    if (domain >= 1 << (8 * sizeof(Domain))) {
        GrCrash("Too many Cache Domains");
    }

    return static_cast<Domain>(domain);
}
<|endoftext|>


<commit_before>/*
    Kopete , The KDE Instant Messenger
    Copyright (c) 2001-2002 by Duncan Mac-Vicar Prett <duncan@kde.org>

    Viva Chile Mierda!
    Started at Wed Dec 26 03:12:10 CLST 2001, Santiago de Chile

    Kopete    (c) 2002-2003 by the Kopete developers  <kopete-devel@kde.org>

    *************************************************************************
    *                                                                       *
    * This program is free software; you can redistribute it and/or modify  *
    * it under the terms of the GNU General Public License as published by  *
    * the Free Software Foundation; either version 2 of the License, or     *
    * (at your option) any later version.                                   *
    *                                                                       *
    *************************************************************************
*/

#include <kcmdlineargs.h>
#include <kaboutdata.h>
#include "kopeteapplication.h"

#include <dcopclient.h>
#include "kopeteiface.h"
#include "kimifaceimpl.h"

#define KOPETE_VERSION "0.8.90 (CVS >= 20040616)"

static const char description[] =
	I18N_NOOP( "Kopete, the KDE Instant Messenger" );

static KCmdLineOptions options[] =
{
	{ "noplugins",              I18N_NOOP( "Do not load plugins. This option overrides all other options." ), 0 },
	{ "noconnect",              I18N_NOOP( "Disable auto-connection" ), 0 },
	{ "autoconnect <accounts>", I18N_NOOP( "Auto-connect the specified accounts. Use a comma-separated list\n"
		"to auto-connect multiple accounts." ), 0 },
	{ "disable <plugins>",      I18N_NOOP( "Do not load the specified plugin. Use a comma-separated list\n"
		"to disable multiple plugins." ), 0 },
	{ "load-plugins <plugins>", I18N_NOOP( "Load only the specified plugins. Use a comma-separated list\n"
		"to load multiple plugins. This option has no effect when\n"
		"--noplugins is set and overrides all other plugin related\n"
		"command line options." ), 0 },
//	{ "url <url>",              I18N_NOOP( "Load the given Kopete URL" ), 0 },
//	{ "!+[plugin]",            I18N_NOOP( "Load specified plugins" ), 0 },
	{ "!+[URL]",                 I18N_NOOP("URLs to pass to kopete / emoticon themes to install"), 0},
	KCmdLineLastOption
};

int main( int argc, char *argv[] )
{
	KAboutData aboutData( "kopete", I18N_NOOP("Kopete"),
		KOPETE_VERSION, description, KAboutData::License_GPL,
		I18N_NOOP("(c) 2001-2004, Duncan Mac-Vicar Prett\n(c) 2002-2004, Kopete Development Team"), "kopete-devel@kde.org", "http://kopete.kde.org");

	aboutData.addAuthor ( "Duncan Mac-Vicar Prett", I18N_NOOP("Original author, Developer"), "duncan@kde.org", "http://www.mac-vicar.org/~duncan" );
	aboutData.addAuthor ( "Stefan Gehn", I18N_NOOP("Developer, Oscar plugin"), "metz@gehn.net", "http://metz.gehn.net" );
	aboutData.addAuthor ( "Till Gerken", I18N_NOOP("Developer, Jabber plugin maintainer"), "till@tantalo.net");
	aboutData.addAuthor ( "Olivier Goffart", I18N_NOOP("Developer, MSN plugin maintainer"), "ogoffart@tiscalinet.be");
	aboutData.addAuthor ( "Andy Goossens", I18N_NOOP("Developer"), "andygoossens@telenet.be" );
	aboutData.addAuthor ( "Chris Howells", I18N_NOOP("Developer, Connection status plugin author"), "howells@kde.org", "http://chrishowells.co.uk");
	aboutData.addAuthor ( "Grzegorz Jaskiewicz", I18N_NOOP("Developer, Gadu plugin maintainer"), "gj@pointblue.com.pl" );
	aboutData.addAuthor ( "Jason Keirstead", I18N_NOOP("Developer, IRC maintainer"), "jason@keirstead.org", "http://www.keirstead.org");
	aboutData.addAuthor ( "Martijn Klingens", I18N_NOOP("Developer"), "klingens@kde.org" );
	aboutData.addAuthor ( "Matt Rogers", I18N_NOOP("Developer, Yahoo plugin and Oscar plugin maintainer"), "mattrogers@sbcglobal.net" );
	aboutData.addAuthor ( "Zack Rusin", I18N_NOOP("Developer, original Gadu plugin author"), "zack@kde.org" );
	aboutData.addAuthor ( "Richard Smith", I18N_NOOP("Developer, UI maintainer"), "kde@metafoo.co.uk" );
	aboutData.addAuthor ( "Will Stephenson", I18N_NOOP("Developer, icons, various plugins"), "lists@stevello.free-online.co.uk" );
	aboutData.addAuthor ( "Gav Wood", I18N_NOOP("Developer, WinPopup plugin maintainer"), "gjw102@york.ac.uk" );

	aboutData.addCredit ( "Luciash d' Being", I18N_NOOP("Kopete's icon author") );
	aboutData.addCredit ( "Steve Cable", I18N_NOOP("Sounds") );
	aboutData.addCredit ( "Justin Karneges", I18N_NOOP("Iris Jabber Backend Library") );
	aboutData.addCredit ( "Tom Linsky", I18N_NOOP("OscarSocket author"), "twl6@po.cwru.edu" );
	aboutData.addCredit ( "Olaf Lueg", I18N_NOOP("Kmerlin MSN code") );

	aboutData.addCredit ( "Nick Betcher", I18N_NOOP("Former developer, project co-founder"), "nbetcher@kde.org");
	aboutData.addCredit ( "Ryan Cumming", I18N_NOOP("Former developer"), "ryan@kde.org" );
	aboutData.addCredit ( "Andres Krapf", I18N_NOOP("Former developer"), "dae@chez.com" );
	aboutData.addCredit ( "Carsten Pfeiffer", I18N_NOOP("Misc bugfixes and enhancements"), "pfeiffer@kde.org" );
	aboutData.addCredit ( "Richard Stellingwerff", I18N_NOOP("Former developer"), "remenic@linuxfromscratch.org");
	aboutData.addCredit ( "Daniel Stone", I18N_NOOP("Former developer, Jabber plugin author"), "daniel@fooishbar.org", "http://fooishbar.org");
	aboutData.addCredit ( "Chris TenHarmsel", I18N_NOOP("Former developer, Oscar plugin"), "tenharmsel@users.sourceforge.net");
	aboutData.addCredit ( "Hendrik vom Lehn", I18N_NOOP("Former developer"), "hennevl@hennevl.de", "http://www.hennevl.de");

	aboutData.setTranslator( I18N_NOOP("_: NAME OF TRANSLATORS\nYour names"),
		I18N_NOOP("_: EMAIL OF TRANSLATORS\nYour emails") );

	KCmdLineArgs::init( argc, argv, &aboutData );
	KCmdLineArgs::addCmdLineOptions( options ); // Add our own options.
	KUniqueApplication::addCmdLineOptions();

	KopeteApplication kopete;
	new KIMIfaceImpl();
	kapp->dcopClient()->registerAs( "kopete", false );
	kapp->dcopClient()->setDefaultObject( (new KopeteIface())->objId() ); // Has to be called before exec

	kopete.exec();
}
// vim: set noet ts=4 sts=4 sw=4:
<commit_msg>91<commit_after>/*
    Kopete , The KDE Instant Messenger
    Copyright (c) 2001-2002 by Duncan Mac-Vicar Prett <duncan@kde.org>

    Viva Chile Mierda!
    Started at Wed Dec 26 03:12:10 CLST 2001, Santiago de Chile

    Kopete    (c) 2002-2003 by the Kopete developers  <kopete-devel@kde.org>

    *************************************************************************
    *                                                                       *
    * This program is free software; you can redistribute it and/or modify  *
    * it under the terms of the GNU General Public License as published by  *
    * the Free Software Foundation; either version 2 of the License, or     *
    * (at your option) any later version.                                   *
    *                                                                       *
    *************************************************************************
*/

#include <kcmdlineargs.h>
#include <kaboutdata.h>
#include "kopeteapplication.h"

#include <dcopclient.h>
#include "kopeteiface.h"
#include "kimifaceimpl.h"

#define KOPETE_VERSION "0.8.91 (CVS >= 20040626)"

static const char description[] =
	I18N_NOOP( "Kopete, the KDE Instant Messenger" );

static KCmdLineOptions options[] =
{
	{ "noplugins",              I18N_NOOP( "Do not load plugins. This option overrides all other options." ), 0 },
	{ "noconnect",              I18N_NOOP( "Disable auto-connection" ), 0 },
	{ "autoconnect <accounts>", I18N_NOOP( "Auto-connect the specified accounts. Use a comma-separated list\n"
		"to auto-connect multiple accounts." ), 0 },
	{ "disable <plugins>",      I18N_NOOP( "Do not load the specified plugin. Use a comma-separated list\n"
		"to disable multiple plugins." ), 0 },
	{ "load-plugins <plugins>", I18N_NOOP( "Load only the specified plugins. Use a comma-separated list\n"
		"to load multiple plugins. This option has no effect when\n"
		"--noplugins is set and overrides all other plugin related\n"
		"command line options." ), 0 },
//	{ "url <url>",              I18N_NOOP( "Load the given Kopete URL" ), 0 },
//	{ "!+[plugin]",            I18N_NOOP( "Load specified plugins" ), 0 },
	{ "!+[URL]",                 I18N_NOOP("URLs to pass to kopete / emoticon themes to install"), 0},
	KCmdLineLastOption
};

int main( int argc, char *argv[] )
{
	KAboutData aboutData( "kopete", I18N_NOOP("Kopete"),
		KOPETE_VERSION, description, KAboutData::License_GPL,
		I18N_NOOP("(c) 2001-2004, Duncan Mac-Vicar Prett\n(c) 2002-2004, Kopete Development Team"), "kopete-devel@kde.org", "http://kopete.kde.org");

	aboutData.addAuthor ( "Duncan Mac-Vicar Prett", I18N_NOOP("Original author, Developer"), "duncan@kde.org", "http://www.mac-vicar.org/~duncan" );
	aboutData.addAuthor ( "Stefan Gehn", I18N_NOOP("Developer, Oscar plugin"), "metz@gehn.net", "http://metz.gehn.net" );
	aboutData.addAuthor ( "Till Gerken", I18N_NOOP("Developer, Jabber plugin maintainer"), "till@tantalo.net");
	aboutData.addAuthor ( "Olivier Goffart", I18N_NOOP("Developer, MSN plugin maintainer"), "ogoffart@tiscalinet.be");
	aboutData.addAuthor ( "Andy Goossens", I18N_NOOP("Developer"), "andygoossens@telenet.be" );
	aboutData.addAuthor ( "Chris Howells", I18N_NOOP("Developer, Connection status plugin author"), "howells@kde.org", "http://chrishowells.co.uk");
	aboutData.addAuthor ( "Grzegorz Jaskiewicz", I18N_NOOP("Developer, Gadu plugin maintainer"), "gj@pointblue.com.pl" );
	aboutData.addAuthor ( "Jason Keirstead", I18N_NOOP("Developer, IRC maintainer"), "jason@keirstead.org", "http://www.keirstead.org");
	aboutData.addAuthor ( "Martijn Klingens", I18N_NOOP("Developer"), "klingens@kde.org" );
	aboutData.addAuthor ( "Matt Rogers", I18N_NOOP("Developer, Yahoo plugin and Oscar plugin maintainer"), "mattrogers@sbcglobal.net" );
	aboutData.addAuthor ( "Zack Rusin", I18N_NOOP("Developer, original Gadu plugin author"), "zack@kde.org" );
	aboutData.addAuthor ( "Richard Smith", I18N_NOOP("Developer, UI maintainer"), "kde@metafoo.co.uk" );
	aboutData.addAuthor ( "Will Stephenson", I18N_NOOP("Developer, icons, various plugins"), "lists@stevello.free-online.co.uk" );
	aboutData.addAuthor ( "Gav Wood", I18N_NOOP("Developer, WinPopup plugin maintainer"), "gjw102@york.ac.uk" );

	aboutData.addCredit ( "Luciash d' Being", I18N_NOOP("Kopete's icon author") );
	aboutData.addCredit ( "Steve Cable", I18N_NOOP("Sounds") );
	aboutData.addCredit ( "Justin Karneges", I18N_NOOP("Iris Jabber Backend Library") );
	aboutData.addCredit ( "Tom Linsky", I18N_NOOP("OscarSocket author"), "twl6@po.cwru.edu" );
	aboutData.addCredit ( "Olaf Lueg", I18N_NOOP("Kmerlin MSN code") );

	aboutData.addCredit ( "Nick Betcher", I18N_NOOP("Former developer, project co-founder"), "nbetcher@kde.org");
	aboutData.addCredit ( "Ryan Cumming", I18N_NOOP("Former developer"), "ryan@kde.org" );
	aboutData.addCredit ( "Andres Krapf", I18N_NOOP("Former developer"), "dae@chez.com" );
	aboutData.addCredit ( "Carsten Pfeiffer", I18N_NOOP("Misc bugfixes and enhancements"), "pfeiffer@kde.org" );
	aboutData.addCredit ( "Richard Stellingwerff", I18N_NOOP("Former developer"), "remenic@linuxfromscratch.org");
	aboutData.addCredit ( "Daniel Stone", I18N_NOOP("Former developer, Jabber plugin author"), "daniel@fooishbar.org", "http://fooishbar.org");
	aboutData.addCredit ( "Chris TenHarmsel", I18N_NOOP("Former developer, Oscar plugin"), "tenharmsel@users.sourceforge.net");
	aboutData.addCredit ( "Hendrik vom Lehn", I18N_NOOP("Former developer"), "hennevl@hennevl.de", "http://www.hennevl.de");

	aboutData.setTranslator( I18N_NOOP("_: NAME OF TRANSLATORS\nYour names"),
		I18N_NOOP("_: EMAIL OF TRANSLATORS\nYour emails") );

	KCmdLineArgs::init( argc, argv, &aboutData );
	KCmdLineArgs::addCmdLineOptions( options ); // Add our own options.
	KUniqueApplication::addCmdLineOptions();

	KopeteApplication kopete;
	new KIMIfaceImpl();
	kapp->dcopClient()->registerAs( "kopete", false );
	kapp->dcopClient()->setDefaultObject( (new KopeteIface())->objId() ); // Has to be called before exec

	kopete.exec();
}
// vim: set noet ts=4 sts=4 sw=4:
<|endoftext|>


<commit_before>/** @file

  A brief file description

  @section license License

  Licensed to the Apache Software Foundation (ASF) under one
  or more contributor license agreements.  See the NOTICE file
  distributed with this work for additional information
  regarding copyright ownership.  The ASF licenses this file
  to you under the Apache License, Version 2.0 (the
  "License"); you may not use this file except in compliance
  with the License.  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  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 "ink_platform.h"
#include "Tokenizer.h"
#include "ink_assert.h"
#include "ink_memory.h"

/****************************************************************************
 *
 *  Tokenizer.cc - A string tokenzier
 *
 *
 *
 ****************************************************************************/        /* MAGIC_EDITING_TAG */

Tokenizer::Tokenizer(const char *StrOfDelimiters)
{
  int length;

  if (StrOfDelimiters == NULL) {
    strOfDelimit = NULL;
  } else {
    length = (int) (strlen(StrOfDelimiters) + 1);
    strOfDelimit = new char[length];
    memcpy(strOfDelimit, StrOfDelimiters, length);
  }

  memset(&start_node, 0, sizeof(tok_node));

  numValidTokens = 0;
  maxTokens = -1;
  options = 0;

  add_node = &start_node;
  add_index = 0;
  quoteFound = false;
}

Tokenizer::~Tokenizer()
{
  bool root = true;
  tok_node *cur = &start_node;;
  tok_node *next = NULL;

  if (strOfDelimit != NULL) {
    delete[]strOfDelimit;
  }

  while (cur != NULL) {

    if (options & COPY_TOKS) {
      for (int i = 0; i < TOK_NODE_ELEMENTS; i++)
        ats_free(cur->el[i]);
    }

    next = cur->next;
    if (root == false) {
      ats_free(cur);
    } else {
      root = false;
    }
    cur = next;
  }
}

int
Tokenizer::Initialize(const char *str)
{
  return Initialize((char *) str, COPY_TOKS);
}

inline int
Tokenizer::isDelimiter(char c)
{
  int i = 0;

  if ((options & ALLOW_SPACES) &&
      ((c == 0x22) || (c == 0x27))) {
    quoteFound = !quoteFound;
  }

  if (quoteFound)
    return 0;

  while (strOfDelimit[i] != '\0') {
    if (c == strOfDelimit[i]) {
      return 1;
    }
    i++;
  }

  return 0;
}

int
Tokenizer::Initialize(char *str, int opt)
{
  char *strStart;
  int priorCharWasDelimit = 1;
  char *tokStart = NULL;
  int tok_count = 0;
  bool max_limit_hit = false;

  // We can't depend on ReUse() being called so just do it
  //   if the object needs it
  if (numValidTokens > 0) {
    ReUse();
  }

  strStart = str;

  if (!(opt & (COPY_TOKS | SHARE_TOKS))) {
    opt = opt | COPY_TOKS;
  }
  options = opt;

  // Make sure that both options are not set
  ink_assert(!((opt & COPY_TOKS) && (opt & SHARE_TOKS)));

  str = strStart;
  priorCharWasDelimit = 1;

  tok_count = 0;
  tokStart = str;

  while (*str != '\0') {

    // Check to see if we've run to maxToken limit
    if (tok_count + 1 == maxTokens) {
      max_limit_hit = true;
      break;
    }
    // There two modes for collecting tokens
    //
    //  Mode 1: Every delimiter creates a token
    //          even if some of those tokens
    //          are zero length
    //
    //  Mode2:  Every token has some data
    //          in it which means we
    //          to skip past repeated delimiters
    if (options & ALLOW_EMPTY_TOKS) {
      if (isDelimiter(*str)) {
        addToken(tokStart, (int) (str - tokStart));
        tok_count++;
        tokStart = str + 1;
        priorCharWasDelimit = 1;
      } else {
        priorCharWasDelimit = 0;
      }
      str++;
    } else {
      if (isDelimiter(*str)) {
        if (priorCharWasDelimit == 0) {
          // This is a word end, so add it
          addToken(tokStart, (int) (str - tokStart));
          tok_count++;
        }
        priorCharWasDelimit = 1;
      } else {
        if (priorCharWasDelimit == 1) {
          // This is the start of a new token
          tokStart = str;
        }
        priorCharWasDelimit = 0;
      }
      str++;
    }
  }

  quoteFound = false;

  // Check to see if we stoped due to a maxToken limit
  if (max_limit_hit == true) {

    if (options & ALLOW_EMPTY_TOKS) {

      // Go till either we hit a delimiter or we've
      //   come to the end of the string, then
      //   set for copying
      for (; *str != '\0' && !isDelimiter(*str); str++);
      priorCharWasDelimit = 0;

    } else {

      // First, skip the delimiters
      for (; *str != '\0' && isDelimiter(*str); str++);

      // If there are only delimiters remaining, bail and set
      //   so that we do not add the empty token
      if (*str == '\0') {
        priorCharWasDelimit = 1;
      } else {
        // There is stuff to copy for the last token
        tokStart = str;
        priorCharWasDelimit = 0;

        // Advance until the end of the string
        for (; *str != '\0'; str++);

        // Now back off all trailing delimiters
        for (; isDelimiter(*(str - 1)); str--);
      }
    }
  }

  quoteFound = false;
  // Check to see if we got the last token.  We will
  //  only have gotten it if the string ended with a delimiter
  if (priorCharWasDelimit == 0) {
    // We did not get it
    addToken(tokStart, (int) (str - tokStart));
    tok_count++;
  }

  numValidTokens = tok_count;
  return tok_count;
}

void
Tokenizer::addToken(char *startAddr, int length)
{
  char *add_ptr;
  if (options & SHARE_TOKS) {
    startAddr[length] = '\0';
    add_ptr = startAddr;
  } else {
    add_ptr = (char *)ats_malloc(length + 1);
    memcpy(add_ptr, startAddr, length);
    add_ptr[length] = '\0';
  }

  add_node->el[add_index] = add_ptr;

  add_index++;

  // Check to see if we are out of elements after
  //   adding this one.  If we are change add_node
  //   to point to next tok_node, creating one
  //   if there is not a next one
  if (add_index >= TOK_NODE_ELEMENTS) {
    if (add_node->next == NULL) {
      add_node->next = (tok_node *)ats_malloc(sizeof(tok_node));
      memset(add_node->next, 0, sizeof(tok_node));
    }
    add_node = add_node->next;
    add_index = 0;
  }
}

const char *
Tokenizer::operator[] (int index)
{
  tok_node *
    cur_node = &start_node;
  int
    cur_start = 0;
  if (index >= numValidTokens) {
    return NULL;
  } else {
    while (cur_start + TOK_NODE_ELEMENTS <= index) {
      cur_node = cur_node->next;
      ink_assert(cur_node != NULL);
      cur_start += TOK_NODE_ELEMENTS;
    }
    return cur_node->el[index % TOK_NODE_ELEMENTS];
  }
}

int
Tokenizer::getNumber()
{
  return numValidTokens;
}

const char *
Tokenizer::iterFirst(tok_iter_state * state)
{
  state->node = &start_node;
  state->index = -1;
  return iterNext(state);
}

const char *
Tokenizer::iterNext(tok_iter_state * state)
{
  tok_node *node = state->node;;
  int index = state->index;

  index++;
  if (index >= TOK_NODE_ELEMENTS) {
    node = node->next;
    if (node == NULL) {
      return NULL;
    } else {
      index = 0;
    }
  }

  if (node->el[index] != NULL) {
    state->node = node;
    state->index = index;
    return node->el[index];
  } else {
    return NULL;
  }
}

void
Tokenizer::Print()
{
  tok_node *cur_node = &start_node;
  int node_index = 0;
  int count = 0;

  while (cur_node != NULL) {

    if (cur_node->el[node_index] != NULL) {
      printf("Token %d : |%s|\n", count, cur_node->el[node_index]);
      count++;
    } else {
      return;
    }

    node_index++;
    if (node_index >= TOK_NODE_ELEMENTS) {
      cur_node = cur_node->next;
      node_index = 0;
    }
  }
}

void
Tokenizer::ReUse()
{
  tok_node *cur_node = &start_node;

  while (cur_node != NULL) {
    if (options & COPY_TOKS) {
      for (int i = 0; i < TOK_NODE_ELEMENTS; i++)
        ats_free(cur_node->el[i]);
    }
    memset(cur_node->el, 0, sizeof(char *) * TOK_NODE_ELEMENTS);
    cur_node = cur_node->next;
  }

  numValidTokens = 0;
  add_node = &start_node;
  add_index = 0;
}
<commit_msg>TS-3023 Fix indentation.<commit_after>/** @file

  A brief file description

  @section license License

  Licensed to the Apache Software Foundation (ASF) under one
  or more contributor license agreements.  See the NOTICE file
  distributed with this work for additional information
  regarding copyright ownership.  The ASF licenses this file
  to you under the Apache License, Version 2.0 (the
  "License"); you may not use this file except in compliance
  with the License.  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  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 "ink_platform.h"
#include "Tokenizer.h"
#include "ink_assert.h"
#include "ink_memory.h"

/****************************************************************************
 *
 *  Tokenizer.cc - A string tokenzier
 *
 *
 *
 ****************************************************************************/        /* MAGIC_EDITING_TAG */

Tokenizer::Tokenizer(const char *StrOfDelimiters)
{
  int length;

  if (StrOfDelimiters == NULL) {
    strOfDelimit = NULL;
  } else {
    length = (int) (strlen(StrOfDelimiters) + 1);
    strOfDelimit = new char[length];
    memcpy(strOfDelimit, StrOfDelimiters, length);
  }

  memset(&start_node, 0, sizeof(tok_node));

  numValidTokens = 0;
  maxTokens = -1;
  options = 0;

  add_node = &start_node;
  add_index = 0;
  quoteFound = false;
}

Tokenizer::~Tokenizer()
{
  bool root = true;
  tok_node *cur = &start_node;;
  tok_node *next = NULL;

  if (strOfDelimit != NULL) {
    delete[]strOfDelimit;
  }

  while (cur != NULL) {

    if (options & COPY_TOKS) {
      for (int i = 0; i < TOK_NODE_ELEMENTS; i++)
        ats_free(cur->el[i]);
    }

    next = cur->next;
    if (root == false) {
      ats_free(cur);
    } else {
      root = false;
    }
    cur = next;
  }
}

int
Tokenizer::Initialize(const char *str)
{
  return Initialize((char *) str, COPY_TOKS);
}

inline int
Tokenizer::isDelimiter(char c)
{
  int i = 0;

  if ((options & ALLOW_SPACES) && ((c == 0x22) || (c == 0x27))) {
    quoteFound = !quoteFound;
  }

  if (quoteFound)
    return 0;

  while (strOfDelimit[i] != '\0') {
    if (c == strOfDelimit[i]) {
      return 1;
    }
    i++;
  }

  return 0;
}

int
Tokenizer::Initialize(char *str, int opt)
{
  char *strStart;
  int priorCharWasDelimit = 1;
  char *tokStart = NULL;
  int tok_count = 0;
  bool max_limit_hit = false;

  // We can't depend on ReUse() being called so just do it
  //   if the object needs it
  if (numValidTokens > 0) {
    ReUse();
  }

  strStart = str;

  if (!(opt & (COPY_TOKS | SHARE_TOKS))) {
    opt = opt | COPY_TOKS;
  }
  options = opt;

  // Make sure that both options are not set
  ink_assert(!((opt & COPY_TOKS) && (opt & SHARE_TOKS)));

  str = strStart;
  priorCharWasDelimit = 1;

  tok_count = 0;
  tokStart = str;

  while (*str != '\0') {

    // Check to see if we've run to maxToken limit
    if (tok_count + 1 == maxTokens) {
      max_limit_hit = true;
      break;
    }
    // There two modes for collecting tokens
    //
    //  Mode 1: Every delimiter creates a token
    //          even if some of those tokens
    //          are zero length
    //
    //  Mode2:  Every token has some data
    //          in it which means we
    //          to skip past repeated delimiters
    if (options & ALLOW_EMPTY_TOKS) {
      if (isDelimiter(*str)) {
        addToken(tokStart, (int) (str - tokStart));
        tok_count++;
        tokStart = str + 1;
        priorCharWasDelimit = 1;
      } else {
        priorCharWasDelimit = 0;
      }
      str++;
    } else {
      if (isDelimiter(*str)) {
        if (priorCharWasDelimit == 0) {
          // This is a word end, so add it
          addToken(tokStart, (int) (str - tokStart));
          tok_count++;
        }
        priorCharWasDelimit = 1;
      } else {
        if (priorCharWasDelimit == 1) {
          // This is the start of a new token
          tokStart = str;
        }
        priorCharWasDelimit = 0;
      }
      str++;
    }
  }

  quoteFound = false;

  // Check to see if we stoped due to a maxToken limit
  if (max_limit_hit == true) {

    if (options & ALLOW_EMPTY_TOKS) {

      // Go till either we hit a delimiter or we've
      //   come to the end of the string, then
      //   set for copying
      for (; *str != '\0' && !isDelimiter(*str); str++);
      priorCharWasDelimit = 0;

    } else {

      // First, skip the delimiters
      for (; *str != '\0' && isDelimiter(*str); str++);

      // If there are only delimiters remaining, bail and set
      //   so that we do not add the empty token
      if (*str == '\0') {
        priorCharWasDelimit = 1;
      } else {
        // There is stuff to copy for the last token
        tokStart = str;
        priorCharWasDelimit = 0;

        // Advance until the end of the string
        for (; *str != '\0'; str++);

        // Now back off all trailing delimiters
        for (; isDelimiter(*(str - 1)); str--);
      }
    }
  }

  quoteFound = false;
  // Check to see if we got the last token.  We will
  //  only have gotten it if the string ended with a delimiter
  if (priorCharWasDelimit == 0) {
    // We did not get it
    addToken(tokStart, (int) (str - tokStart));
    tok_count++;
  }

  numValidTokens = tok_count;
  return tok_count;
}

void
Tokenizer::addToken(char *startAddr, int length)
{
  char *add_ptr;
  if (options & SHARE_TOKS) {
    startAddr[length] = '\0';
    add_ptr = startAddr;
  } else {
    add_ptr = (char *)ats_malloc(length + 1);
    memcpy(add_ptr, startAddr, length);
    add_ptr[length] = '\0';
  }

  add_node->el[add_index] = add_ptr;

  add_index++;

  // Check to see if we are out of elements after
  //   adding this one.  If we are change add_node
  //   to point to next tok_node, creating one
  //   if there is not a next one
  if (add_index >= TOK_NODE_ELEMENTS) {
    if (add_node->next == NULL) {
      add_node->next = (tok_node *)ats_malloc(sizeof(tok_node));
      memset(add_node->next, 0, sizeof(tok_node));
    }
    add_node = add_node->next;
    add_index = 0;
  }
}

const char *
Tokenizer::operator[] (int index)
{
  tok_node *
    cur_node = &start_node;
  int
    cur_start = 0;
  if (index >= numValidTokens) {
    return NULL;
  } else {
    while (cur_start + TOK_NODE_ELEMENTS <= index) {
      cur_node = cur_node->next;
      ink_assert(cur_node != NULL);
      cur_start += TOK_NODE_ELEMENTS;
    }
    return cur_node->el[index % TOK_NODE_ELEMENTS];
  }
}

int
Tokenizer::getNumber()
{
  return numValidTokens;
}

const char *
Tokenizer::iterFirst(tok_iter_state * state)
{
  state->node = &start_node;
  state->index = -1;
  return iterNext(state);
}

const char *
Tokenizer::iterNext(tok_iter_state * state)
{
  tok_node *node = state->node;;
  int index = state->index;

  index++;
  if (index >= TOK_NODE_ELEMENTS) {
    node = node->next;
    if (node == NULL) {
      return NULL;
    } else {
      index = 0;
    }
  }

  if (node->el[index] != NULL) {
    state->node = node;
    state->index = index;
    return node->el[index];
  } else {
    return NULL;
  }
}

void
Tokenizer::Print()
{
  tok_node *cur_node = &start_node;
  int node_index = 0;
  int count = 0;

  while (cur_node != NULL) {

    if (cur_node->el[node_index] != NULL) {
      printf("Token %d : |%s|\n", count, cur_node->el[node_index]);
      count++;
    } else {
      return;
    }

    node_index++;
    if (node_index >= TOK_NODE_ELEMENTS) {
      cur_node = cur_node->next;
      node_index = 0;
    }
  }
}

void
Tokenizer::ReUse()
{
  tok_node *cur_node = &start_node;

  while (cur_node != NULL) {
    if (options & COPY_TOKS) {
      for (int i = 0; i < TOK_NODE_ELEMENTS; i++)
        ats_free(cur_node->el[i]);
    }
    memset(cur_node->el, 0, sizeof(char *) * TOK_NODE_ELEMENTS);
    cur_node = cur_node->next;
  }

  numValidTokens = 0;
  add_node = &start_node;
  add_index = 0;
}
<|endoftext|>


<commit_before>#include <vtkVersion.h>
#include <vtkSmartPointer.h>

#include <vtkSurfaceReconstructionFilter.h>
#include <vtkProgrammableSource.h>
#include <vtkContourFilter.h>
#include <vtkReverseSense.h>
#include <vtkPolyDataMapper.h>
#include <vtkProperty.h>
#include <vtkPolyData.h>
#include <vtkCamera.h>
#include <vtkRenderer.h>
#include <vtkRenderWindow.h>
#include <vtkRenderWindowInteractor.h>
#include <vtkSphereSource.h>
#include <vtkXMLPolyDataReader.h>

#include <vtkNamedColors.h>

int main(int argc, char *argv[])
{

  vtkSmartPointer<vtkNamedColors> colors =
    vtkSmartPointer<vtkNamedColors>::New();

  vtkSmartPointer<vtkPolyData> input;
  if(argc > 1)
  {
    vtkSmartPointer<vtkXMLPolyDataReader> reader =
      vtkSmartPointer<vtkXMLPolyDataReader>::New();
    reader->SetFileName(argv[1]);
    reader->Update();
    input = reader->GetOutput();
  }
  else
  {
    vtkSmartPointer<vtkSphereSource> sphereSource =
      vtkSmartPointer<vtkSphereSource>::New();
    sphereSource->Update();
    input = sphereSource->GetOutput();
  }

  vtkSmartPointer<vtkPolyData> polydata =
    vtkSmartPointer<vtkPolyData>::New();
  polydata->SetPoints(input->GetPoints());

  // Construct the surface and create isosurface.
  vtkSmartPointer<vtkSurfaceReconstructionFilter> surf =
    vtkSmartPointer<vtkSurfaceReconstructionFilter>::New();
  surf->SetInputData(polydata);

  vtkSmartPointer<vtkContourFilter> cf =
    vtkSmartPointer<vtkContourFilter>::New();
  cf->SetInputConnection(surf->GetOutputPort());
  cf->SetValue(0, 0.0);

  // Sometimes the contouring algorithm can create a volume whose gradient
  // vector and ordering of polygon (using the right hand rule) are
  // inconsistent. vtkReverseSense cures this problem.
  vtkSmartPointer<vtkReverseSense> reverse =
    vtkSmartPointer<vtkReverseSense>::New();
  reverse->SetInputConnection(cf->GetOutputPort());
  reverse->ReverseCellsOn();
  reverse->ReverseNormalsOn();

  vtkSmartPointer<vtkPolyDataMapper> map =
    vtkSmartPointer<vtkPolyDataMapper>::New();
  map->SetInputConnection(reverse->GetOutputPort());
  map->ScalarVisibilityOff();

  vtkSmartPointer<vtkActor> surfaceActor =
    vtkSmartPointer<vtkActor>::New();
  surfaceActor->SetMapper(map);
  surfaceActor->GetProperty()->SetDiffuseColor(colors->GetColor3d("Tomato").GetData());
  surfaceActor->GetProperty()->SetSpecularColor(colors->GetColor3d("Seashell").GetData());
  surfaceActor->GetProperty()->SetSpecular(.4);
  surfaceActor->GetProperty()->SetSpecularPower(50);

  // Create the RenderWindow, Renderer and both Actors
  vtkSmartPointer<vtkRenderer> renderer =
    vtkSmartPointer<vtkRenderer>::New();
  vtkSmartPointer<vtkRenderWindow> renderWindow =
    vtkSmartPointer<vtkRenderWindow>::New();
  renderWindow->AddRenderer(renderer);
  renderWindow->SetSize(640, 480);

  vtkSmartPointer<vtkRenderWindowInteractor> interactor =
    vtkSmartPointer<vtkRenderWindowInteractor>::New();
  interactor->SetRenderWindow(renderWindow);

  // Add the actors to the renderer, set the background and size
  renderer->AddActor(surfaceActor);
  renderer->SetBackground(colors->GetColor3d("Burlywood").GetData());

  renderWindow->Render();
  interactor->Start();

  return EXIT_SUCCESS;

}
<commit_msg>BUG: Bad return<commit_after>#include <vtkVersion.h>
#include <vtkSmartPointer.h>

#include <vtkSurfaceReconstructionFilter.h>
#include <vtkProgrammableSource.h>
#include <vtkContourFilter.h>
#include <vtkReverseSense.h>
#include <vtkPolyDataMapper.h>
#include <vtkProperty.h>
#include <vtkPolyData.h>
#include <vtkCamera.h>
#include <vtkRenderer.h>
#include <vtkRenderWindow.h>
#include <vtkRenderWindowInteractor.h>
#include <vtkSphereSource.h>
#include <vtkXMLPolyDataReader.h>

#include <vtkNamedColors.h>

int main(int argc, char *argv[])
{

  vtkSmartPointer<vtkNamedColors> colors =
    vtkSmartPointer<vtkNamedColors>::New();

  vtkSmartPointer<vtkPolyData> input;
  if(argc > 1)
  {
    vtkSmartPointer<vtkXMLPolyDataReader> reader =
      vtkSmartPointer<vtkXMLPolyDataReader>::New();
    reader->SetFileName(argv[1]);
    reader->Update();
    input = reader->GetOutput();
  }
  else
  {
    vtkSmartPointer<vtkSphereSource> sphereSource =
      vtkSmartPointer<vtkSphereSource>::New();
    sphereSource->Update();
    input = sphereSource->GetOutput();
  }

  vtkSmartPointer<vtkPolyData> polydata =
    vtkSmartPointer<vtkPolyData>::New();
  polydata->SetPoints(input->GetPoints());

  // Construct the surface and create isosurface.
  vtkSmartPointer<vtkSurfaceReconstructionFilter> surf =
    vtkSmartPointer<vtkSurfaceReconstructionFilter>::New();
  surf->SetInputData(polydata);

  vtkSmartPointer<vtkContourFilter> cf =
    vtkSmartPointer<vtkContourFilter>::New();
  cf->SetInputConnection(surf->GetOutputPort());
  cf->SetValue(0, 0.0);

  // Sometimes the contouring algorithm can create a volume whose gradient
  // vector and ordering of polygon (using the right hand rule) are
  // inconsistent. vtkReverseSense cures this problem.
  vtkSmartPointer<vtkReverseSense> reverse =
    vtkSmartPointer<vtkReverseSense>::New();
  reverse->SetInputConnection(cf->GetOutputPort());
  reverse->ReverseCellsOn();
  reverse->ReverseNormalsOn();

  vtkSmartPointer<vtkPolyDataMapper> map =
    vtkSmartPointer<vtkPolyDataMapper>::New();
  map->SetInputConnection(reverse->GetOutputPort());
  map->ScalarVisibilityOff();

  vtkSmartPointer<vtkActor> surfaceActor =
    vtkSmartPointer<vtkActor>::New();
  surfaceActor->SetMapper(map);
  surfaceActor->GetProperty()->SetDiffuseColor(colors->GetColor3d("Tomato").GetData());
  surfaceActor->GetProperty()->SetSpecularColor(colors->GetColor3d("Seashell").GetData());
  surfaceActor->GetProperty()->SetSpecular(.4);
  surfaceActor->GetProperty()->SetSpecularPower(50);

  // Create the RenderWindow, Renderer and both Actors
  vtkSmartPointer<vtkRenderer> renderer =
    vtkSmartPointer<vtkRenderer>::New();
  vtkSmartPointer<vtkRenderWindow> renderWindow =
    vtkSmartPointer<vtkRenderWindow>::New();
  renderWindow->AddRenderer(renderer);
  renderWindow->SetSize(640, 480);

  vtkSmartPointer<vtkRenderWindowInteractor> interactor =
    vtkSmartPointer<vtkRenderWindowInteractor>::New();
  interactor->SetRenderWindow(renderWindow);

  // Add the actors to the renderer, set the background and size
  renderer->AddActor(surfaceActor);
  renderer->SetBackground(colors->GetColor3d("Burlywood").GetData());

  renderWindow->Render();
  interactor->Start();

  return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>#include "stdafx.h"

#include "OpenSubtitlesFile.h"

#include <algorithm>
#include <cctype>
#include <fstream>
#include <sstream>
#include <string>

namespace {

/*
 *  from mpv/sub/sd_ass.c
 * ass_to_plaintext() was written by wm4 and he says it can be under LGPL
 */
std::string ass_to_plaintext(const char *in)
{
    std::string result;

    bool in_tag = false;
    const char *open_tag_pos = nullptr;
    bool in_drawing = false;
    while (*in) {
        if (in_tag) {
            if (in[0] == '}') {
                in += 1;
                in_tag = false;
            } else if (in[0] == '\\' && in[1] == 'p') {
                in += 2;
                // Skip text between \pN and \p0 tags. A \p without a number
                // is the same as \p0, and leading 0s are also allowed.
                in_drawing = false;
                while (in[0] >= '0' && in[0] <= '9') {
                    if (in[0] != '0')
                        in_drawing = true;
                    in += 1;
                }
            } else {
                in += 1;
            }
        } else {
            if (in[0] == '\\' && (in[1] == 'N' || in[1] == 'n')) {
                in += 2;
                result += '\n';
            } else if (in[0] == '\\' && in[1] == 'h') {
                in += 2;
                result += ' ';
            } else if (in[0] == '{') {
                open_tag_pos = in;
                in += 1;
                in_tag = true;
            } else {
                if (!in_drawing)
                    result += in[0];
                in += 1;
            }
        }
    }
    // A '{' without a closing '}' is always visible.
    if (in_tag) {
        result += open_tag_pos;
    }

    return result;
}

CString ChangePathExtension(const TCHAR* videoPathName, const TCHAR* ext)
{
    CString subRipPathName(videoPathName);
    PathRemoveExtension(subRipPathName.GetBuffer());
    subRipPathName.ReleaseBuffer();
    subRipPathName += ext;
    return subRipPathName;
}

// https://chromium.googlesource.com/chromium/src/third_party/+/refs/heads/master/unrar/src/unicode.cpp
// Source data can be both with and without UTF-8 BOM.
bool IsTextUtf8(const char *Src, size_t SrcSize)
{
    while (SrcSize-- > 0)
    {
        int C = *(Src++);
        int HighOne = 0; // Number of leftmost '1' bits.
        for (int Mask = 0x80; Mask != 0 && (C & Mask) != 0; Mask >>= 1)
            HighOne++;
        if (HighOne == 1 || HighOne > 4)
            return false;
        while (--HighOne > 0)
            if (SrcSize-- == 0 || (*(Src++) & 0xc0) != 0x80)
                return false;
    }
    return true;
}

bool IsTextUtf8(const std::string& Src)
{
    return IsTextUtf8(Src.c_str(), Src.length());
}

bool OpenSubRipFile(std::istream& s,
    bool& unicodeSubtitles,
    AddIntervalCallback addIntervalCallback)
{
    bool autoDetectedUnicode = true;
    bool ok = false;
    std::string buffer;
    while (std::getline(s, buffer))
    {
        if (std::find_if(buffer.begin(), buffer.end(), [](unsigned char c) { return !std::isspace(c); })
            == buffer.end())
        {
            continue;
        }

        if (!std::getline(s, buffer))
            break;

        int startHr, startMin, startSec, startMsec;
        int endHr, endMin, endSec, endMsec;

        if (sscanf_s(
            buffer.c_str(),
            "%d:%d:%d,%d --> %d:%d:%d,%d",
            &startHr, &startMin, &startSec, &startMsec,
            &endHr, &endMin, &endSec, &endMsec) != 8)
        {
            if (std::find_if(buffer.begin(), buffer.end(), [](unsigned char c) { return !std::isspace(c); })
                == buffer.end())
            {
                continue;
            }
            break;
        }

        const double start = startHr * 3600 + startMin * 60 + startSec + startMsec / 1000.;
        const double end = endHr * 3600 + endMin * 60 + endSec + endMsec / 1000.;

        std::string subtitle;
        while (std::getline(s, buffer) && !buffer.empty())
        {
            subtitle += buffer;
            subtitle += '\n'; // The last '\n' is for aggregating overlapped subtitles (if any)
        }

        if (!unicodeSubtitles && autoDetectedUnicode)
            autoDetectedUnicode = IsTextUtf8(subtitle);

        if (!subtitle.empty())
        {
            addIntervalCallback(start, end, subtitle);
            ok = true;
        }
    }

    if (!unicodeSubtitles)
        unicodeSubtitles = autoDetectedUnicode;

    return ok;
}

bool OpenSubStationAlphaFile(std::istream& s,
    bool& unicodeSubtitles,
    AddIntervalCallback addIntervalCallback)
{
    bool autoDetectedUnicode = true;
    bool ok = false;
    std::string buffer;
    while (std::getline(s, buffer))
    {
        std::istringstream ss(buffer);

        std::getline(ss, buffer, ':');

        if (buffer != "Dialogue")
            continue;

        double start, end;
        bool skip = false;
        for (int i = 0; i < 9; ++i) // TODO indices from Format?
        {
            std::getline(ss, buffer, ',');
            if (i == 1 || i == 2)
            {
                int hr, min, sec;
                char msecString[10]{};
                if (sscanf_s(
                    buffer.c_str(),
                    "%d:%d:%d.%9s",
                    &hr, &min, &sec, msecString, (unsigned)_countof(msecString)) != 4)
                {
                    return true;
                }

                double msec = 0;
                if (const auto msecStringLen = strlen(msecString))
                {
                    msec = atoi(msecString) / pow(10, msecStringLen);
                }

                ((i == 1) ? start : end)
                    = hr * 3600 + min * 60 + sec + msec;
            }
            else if (i == 3 && buffer == "OP_kar")
            {
                skip = true;
                break;
            }
        }

        if (skip)
            continue;

        std::getline(ss, buffer, {});
        std::string subtitle = ass_to_plaintext(buffer.c_str());

        if (!unicodeSubtitles && autoDetectedUnicode)
            autoDetectedUnicode = IsTextUtf8(subtitle);

        if (!subtitle.empty())
        {
            subtitle += '\n'; // The last '\n' is for aggregating overlapped subtitles (if any)
            addIntervalCallback(start, end, subtitle);
            ok = true;
        }
    }

    if (!unicodeSubtitles)
        unicodeSubtitles = autoDetectedUnicode;

    return ok;
}

template<char C>
class FilterBuf : public std::streambuf
{
    char readBuf_;
    const char* pExternBuf_;

    int_type underflow() override
    {
        if (gptr() == &readBuf_)
            return traits_type::to_int_type(readBuf_);

        for (; *pExternBuf_ == C; ++pExternBuf_);

        if (*pExternBuf_ == '\0')
            return traits_type::eof();

        int_type nextChar = *pExternBuf_++;

        readBuf_ = traits_type::to_char_type(nextChar);

        setg(&readBuf_, &readBuf_, &readBuf_ + 1);
        return traits_type::to_int_type(readBuf_);
    }

public:
    explicit FilterBuf(const char* pExternBuf)
        : pExternBuf_(pExternBuf)
    {
        setg(nullptr, nullptr, nullptr);
    }
};

bool OpenSubFile(
    bool(*doOpenSubFile)(std::istream&, bool&, AddIntervalCallback),
    const TCHAR* videoPathName,
    bool& unicodeSubtitles,
    AddIntervalCallback addIntervalCallback)
{
    do
    {
        std::ifstream s(videoPathName);
        if (!s)
            return false;

        unicodeSubtitles = false;
        const char ch = s.peek();
        if (ch == char(0xFF))
        {
            s.get();
            if (char(s.peek()) == char(0xFE))
            {
                break; // go to unicode part
            }
            s.unget();
        }
        else if (ch == char(0xEF))
        {
            s.get();
            if (char(s.peek()) == char(0xBB))
            {
                s.get();
                if (char(s.peek()) == char(0xBF))
                {
                    unicodeSubtitles = true;
                }
                else
                {
                    s.unget();
                    s.unget();
                }
            }
            else
                s.unget();
        }

        return doOpenSubFile(s, unicodeSubtitles, addIntervalCallback);

    } while (false);

    std::ifstream s(videoPathName, std::ios::binary);
    if (!s)
        return false;

    s.seekg(0, std::ios::end);
    const auto size = static_cast<size_t>(s.tellg()) - 2;
    s.seekg(2, std::ios::beg);

    std::wstring str(size / 2 + 1, L'\0');

    s.read(static_cast<char*>(static_cast<void*>(str.data())), size);

    ATL::CW2A text(str.c_str(), CP_UTF8);
    FilterBuf<'\r'> buf(text);

    std::iostream ss(&buf);

    unicodeSubtitles = true;

    return doOpenSubFile(ss, unicodeSubtitles, addIntervalCallback);
}

} // namespace

bool OpenSubtitlesFile(const TCHAR* videoPathName,
    bool& unicodeSubtitles,
    AddIntervalCallback addIntervalCallback)
{
    const auto extension = PathFindExtension(videoPathName);
    if (!_tcsicmp(extension, _T(".srt"))
        && OpenSubFile(OpenSubRipFile, videoPathName, unicodeSubtitles, addIntervalCallback))
    {
        return true;
    }

    return OpenSubFile(OpenSubStationAlphaFile, videoPathName, unicodeSubtitles, addIntervalCallback);
}

bool OpenMatchingSubtitlesFile(const TCHAR* videoPathName,
    bool& unicodeSubtitles,
    AddIntervalCallback addIntervalCallback)
{
    for (auto ext : { _T(".ass"), _T(".ssa") })
    {
        if (OpenSubFile(OpenSubStationAlphaFile, ChangePathExtension(videoPathName, ext), unicodeSubtitles, addIntervalCallback))
            return true;
    }

    const auto ext = ChangePathExtension(videoPathName, _T(".srt"));
    return OpenSubFile(OpenSubRipFile, ext, unicodeSubtitles, addIntervalCallback)
        || OpenSubFile(OpenSubStationAlphaFile, ext, unicodeSubtitles, addIntervalCallback);
}
<commit_msg>another correction<commit_after>#include "stdafx.h"

#include "OpenSubtitlesFile.h"

#include <algorithm>
#include <cctype>
#include <fstream>
#include <sstream>
#include <string>

namespace {

/*
 *  from mpv/sub/sd_ass.c
 * ass_to_plaintext() was written by wm4 and he says it can be under LGPL
 */
std::string ass_to_plaintext(const char *in)
{
    std::string result;

    bool in_tag = false;
    const char *open_tag_pos = nullptr;
    bool in_drawing = false;
    while (*in) {
        if (in_tag) {
            if (in[0] == '}') {
                in += 1;
                in_tag = false;
            } else if (in[0] == '\\' && in[1] == 'p') {
                in += 2;
                // Skip text between \pN and \p0 tags. A \p without a number
                // is the same as \p0, and leading 0s are also allowed.
                in_drawing = false;
                while (in[0] >= '0' && in[0] <= '9') {
                    if (in[0] != '0')
                        in_drawing = true;
                    in += 1;
                }
            } else {
                in += 1;
            }
        } else {
            if (in[0] == '\\' && (in[1] == 'N' || in[1] == 'n')) {
                in += 2;
                result += '\n';
            } else if (in[0] == '\\' && in[1] == 'h') {
                in += 2;
                result += ' ';
            } else if (in[0] == '{') {
                open_tag_pos = in;
                in += 1;
                in_tag = true;
            } else {
                if (!in_drawing)
                    result += in[0];
                in += 1;
            }
        }
    }
    // A '{' without a closing '}' is always visible.
    if (in_tag) {
        result += open_tag_pos;
    }

    return result;
}

CString ChangePathExtension(const TCHAR* videoPathName, const TCHAR* ext)
{
    CString subRipPathName(videoPathName);
    PathRemoveExtension(subRipPathName.GetBuffer());
    subRipPathName.ReleaseBuffer();
    subRipPathName += ext;
    return subRipPathName;
}

// https://chromium.googlesource.com/chromium/src/third_party/+/refs/heads/master/unrar/src/unicode.cpp
// Source data can be both with and without UTF-8 BOM.
bool IsTextUtf8(const char *Src, size_t SrcSize)
{
    while (SrcSize-- > 0)
    {
        int C = *(Src++);
        int HighOne = 0; // Number of leftmost '1' bits.
        for (int Mask = 0x80; Mask != 0 && (C & Mask) != 0; Mask >>= 1)
            HighOne++;
        if (HighOne == 1 || HighOne > 4)
            return false;
        while (--HighOne > 0)
            if (SrcSize-- == 0 || (*(Src++) & 0xc0) != 0x80)
                return false;
    }
    return true;
}

bool IsTextUtf8(const std::string& Src)
{
    return IsTextUtf8(Src.c_str(), Src.length());
}

bool OpenSubRipFile(std::istream& s,
    bool& unicodeSubtitles,
    AddIntervalCallback addIntervalCallback)
{
    bool autoDetectedUnicode = true;
    bool ok = false;
    std::string buffer;
    while (std::getline(s, buffer))
    {
        if (std::find_if(buffer.begin(), buffer.end(), [](unsigned char c) { return !std::isspace(c); })
            == buffer.end())
        {
            continue;
        }

        if (!std::getline(s, buffer))
            break;

        int startHr, startMin, startSec, startMsec;
        int endHr, endMin, endSec, endMsec;

        if (sscanf_s(
            buffer.c_str(),
            "%d:%d:%d,%d --> %d:%d:%d,%d",
            &startHr, &startMin, &startSec, &startMsec,
            &endHr, &endMin, &endSec, &endMsec) != 8)
        {
            if (std::find_if(buffer.begin(), buffer.end(), [](unsigned char c) { return !std::isspace(c); })
                == buffer.end())
            {
                continue;
            }
            break;
        }

        const double start = startHr * 3600 + startMin * 60 + startSec + startMsec / 1000.;
        const double end = endHr * 3600 + endMin * 60 + endSec + endMsec / 1000.;

        std::string subtitle;
        while (std::getline(s, buffer)
            && std::find_if(buffer.begin(), buffer.end(), [](unsigned char c) { return !std::isspace(c); })
            != buffer.end())
        {
            subtitle += buffer;
            subtitle += '\n'; // The last '\n' is for aggregating overlapped subtitles (if any)
        }

        if (!unicodeSubtitles && autoDetectedUnicode)
            autoDetectedUnicode = IsTextUtf8(subtitle);

        if (!subtitle.empty())
        {
            addIntervalCallback(start, end, subtitle);
            ok = true;
        }
    }

    if (!unicodeSubtitles)
        unicodeSubtitles = autoDetectedUnicode;

    return ok;
}

bool OpenSubStationAlphaFile(std::istream& s,
    bool& unicodeSubtitles,
    AddIntervalCallback addIntervalCallback)
{
    bool autoDetectedUnicode = true;
    bool ok = false;
    std::string buffer;
    while (std::getline(s, buffer))
    {
        std::istringstream ss(buffer);

        std::getline(ss, buffer, ':');

        if (buffer != "Dialogue")
            continue;

        double start, end;
        bool skip = false;
        for (int i = 0; i < 9; ++i) // TODO indices from Format?
        {
            std::getline(ss, buffer, ',');
            if (i == 1 || i == 2)
            {
                int hr, min, sec;
                char msecString[10]{};
                if (sscanf_s(
                    buffer.c_str(),
                    "%d:%d:%d.%9s",
                    &hr, &min, &sec, msecString, (unsigned)_countof(msecString)) != 4)
                {
                    return true;
                }

                double msec = 0;
                if (const auto msecStringLen = strlen(msecString))
                {
                    msec = atoi(msecString) / pow(10, msecStringLen);
                }

                ((i == 1) ? start : end)
                    = hr * 3600 + min * 60 + sec + msec;
            }
            else if (i == 3 && buffer == "OP_kar")
            {
                skip = true;
                break;
            }
        }

        if (skip)
            continue;

        std::getline(ss, buffer, {});
        std::string subtitle = ass_to_plaintext(buffer.c_str());

        if (!unicodeSubtitles && autoDetectedUnicode)
            autoDetectedUnicode = IsTextUtf8(subtitle);

        if (!subtitle.empty())
        {
            subtitle += '\n'; // The last '\n' is for aggregating overlapped subtitles (if any)
            addIntervalCallback(start, end, subtitle);
            ok = true;
        }
    }

    if (!unicodeSubtitles)
        unicodeSubtitles = autoDetectedUnicode;

    return ok;
}

template<char C>
class FilterBuf : public std::streambuf
{
    char readBuf_;
    const char* pExternBuf_;

    int_type underflow() override
    {
        if (gptr() == &readBuf_)
            return traits_type::to_int_type(readBuf_);

        for (; *pExternBuf_ == C; ++pExternBuf_);

        if (*pExternBuf_ == '\0')
            return traits_type::eof();

        int_type nextChar = *pExternBuf_++;

        readBuf_ = traits_type::to_char_type(nextChar);

        setg(&readBuf_, &readBuf_, &readBuf_ + 1);
        return traits_type::to_int_type(readBuf_);
    }

public:
    explicit FilterBuf(const char* pExternBuf)
        : pExternBuf_(pExternBuf)
    {
        setg(nullptr, nullptr, nullptr);
    }
};

bool OpenSubFile(
    bool(*doOpenSubFile)(std::istream&, bool&, AddIntervalCallback),
    const TCHAR* videoPathName,
    bool& unicodeSubtitles,
    AddIntervalCallback addIntervalCallback)
{
    do
    {
        std::ifstream s(videoPathName);
        if (!s)
            return false;

        unicodeSubtitles = false;
        const char ch = s.peek();
        if (ch == char(0xFF))
        {
            s.get();
            if (char(s.peek()) == char(0xFE))
            {
                break; // go to unicode part
            }
            s.unget();
        }
        else if (ch == char(0xEF))
        {
            s.get();
            if (char(s.peek()) == char(0xBB))
            {
                s.get();
                if (char(s.peek()) == char(0xBF))
                {
                    unicodeSubtitles = true;
                }
                else
                {
                    s.unget();
                    s.unget();
                }
            }
            else
                s.unget();
        }

        return doOpenSubFile(s, unicodeSubtitles, addIntervalCallback);

    } while (false);

    std::ifstream s(videoPathName, std::ios::binary);
    if (!s)
        return false;

    s.seekg(0, std::ios::end);
    const auto size = static_cast<size_t>(s.tellg()) - 2;
    s.seekg(2, std::ios::beg);

    std::wstring str(size / 2 + 1, L'\0');

    s.read(static_cast<char*>(static_cast<void*>(str.data())), size);

    ATL::CW2A text(str.c_str(), CP_UTF8);
    FilterBuf<'\r'> buf(text);

    std::iostream ss(&buf);

    unicodeSubtitles = true;

    return doOpenSubFile(ss, unicodeSubtitles, addIntervalCallback);
}

} // namespace

bool OpenSubtitlesFile(const TCHAR* videoPathName,
    bool& unicodeSubtitles,
    AddIntervalCallback addIntervalCallback)
{
    const auto extension = PathFindExtension(videoPathName);
    if (!_tcsicmp(extension, _T(".srt"))
        && OpenSubFile(OpenSubRipFile, videoPathName, unicodeSubtitles, addIntervalCallback))
    {
        return true;
    }

    return OpenSubFile(OpenSubStationAlphaFile, videoPathName, unicodeSubtitles, addIntervalCallback);
}

bool OpenMatchingSubtitlesFile(const TCHAR* videoPathName,
    bool& unicodeSubtitles,
    AddIntervalCallback addIntervalCallback)
{
    for (auto ext : { _T(".ass"), _T(".ssa") })
    {
        if (OpenSubFile(OpenSubStationAlphaFile, ChangePathExtension(videoPathName, ext), unicodeSubtitles, addIntervalCallback))
            return true;
    }

    const auto ext = ChangePathExtension(videoPathName, _T(".srt"));
    return OpenSubFile(OpenSubRipFile, ext, unicodeSubtitles, addIntervalCallback)
        || OpenSubFile(OpenSubStationAlphaFile, ext, unicodeSubtitles, addIntervalCallback);
}
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2012 Stanford University
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR(S) DISCLAIM ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL AUTHORS BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

#include <cassert>
#include <cstdio>
#include <cstdlib>
#include <cstring>

#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <signal.h>

#include <sys/types.h>
#include <sys/socket.h>

#include "sshclient.h"
#include "sshrepo.h"
#include "util.h"

#define D_READ 0
#define D_WRITE 1

/*
 * SshClient
 */
SshClient::SshClient(const std::string &remotePath)
    : fdFromChild(-1), fdToChild(-1), childPid(-1)
{
    assert(Util_IsPathRemote(remotePath.c_str()));
    size_t pos = remotePath.find(':');
    remoteHost = remotePath.substr(0, pos);
    remoteRepo = remotePath.substr(pos+1);
}

SshClient::~SshClient()
{
    if (childPid > 0) {
        //kill(childPid, SIGINT);
        close(fdToChild);
        // Wait for child to die
        while (kill(childPid, 0)) {
            // TODO timeout
        }
    }

    childPid = -1;
}

int SshClient::connect()
{
    int pipe_to_child[2], pipe_from_child[2];
    if (pipe(pipe_to_child) < 0) {
        perror("pipe");
        return -errno;
    }
    if (pipe(pipe_from_child) < 0) {
        perror("pipe");
        return -errno;
    }

    childPid = fork();
    if (childPid < 0) {
        perror("fork");
        return -errno;
    }
    else if (childPid == 0) {
        // This is the child process
        if (close(pipe_to_child[D_WRITE]) < 0 ||
                close(pipe_from_child[D_READ]) < 0) {
            perror("close");
            return -errno;
        }

        // dup pipes into stdin/out
        if (dup2(pipe_to_child[D_READ], STDIN_FILENO) < 0) {
            perror("dup2");
            return -errno;
        }
        if (dup2(pipe_from_child[D_WRITE], STDOUT_FILENO) < 0) {
            perror("dup2");
            return -errno;
        }

        // close pipe fds (already duped)
        if (pipe_to_child[D_READ] != STDIN_FILENO) {
            if (close(pipe_to_child[D_READ]) < 0) {
                perror("close"); return -errno;
            }
        }
        if (pipe_from_child[D_WRITE] != STDOUT_FILENO) {
            if (close(pipe_from_child[D_WRITE]) < 0) {
                perror("close"); return -errno;
            }
        }

        // This is needed for SSH to function properly (according to rsync)
        Util_SetBlocking(STDIN_FILENO, true);

        // Run ssh
        execlp("/usr/bin/ssh", "ssh", remoteHost.c_str(), "ori", "sshserver",
                remoteRepo.c_str(), NULL);
        perror("execlp failed");
        return -errno;
    }

    // This is the parent
    if (close(pipe_to_child[D_READ]) < 0 ||
            close(pipe_from_child[D_WRITE]) < 0) {
        perror("close");
        exit(errno);
    }

    fdToChild = pipe_to_child[D_WRITE];
    fdFromChild = pipe_from_child[D_READ];

    // TODO: sync here
    //sleep(2);

    // SSH sets stderr to nonblock, possibly screwing up stdout (according to
    // rsync)
    Util_SetBlocking(STDERR_FILENO, true);

    // Wait for READY from server
    std::string ready;
    recvResponse(ready);
    if (ready != "READY\n") {
        return -1;
    }

    return 0;
}

bool SshClient::connected() {
    return fdFromChild != -1;
}

void SshClient::sendCommand(const std::string &command) {
    assert(connected());
    write(fdToChild, command.data(), command.length());
    write(fdToChild, "\n", 1);
    fsync(fdToChild);
}

void SshClient::recvResponse(std::string &out) {
    assert(connected());

    out.clear();
    while (true) {
        fd_set read_set;
        FD_ZERO(&read_set);
        FD_SET(fdFromChild, &read_set);

        int ret = select(fdFromChild+1, &read_set, NULL, NULL, NULL);
        if (ret == 1) {
            char buf[512];

            // Ready to read from child
            ssize_t read_n = read(fdFromChild, buf, 512);
            if (read_n < 0) {
                perror("read");
                out.clear();
                return;
            }

            //printf("Read '%s'\n", buf);

            size_t curr_size = out.size();
            out.resize(curr_size + read_n);
            memcpy(&out[curr_size], buf, read_n);

            if (strcmp(&out[out.size()-5], "DONE\n") == 0) {
                return;
            }
            else if (strcmp(&out[out.size()-6], "READY\n") == 0) {
                return;
            }
        }
        else if (ret == -1) {
            perror("select");
            out.clear();
            return;
        }
    }
}

/*
 * SshResponseParser
 */
SshResponseParser::SshResponseParser(const std::string &text)
    : text(text), off(0)
{
}

bool SshResponseParser::ended() const {
    return off >= text.size();
}

bool SshResponseParser::nextLine(std::string &line) {
    if (off >= text.size()) return false;

    size_t oldOff = off;
    while (off < text.size()) {
        if (text[off] == '\n') {
            off++;
            line = text.substr(oldOff, (off-oldOff-1));
            if (line == "DONE")
                return false;
            return true;
        }
        off++;
    }
    line = text.substr(oldOff, (off-oldOff-1));

    if (line == "DONE")
        return false;
    return true;
}

size_t SshResponseParser::getDataLength(const std::string &line) const {
    size_t len = 0;
    if (sscanf(line.c_str(), "DATA %lu", &len) != 1) {
        return 0;
    }
    return len;
}

std::string SshResponseParser::getData(size_t len) {
    assert(len > 0);
    assert(off + len <= text.size());
    size_t oldOff = off;
    off += len;
    return text.substr(oldOff, len);
}

bool SshResponseParser::loadObjectInfo(ObjectInfo &info) {
    std::string line;
    nextLine(line); // hash
    if (line == "DONE") return false;

    assert(line.size() == 64); // 2*SHA256_DIGEST_LENGTH
    info.hash = line.data();

    nextLine(line); // type
    info.type = Object::getTypeForStr(line.c_str());
    assert(info.type != Object::Null);

    nextLine(line); // flags
    sscanf(line.c_str(), "%X", &info.flags);

    nextLine(line); // payload_size
    sscanf(line.c_str(), "%lu", &info.payload_size);
    assert(info.payload_size != (size_t)-1);

    return true;
}

/*
 * cmd_sshclient
 */
int cmd_sshclient(int argc, const char *argv[]) {
    if (argc < 2) {
        printf("Usage: ori sshclient [username@]hostname\n");
        exit(1);
    }

    SshClient client = SshClient(std::string(argv[1])
                                  + ":/Users/fyhuang/Projects/ori/tr");
    if (client.connect() < 0) {
        printf("Error connecting to %s\n", argv[1]);
        exit(1);
    }

    printf("Connected\n");

    SshRepo repo(&client);
    std::vector<Commit> commits = repo.listCommits();
    for (size_t i = 0; i < commits.size(); i++) {
        printf("%ld\n", commits[i].getTime());
    }

    //Object::ObjectInfo info("b7287ce2bca00e9b78555dba3ec7b013415425f7ffd6628b6ed68dcfba699426");
    //std::string data;
    //printf("type: %d\nflags: %08X\npayload_size: %lu\n", info.type, info.flags,
    //        info.payload_size);

    return 0;

    // Simple command-line client
    while (true) {
        char buf[256];
        char *status = fgets(buf, 256, stdin);
        if (status == NULL) {
            if (feof(stdin)) break;
            if (ferror(stdin)) {
                perror("fgets");
                break;
            }
        }
        else {
            buf[strlen(buf)-1] = '\0'; // remove trailing \n
            client.sendCommand(buf);
            std::string resp;
            client.recvResponse(resp);
            if (resp.size() == 0) {
                break;
            }
            write(STDOUT_FILENO, resp.data(), resp.size());
        }
    }

    printf("Terminating SSH connection...\n");
    return 0;
}
<commit_msg>Fixing an overly aggressive assert in SSH due to the empty object.<commit_after>/*
 * Copyright (c) 2012 Stanford University
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR(S) DISCLAIM ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL AUTHORS BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

#include <cassert>
#include <cstdio>
#include <cstdlib>
#include <cstring>

#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <signal.h>

#include <sys/types.h>
#include <sys/socket.h>

#include "sshclient.h"
#include "sshrepo.h"
#include "util.h"

#define D_READ 0
#define D_WRITE 1

/*
 * SshClient
 */
SshClient::SshClient(const std::string &remotePath)
    : fdFromChild(-1), fdToChild(-1), childPid(-1)
{
    assert(Util_IsPathRemote(remotePath.c_str()));
    size_t pos = remotePath.find(':');
    remoteHost = remotePath.substr(0, pos);
    remoteRepo = remotePath.substr(pos+1);
}

SshClient::~SshClient()
{
    if (childPid > 0) {
        //kill(childPid, SIGINT);
        close(fdToChild);
        // Wait for child to die
        while (kill(childPid, 0)) {
            // TODO timeout
        }
    }

    childPid = -1;
}

int SshClient::connect()
{
    int pipe_to_child[2], pipe_from_child[2];
    if (pipe(pipe_to_child) < 0) {
        perror("pipe");
        return -errno;
    }
    if (pipe(pipe_from_child) < 0) {
        perror("pipe");
        return -errno;
    }

    childPid = fork();
    if (childPid < 0) {
        perror("fork");
        return -errno;
    }
    else if (childPid == 0) {
        // This is the child process
        if (close(pipe_to_child[D_WRITE]) < 0 ||
                close(pipe_from_child[D_READ]) < 0) {
            perror("close");
            return -errno;
        }

        // dup pipes into stdin/out
        if (dup2(pipe_to_child[D_READ], STDIN_FILENO) < 0) {
            perror("dup2");
            return -errno;
        }
        if (dup2(pipe_from_child[D_WRITE], STDOUT_FILENO) < 0) {
            perror("dup2");
            return -errno;
        }

        // close pipe fds (already duped)
        if (pipe_to_child[D_READ] != STDIN_FILENO) {
            if (close(pipe_to_child[D_READ]) < 0) {
                perror("close"); return -errno;
            }
        }
        if (pipe_from_child[D_WRITE] != STDOUT_FILENO) {
            if (close(pipe_from_child[D_WRITE]) < 0) {
                perror("close"); return -errno;
            }
        }

        // This is needed for SSH to function properly (according to rsync)
        Util_SetBlocking(STDIN_FILENO, true);

        // Run ssh
        execlp("/usr/bin/ssh", "ssh", remoteHost.c_str(), "ori", "sshserver",
                remoteRepo.c_str(), NULL);
        perror("execlp failed");
        return -errno;
    }

    // This is the parent
    if (close(pipe_to_child[D_READ]) < 0 ||
            close(pipe_from_child[D_WRITE]) < 0) {
        perror("close");
        exit(errno);
    }

    fdToChild = pipe_to_child[D_WRITE];
    fdFromChild = pipe_from_child[D_READ];

    // TODO: sync here
    //sleep(2);

    // SSH sets stderr to nonblock, possibly screwing up stdout (according to
    // rsync)
    Util_SetBlocking(STDERR_FILENO, true);

    // Wait for READY from server
    std::string ready;
    recvResponse(ready);
    if (ready != "READY\n") {
        return -1;
    }

    return 0;
}

bool SshClient::connected() {
    return fdFromChild != -1;
}

void SshClient::sendCommand(const std::string &command) {
    assert(connected());
    write(fdToChild, command.data(), command.length());
    write(fdToChild, "\n", 1);
    fsync(fdToChild);
}

void SshClient::recvResponse(std::string &out) {
    assert(connected());

    out.clear();
    while (true) {
        fd_set read_set;
        FD_ZERO(&read_set);
        FD_SET(fdFromChild, &read_set);

        int ret = select(fdFromChild+1, &read_set, NULL, NULL, NULL);
        if (ret == 1) {
            char buf[512];

            // Ready to read from child
            ssize_t read_n = read(fdFromChild, buf, 512);
            if (read_n < 0) {
                perror("read");
                out.clear();
                return;
            }

            //printf("Read '%s'\n", buf);

            size_t curr_size = out.size();
            out.resize(curr_size + read_n);
            memcpy(&out[curr_size], buf, read_n);

            if (strcmp(&out[out.size()-5], "DONE\n") == 0) {
                return;
            }
            else if (strcmp(&out[out.size()-6], "READY\n") == 0) {
                return;
            }
        }
        else if (ret == -1) {
            perror("select");
            out.clear();
            return;
        }
    }
}

/*
 * SshResponseParser
 */
SshResponseParser::SshResponseParser(const std::string &text)
    : text(text), off(0)
{
}

bool SshResponseParser::ended() const {
    return off >= text.size();
}

bool SshResponseParser::nextLine(std::string &line) {
    if (off >= text.size()) return false;

    size_t oldOff = off;
    while (off < text.size()) {
        if (text[off] == '\n') {
            off++;
            line = text.substr(oldOff, (off-oldOff-1));
            if (line == "DONE")
                return false;
            return true;
        }
        off++;
    }
    line = text.substr(oldOff, (off-oldOff-1));

    if (line == "DONE")
        return false;
    return true;
}

size_t SshResponseParser::getDataLength(const std::string &line) const {
    size_t len = 0;
    if (sscanf(line.c_str(), "DATA %lu", &len) != 1) {
        return 0;
    }
    return len;
}

std::string SshResponseParser::getData(size_t len) {
    /*
     * XXX: Replace this assert once we guarentee that the empty object
     * e3b0.... is never transmitted over the wire.
     *
     * assert(len > 0);
     */
    assert(off + len <= text.size());
    size_t oldOff = off;
    off += len;
    return text.substr(oldOff, len);
}

bool SshResponseParser::loadObjectInfo(ObjectInfo &info) {
    std::string line;
    nextLine(line); // hash
    if (line == "DONE") return false;

    assert(line.size() == 64); // 2*SHA256_DIGEST_LENGTH
    info.hash = line.data();

    nextLine(line); // type
    info.type = Object::getTypeForStr(line.c_str());
    assert(info.type != Object::Null);

    nextLine(line); // flags
    sscanf(line.c_str(), "%X", &info.flags);

    nextLine(line); // payload_size
    sscanf(line.c_str(), "%lu", &info.payload_size);
    assert(info.payload_size != (size_t)-1);

    return true;
}

/*
 * cmd_sshclient
 */
int cmd_sshclient(int argc, const char *argv[]) {
    if (argc < 2) {
        printf("Usage: ori sshclient [username@]hostname\n");
        exit(1);
    }

    SshClient client = SshClient(std::string(argv[1])
                                  + ":/Users/fyhuang/Projects/ori/tr");
    if (client.connect() < 0) {
        printf("Error connecting to %s\n", argv[1]);
        exit(1);
    }

    printf("Connected\n");

    SshRepo repo(&client);
    std::vector<Commit> commits = repo.listCommits();
    for (size_t i = 0; i < commits.size(); i++) {
        printf("%ld\n", commits[i].getTime());
    }

    //Object::ObjectInfo info("b7287ce2bca00e9b78555dba3ec7b013415425f7ffd6628b6ed68dcfba699426");
    //std::string data;
    //printf("type: %d\nflags: %08X\npayload_size: %lu\n", info.type, info.flags,
    //        info.payload_size);

    return 0;

    // Simple command-line client
    while (true) {
        char buf[256];
        char *status = fgets(buf, 256, stdin);
        if (status == NULL) {
            if (feof(stdin)) break;
            if (ferror(stdin)) {
                perror("fgets");
                break;
            }
        }
        else {
            buf[strlen(buf)-1] = '\0'; // remove trailing \n
            client.sendCommand(buf);
            std::string resp;
            client.recvResponse(resp);
            if (resp.size() == 0) {
                break;
            }
            write(STDOUT_FILENO, resp.data(), resp.size());
        }
    }

    printf("Terminating SSH connection...\n");
    return 0;
}
<|endoftext|>