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

#include "media/base/video_frame_impl.h"
#include "media/filters/ffmpeg_common.h"
#include "media/filters/ffmpeg_demuxer.h"
#include "media/filters/ffmpeg_video_decoder.h"

namespace media {

FFmpegVideoDecoder::FFmpegVideoDecoder()
    : DecoderBase<VideoDecoder, VideoFrame>(NULL),
      width_(0),
      height_(0) {
}

FFmpegVideoDecoder::~FFmpegVideoDecoder() {
}

// static
bool FFmpegVideoDecoder::IsMediaFormatSupported(const MediaFormat& format) {
  std::string mime_type;
  return format.GetAsString(MediaFormat::kMimeType, &mime_type) &&
      mime_type::kFFmpegVideo == mime_type;
}

bool FFmpegVideoDecoder::OnInitialize(DemuxerStream* demuxer_stream) {
  scoped_refptr<FFmpegDemuxerStream> ffmpeg_demuxer_stream;
  if (!demuxer_stream->QueryInterface(&ffmpeg_demuxer_stream)) {
    return false;
  }

  AVStream* av_stream = ffmpeg_demuxer_stream->av_stream();

  width_ = av_stream->codec->width;
  height_ = av_stream->codec->height;

  media_format_.SetAsString(MediaFormat::kMimeType,
                            mime_type::kUncompressedVideo);
  media_format_.SetAsInteger(MediaFormat::kWidth, width_);
  media_format_.SetAsInteger(MediaFormat::kHeight, height_);

  codec_context_ = ffmpeg_demuxer_stream->av_stream()->codec;
  AVCodec* codec = avcodec_find_decoder(codec_context_->codec_id);
  if (!codec || avcodec_open(codec_context_, codec) < 0) {
    host_->Error(media::PIPELINE_ERROR_DECODE);
    return false;
  }
  return true;
}

void FFmpegVideoDecoder::OnDecode(Buffer* buffer) {
  // Check for end of stream.
  // TODO(scherkus): check for end of stream.

  // Queue the incoming timestamp.
  TimeTuple times;
  times.timestamp = buffer->GetTimestamp();
  times.duration = buffer->GetDuration();
  time_queue_.push(times);

  // Cast everything to FFmpeg types.
  const uint8_t* data_in = buffer->GetData();
  const size_t size_in = buffer->GetDataSize();

  int decoded = 0;
  AVFrame yuv_frame;
  avcodec_get_frame_defaults(&yuv_frame);
  int result = avcodec_decode_video(codec_context_, &yuv_frame, &decoded,
                                    data_in, size_in);

  if (result < 0) {
    host_->Error(PIPELINE_ERROR_DECODE);
    return;
  }

  if (result == 0 || decoded == 0) {
    return;
  }

  // J (Motion JPEG) versions of YUV are full range 0..255.
  // Regular (MPEG) YUV is 16..240.
  // For now we will ignore the distinction and treat them the same.

  VideoSurface::Format surface_format;
  switch (codec_context_->pix_fmt) {
    case PIX_FMT_YUV420P:
    case PIX_FMT_YUVJ420P:
      surface_format = VideoSurface::YV12;
      break;
    case PIX_FMT_YUV422P:
    case PIX_FMT_YUVJ422P:
      surface_format = VideoSurface::YV16;
      break;
    default:
      // TODO(scherkus): More formats here?
      NOTREACHED();
      host_->Error(PIPELINE_ERROR_DECODE);
      return;
  }
  if (!EnqueueVideoFrame(surface_format, yuv_frame)) {
    host_->Error(PIPELINE_ERROR_DECODE);
  }
}

bool FFmpegVideoDecoder::EnqueueVideoFrame(VideoSurface::Format surface_format,
                                           const AVFrame& frame) {
  // Dequeue the next time tuple and create a VideoFrame object with
  // that timestamp and duration.
  TimeTuple time = time_queue_.top();
  time_queue_.pop();

  scoped_refptr<VideoFrame> video_frame;
  VideoFrameImpl::CreateFrame(surface_format, width_, height_,
                              time.timestamp, time.duration, &video_frame);
  if (!video_frame) {
    return false;
  }
  // Copy the frame data since FFmpeg reuses internal buffers for AVFrame
  // output, meaning the data is only valid until the next
  // avcodec_decode_video() call.
  // TODO(scherkus): figure out pre-allocation/buffer cycling scheme.
  // TODO(scherkus): is there a cleaner way to figure out the # of planes?
  VideoSurface surface;
  if (!video_frame->Lock(&surface)) {
    return false;
  }
  CopyPlane(VideoSurface::kYPlane, surface, frame);
  CopyPlane(VideoSurface::kUPlane, surface, frame);
  CopyPlane(VideoSurface::kVPlane, surface, frame);
  video_frame->Unlock();
  EnqueueResult(video_frame);
  return true;
}

void FFmpegVideoDecoder::CopyPlane(size_t plane,
                                   const VideoSurface& surface,
                                   const AVFrame& frame) {
  DCHECK(surface.width % 4 == 0);
  DCHECK(surface.height % 2 == 0);
  const uint8* source = frame.data[plane];
  const size_t source_stride = frame.linesize[plane];
  uint8* dest = surface.data[plane];
  const size_t dest_stride = surface.strides[plane];
  size_t bytes_per_line = surface.width;
  size_t copy_lines = surface.height;
  if (plane != VideoSurface::kYPlane) {
    bytes_per_line /= 2;
    if (surface.format == VideoSurface::YV12) {
      copy_lines /= 2;
    }
  }
  DCHECK(bytes_per_line <= source_stride && bytes_per_line <= dest_stride);
  for (size_t i = 0; i < copy_lines; ++i) {
    memcpy(dest, source, bytes_per_line);
    source += source_stride;
    dest += dest_stride;
  }
}

}  // namespace
<commit_msg>Fast flag for h264 improves performance of loop filter. Increases performance by about 10% with minimal quality loss.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.  Use of this
// source code is governed by a BSD-style license that can be found in the
// LICENSE file.

#include "media/base/video_frame_impl.h"
#include "media/filters/ffmpeg_common.h"
#include "media/filters/ffmpeg_demuxer.h"
#include "media/filters/ffmpeg_video_decoder.h"

namespace media {

FFmpegVideoDecoder::FFmpegVideoDecoder()
    : DecoderBase<VideoDecoder, VideoFrame>(NULL),
      width_(0),
      height_(0) {
}

FFmpegVideoDecoder::~FFmpegVideoDecoder() {
}

// static
bool FFmpegVideoDecoder::IsMediaFormatSupported(const MediaFormat& format) {
  std::string mime_type;
  return format.GetAsString(MediaFormat::kMimeType, &mime_type) &&
      mime_type::kFFmpegVideo == mime_type;
}

bool FFmpegVideoDecoder::OnInitialize(DemuxerStream* demuxer_stream) {
  scoped_refptr<FFmpegDemuxerStream> ffmpeg_demuxer_stream;
  if (!demuxer_stream->QueryInterface(&ffmpeg_demuxer_stream)) {
    return false;
  }

  AVStream* av_stream = ffmpeg_demuxer_stream->av_stream();

  width_ = av_stream->codec->width;
  height_ = av_stream->codec->height;

  media_format_.SetAsString(MediaFormat::kMimeType,
                            mime_type::kUncompressedVideo);
  media_format_.SetAsInteger(MediaFormat::kWidth, width_);
  media_format_.SetAsInteger(MediaFormat::kHeight, height_);

  codec_context_ = ffmpeg_demuxer_stream->av_stream()->codec;
  codec_context_->flags2 |= CODEC_FLAG2_FAST;  // Enable faster H264 decode.
  AVCodec* codec = avcodec_find_decoder(codec_context_->codec_id);
  if (!codec || avcodec_open(codec_context_, codec) < 0) {
    host_->Error(media::PIPELINE_ERROR_DECODE);
    return false;
  }
  return true;
}

void FFmpegVideoDecoder::OnDecode(Buffer* buffer) {
  // Check for end of stream.
  // TODO(scherkus): check for end of stream.

  // Queue the incoming timestamp.
  TimeTuple times;
  times.timestamp = buffer->GetTimestamp();
  times.duration = buffer->GetDuration();
  time_queue_.push(times);

  // Cast everything to FFmpeg types.
  const uint8_t* data_in = buffer->GetData();
  const size_t size_in = buffer->GetDataSize();

  int decoded = 0;
  AVFrame yuv_frame;
  avcodec_get_frame_defaults(&yuv_frame);
  int result = avcodec_decode_video(codec_context_, &yuv_frame, &decoded,
                                    data_in, size_in);

  if (result < 0) {
    host_->Error(PIPELINE_ERROR_DECODE);
    return;
  }

  if (result == 0 || decoded == 0) {
    return;
  }

  // J (Motion JPEG) versions of YUV are full range 0..255.
  // Regular (MPEG) YUV is 16..240.
  // For now we will ignore the distinction and treat them the same.

  VideoSurface::Format surface_format;
  switch (codec_context_->pix_fmt) {
    case PIX_FMT_YUV420P:
    case PIX_FMT_YUVJ420P:
      surface_format = VideoSurface::YV12;
      break;
    case PIX_FMT_YUV422P:
    case PIX_FMT_YUVJ422P:
      surface_format = VideoSurface::YV16;
      break;
    default:
      // TODO(scherkus): More formats here?
      NOTREACHED();
      host_->Error(PIPELINE_ERROR_DECODE);
      return;
  }
  if (!EnqueueVideoFrame(surface_format, yuv_frame)) {
    host_->Error(PIPELINE_ERROR_DECODE);
  }
}

bool FFmpegVideoDecoder::EnqueueVideoFrame(VideoSurface::Format surface_format,
                                           const AVFrame& frame) {
  // Dequeue the next time tuple and create a VideoFrame object with
  // that timestamp and duration.
  TimeTuple time = time_queue_.top();
  time_queue_.pop();

  scoped_refptr<VideoFrame> video_frame;
  VideoFrameImpl::CreateFrame(surface_format, width_, height_,
                              time.timestamp, time.duration, &video_frame);
  if (!video_frame) {
    return false;
  }
  // Copy the frame data since FFmpeg reuses internal buffers for AVFrame
  // output, meaning the data is only valid until the next
  // avcodec_decode_video() call.
  // TODO(scherkus): figure out pre-allocation/buffer cycling scheme.
  // TODO(scherkus): is there a cleaner way to figure out the # of planes?
  VideoSurface surface;
  if (!video_frame->Lock(&surface)) {
    return false;
  }
  CopyPlane(VideoSurface::kYPlane, surface, frame);
  CopyPlane(VideoSurface::kUPlane, surface, frame);
  CopyPlane(VideoSurface::kVPlane, surface, frame);
  video_frame->Unlock();
  EnqueueResult(video_frame);
  return true;
}

void FFmpegVideoDecoder::CopyPlane(size_t plane,
                                   const VideoSurface& surface,
                                   const AVFrame& frame) {
  DCHECK(surface.width % 4 == 0);
  DCHECK(surface.height % 2 == 0);
  const uint8* source = frame.data[plane];
  const size_t source_stride = frame.linesize[plane];
  uint8* dest = surface.data[plane];
  const size_t dest_stride = surface.strides[plane];
  size_t bytes_per_line = surface.width;
  size_t copy_lines = surface.height;
  if (plane != VideoSurface::kYPlane) {
    bytes_per_line /= 2;
    if (surface.format == VideoSurface::YV12) {
      copy_lines /= 2;
    }
  }
  DCHECK(bytes_per_line <= source_stride && bytes_per_line <= dest_stride);
  for (size_t i = 0; i < copy_lines; ++i) {
    memcpy(dest, source, bytes_per_line);
    source += source_stride;
    dest += dest_stride;
  }
}

}  // namespace
<|endoftext|>


<commit_before>/*****************************************************************************
 * PokerTH - The open source texas holdem engine                             *
 * Copyright (C) 2006-2011 Felix Hammer, Florian Thauer, Lothar May          *
 *                                                                           *
 * This program is free software: you can redistribute it and/or modify      *
 * it under the terms of the GNU Affero General Public License as            *
 * published by the Free Software Foundation, either version 3 of the        *
 * License, or (at your option) any later version.                           *
 *                                                                           *
 * This program 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 Affero General Public License for more details.                       *
 *                                                                           *
 * You should have received a copy of the GNU Affero General Public License  *
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.     *
 *****************************************************************************/
#include "sdlplayer.h"

#ifndef ANDROID
#if (defined __APPLE__)
#include <SDL.h>
#else
#include <SDL/SDL.h>
#endif
#endif

using namespace std;

SDLPlayer::SDLPlayer(ConfigFile *c)
#ifndef ANDROID
: soundData(NULL), currentChannel(0) , audioEnabled(0), myConfig(c), sound(NULL)
#endif
{
	myAppDataPath = QString::fromUtf8(myConfig->readConfigString("AppDataDir").c_str());
}

SDLPlayer::~SDLPlayer()
{
#ifndef ANDROID
	closeAudio();
#endif
}

void SDLPlayer::initAudio()
{
#ifndef ANDROID
	SDL_Init(SDL_INIT_AUDIO);
	if (!audioEnabled && myConfig->readConfigInt("PlaySoundEffects")) {
		int		audio_rate = 44100;
		Uint16	audio_format = AUDIO_S16; /* 16-bit stereo */
		int		audio_channels = 2;
		int		audio_buffers = 4096;
		sound = NULL;

		if( Mix_OpenAudio(audio_rate, audio_format, audio_channels, audio_buffers) == 0) {
			Mix_QuerySpec(&audio_rate, &audio_format, &audio_channels);
			audioEnabled = 1;
		}
		else {
			qDebug() << "Mix_OpenAudio() was not successfull, no sound possible :(";
		}
	}
#endif
}

void SDLPlayer::playSound(string audioString, int playerID)
{
#ifndef ANDROID
	initAudio();
	if(audioEnabled && myConfig->readConfigInt("PlaySoundEffects")) {

		QFile myFile(myAppDataPath + "sounds/default/" + QString::fromStdString(audioString)+".wav");

		if(myFile.open(QIODevice::ReadOnly)) {

			//set 3d position for player
			int position = 0;
			int distance = 0;

			switch (playerID) {

			case 0: {
				position = 180;
				distance = 10;
			}
			break;
			case 1: {
				position = 281;
				distance = 50;
			}
			break;
			case 2: {
				position = 315;
				distance = 120;
			}
			break;
			case 3: {
				position = 338;
				distance = 160;
			}
			break;
			case 4: {
				position = 23;
				distance = 160;
			}
			break;
			case 5: {
				position = 45;
				distance = 120;
			}
			break;
			case 6: {
				position = 79;
				distance = 50;
			}
			break;
			default: {
				position = 0;
				distance = 0;
			}
			break;
			}

			QDataStream in(&myFile);
			soundData = new Uint8[(int)myFile.size()];
			in.readRawData( (char*)soundData, (int)myFile.size() );
			sound = Mix_QuickLoad_WAV(soundData);

			// set channel 0 to settings volume
			Mix_Volume(-1,myConfig->readConfigInt("SoundVolume")*10);

			// set 3d effect
			if(!Mix_SetPosition(0, position, distance)) {
				printf("Mix_SetPosition: %s\n", Mix_GetError());
				// no position effect, is it ok?
			}
			currentChannel = Mix_PlayChannel(-1, sound,0);
		}

		//TESTING: release audio after every sound when there is no other sound currently played
		if(SDL_GetAudioStatus() != SDL_AUDIO_PLAYING) {
			closeAudio();
		}
	}
#endif
}

void SDLPlayer::closeAudio()
{
#ifndef ANDROID
	if(audioEnabled) {
		Mix_HaltChannel(currentChannel);
		Mix_FreeChunk(sound);
		sound = NULL;
		delete[] soundData;
		soundData = NULL;
		Mix_CloseAudio();
		audioEnabled = false;
	}

	SDL_Quit();
#endif
}
<commit_msg>fix android build<commit_after>/*****************************************************************************
 * PokerTH - The open source texas holdem engine                             *
 * Copyright (C) 2006-2011 Felix Hammer, Florian Thauer, Lothar May          *
 *                                                                           *
 * This program is free software: you can redistribute it and/or modify      *
 * it under the terms of the GNU Affero General Public License as            *
 * published by the Free Software Foundation, either version 3 of the        *
 * License, or (at your option) any later version.                           *
 *                                                                           *
 * This program 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 Affero General Public License for more details.                       *
 *                                                                           *
 * You should have received a copy of the GNU Affero General Public License  *
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.     *
 *****************************************************************************/
#include "sdlplayer.h"

#ifndef ANDROID
#if (defined __APPLE__)
#include <SDL.h>
#else
#include <SDL/SDL.h>
#endif
#endif

using namespace std;

SDLPlayer::SDLPlayer(ConfigFile *c)
#ifndef ANDROID
: soundData(NULL), currentChannel(0) , audioEnabled(0), myConfig(c), sound(NULL)
#endif
{
#ifndef ANDROID
	myAppDataPath = QString::fromUtf8(myConfig->readConfigString("AppDataDir").c_str());
#endif
}

SDLPlayer::~SDLPlayer()
{
#ifndef ANDROID
	closeAudio();
#endif
}

void SDLPlayer::initAudio()
{
#ifndef ANDROID
	SDL_Init(SDL_INIT_AUDIO);
	if (!audioEnabled && myConfig->readConfigInt("PlaySoundEffects")) {
		int		audio_rate = 44100;
		Uint16	audio_format = AUDIO_S16; /* 16-bit stereo */
		int		audio_channels = 2;
		int		audio_buffers = 4096;
		sound = NULL;

		if( Mix_OpenAudio(audio_rate, audio_format, audio_channels, audio_buffers) == 0) {
			Mix_QuerySpec(&audio_rate, &audio_format, &audio_channels);
			audioEnabled = 1;
		}
		else {
			qDebug() << "Mix_OpenAudio() was not successfull, no sound possible :(";
		}
	}
#endif
}

void SDLPlayer::playSound(string audioString, int playerID)
{
#ifndef ANDROID
	initAudio();
	if(audioEnabled && myConfig->readConfigInt("PlaySoundEffects")) {

		QFile myFile(myAppDataPath + "sounds/default/" + QString::fromStdString(audioString)+".wav");

		if(myFile.open(QIODevice::ReadOnly)) {

			//set 3d position for player
			int position = 0;
			int distance = 0;

			switch (playerID) {

			case 0: {
				position = 180;
				distance = 10;
			}
			break;
			case 1: {
				position = 281;
				distance = 50;
			}
			break;
			case 2: {
				position = 315;
				distance = 120;
			}
			break;
			case 3: {
				position = 338;
				distance = 160;
			}
			break;
			case 4: {
				position = 23;
				distance = 160;
			}
			break;
			case 5: {
				position = 45;
				distance = 120;
			}
			break;
			case 6: {
				position = 79;
				distance = 50;
			}
			break;
			default: {
				position = 0;
				distance = 0;
			}
			break;
			}

			QDataStream in(&myFile);
			soundData = new Uint8[(int)myFile.size()];
			in.readRawData( (char*)soundData, (int)myFile.size() );
			sound = Mix_QuickLoad_WAV(soundData);

			// set channel 0 to settings volume
			Mix_Volume(-1,myConfig->readConfigInt("SoundVolume")*10);

			// set 3d effect
			if(!Mix_SetPosition(0, position, distance)) {
				printf("Mix_SetPosition: %s\n", Mix_GetError());
				// no position effect, is it ok?
			}
			currentChannel = Mix_PlayChannel(-1, sound,0);
		}

		//TESTING: release audio after every sound when there is no other sound currently played
		if(SDL_GetAudioStatus() != SDL_AUDIO_PLAYING) {
			closeAudio();
		}
	}
#endif
}

void SDLPlayer::closeAudio()
{
#ifndef ANDROID
	if(audioEnabled) {
		Mix_HaltChannel(currentChannel);
		Mix_FreeChunk(sound);
		sound = NULL;
		delete[] soundData;
		soundData = NULL;
		Mix_CloseAudio();
		audioEnabled = false;
	}

	SDL_Quit();
#endif
}
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2013-2015 John Connor (BM-NC49AxAjcqVcF5jNPu85Rb8MJ2d9JqZt)
 *
 * This file is part of vanillacoin.
 *
 * vanillacoin is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License with
 * additional permissions to the one published by the Free Software
 * Foundation, either version 3 of the License, or (at your option)
 * any later version. For more information see LICENSE.
 *
 * This program 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 Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */

#include <cassert>
#include <cstdlib>

#include <boost/asio.hpp>
#include <boost/format.hpp>

#include <coin/constants.hpp>
#include <coin/filesystem.hpp>
#include <coin/logger.hpp>

using namespace coin;

#if (defined _MSC_VER)
#include "Shlobj.h"
#define ERRNO GetLastError()
static int _mkdir(const char * path)
{
    std::wstring directory(path, path + strlen(path));

    return SHCreateDirectoryEx(NULL, directory.c_str(), NULL );
}
#define CREATE_DIRECTORY(P) _mkdir(P)
#else
#include <sys/stat.h>
#define ERRNO errno
#define ERROR_ALREADY_EXISTS EEXIST
static int _mkdir(const char * dir)
{
    char tmp[256];
    char * p = NULL;
    size_t len;

    snprintf(tmp, sizeof(tmp),"%s",dir);
    len = strlen(tmp);

    if (tmp[len - 1] == '/')
    {
        tmp[len - 1] = 0;
    }

    for (p = tmp + 1; *p; p++)
    {
        if (*p == '/')
        {
            *p = 0;

            mkdir(tmp, S_IRWXU);

            *p = '/';
        }
    }

    return mkdir(tmp, S_IRWXU);
}
#define CREATE_DIRECTORY(P) _mkdir(P)
#endif

int filesystem::error_already_exists = ERROR_ALREADY_EXISTS;

int filesystem::create_path(const std::string & path)
{
    if (CREATE_DIRECTORY(path.c_str()) == 0)
    {
        return 0;
    }

    return ERRNO;
}

bool filesystem::copy_file(const std::string & src, const std::string & dest)
{
    enum { buffer_length = 32768 };

    std::vector<char> buf(buffer_length);

    auto infile =- 1, outfile =- 1;

    if ((infile = ::open(src.c_str(), O_RDONLY)) < 0)
    {
        return false;
    }

    struct stat from_stat;

    if (::stat(src.c_str(), &from_stat)!= 0)
    {
        ::close(infile);

        return false;
    }

    if (from_stat.st_size > buf.size())
    {
        buf.resize(from_stat.st_size);
    }

    int oflag = O_CREAT | O_WRONLY | O_TRUNC;

    if ((outfile = ::open(dest.c_str(), oflag, from_stat.st_mode)) < 0)
    {
        int open_errno = errno;

        assert(infile >= 0);

        ::close(infile);

        errno = open_errno;

        return false;
    }

    ssize_t sz, read = 1, write;

    while (
        read > 0 && (read = ::read(infile, &buf[0], buffer_length)) > 0
        )
    {
        write = 0;

        do
        {
            if (
                (sz = ::write(outfile, &buf[0] + write, read - write)) < 0
                )
            {
                read = sz;

                break;
            }

            write += sz;

        } while (write < read);
    }

    if (::close(infile) < 0)
    {
        read = -1;
    }

    if (::close(outfile) < 0)
    {
        read = -1;
    }

    return read >= 0;
}

std::string filesystem::data_path()
{
    static const std::string bundle_id = constants::client_name;
    std::string ret;
#if (defined _MSC_VER)
    ret += getenv("APPDATA");
    ret += "\\" + bundle_id + "\\";
#elif (defined __APPLE__)
    ret = home_path();
    ret += "Library/";
    ret += "Application Support/";
    ret += bundle_id + "/";
#elif (defined __ANDROID__)
    ret = home_path() + bundle_id + "/";
#else
    ret = home_path();
    ret += "." + bundle_id + "/data/";
#endif
    return ret;
}

std::string filesystem::home_path()
{
    std::string ret;
#if (defined __ANDROID__)
    static const std::string android_package = constants::client_name;
    ret = "/data/data/" + android_package;
#else
    if (std::getenv("HOME"))
    {
        ret = std::getenv("HOME");
    }
    else if (std::getenv("USERPOFILE"))
    {
        ret = std::getenv("USERPOFILE");
    }
    else if (std::getenv("HOMEDRIVE") && std::getenv("HOMEPATH"))
    {
        ret = (
            boost::format("%1%%2%") % std::getenv("HOMEDRIVE") %
            std::getenv("HOMEPATH")
        ).str();
    }
    else
    {
        ret = ".";
    }
#endif // __ANDROID__
#if (defined _MSC_VER)
    return ret + "\\";
#else
    return ret + "/";
#endif
}
<commit_msg>implemented file copy support for making wallet backups<commit_after>/*
 * Copyright (c) 2013-2015 John Connor (BM-NC49AxAjcqVcF5jNPu85Rb8MJ2d9JqZt)
 *
 * This file is part of vanillacoin.
 *
 * vanillacoin is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License with
 * additional permissions to the one published by the Free Software
 * Foundation, either version 3 of the License, or (at your option)
 * any later version. For more information see LICENSE.
 *
 * This program 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 Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */

#include <cassert>
#include <cstdlib>

#include <boost/asio.hpp>
#include <boost/format.hpp>

#include <coin/constants.hpp>
#include <coin/filesystem.hpp>
#include <coin/logger.hpp>

using namespace coin;

#if (defined _MSC_VER)
#include "Shlobj.h"
#define ERRNO GetLastError()
static int _mkdir(const char * path)
{
    std::wstring directory(path, path + strlen(path));

    return SHCreateDirectoryEx(NULL, directory.c_str(), NULL );
}
#define CREATE_DIRECTORY(P) _mkdir(P)
#else
#include <sys/stat.h>
#define ERRNO errno
#define ERROR_ALREADY_EXISTS EEXIST
static int _mkdir(const char * dir)
{
    char tmp[256];
    char * p = NULL;
    size_t len;

    snprintf(tmp, sizeof(tmp),"%s",dir);
    len = strlen(tmp);

    if (tmp[len - 1] == '/')
    {
        tmp[len - 1] = 0;
    }

    for (p = tmp + 1; *p; p++)
    {
        if (*p == '/')
        {
            *p = 0;

            mkdir(tmp, S_IRWXU);

            *p = '/';
        }
    }

    return mkdir(tmp, S_IRWXU);
}
#define CREATE_DIRECTORY(P) _mkdir(P)
#endif

int filesystem::error_already_exists = ERROR_ALREADY_EXISTS;

int filesystem::create_path(const std::string & path)
{
    if (CREATE_DIRECTORY(path.c_str()) == 0)
    {
        return 0;
    }

    return ERRNO;
}

bool filesystem::copy_file(const std::string & src, const std::string & dest)
{
    enum { buffer_length = 32768 };

    std::vector<char> buf(buffer_length);

    auto infile =- 1, outfile =- 1;

    if ((infile = ::open(src.c_str(), O_RDONLY)) < 0)
    {
        return false;
    }

    struct stat from_stat;

    if (::stat(src.c_str(), &from_stat)!= 0)
    {
        ::close(infile);

        return false;
    }

    int oflag = O_CREAT | O_WRONLY | O_TRUNC;

    if ((outfile = ::open(dest.c_str(), oflag, from_stat.st_mode)) < 0)
    {
        int open_errno = errno;

        assert(infile >= 0);

        ::close(infile);

        errno = open_errno;

        return false;
    }

    ssize_t sz, read = 1, write;

    while (
        read > 0 && (read = ::read(infile, &buf[0], buffer_length)) > 0
        )
    {
        write = 0;

        do
        {
            if (
                (sz = ::write(outfile, &buf[0] + write, read - write)) < 0
                )
            {
                read = sz;

                break;
            }

            write += sz;

        } while (write < read);
    }

    if (::close(infile) < 0)
    {
        read = -1;
    }

    if (::close(outfile) < 0)
    {
        read = -1;
    }

    return read >= 0;
}

std::string filesystem::data_path()
{
    static const std::string bundle_id = constants::client_name;
    std::string ret;
#if (defined _MSC_VER)
    ret += getenv("APPDATA");
    ret += "\\" + bundle_id + "\\";
#elif (defined __APPLE__)
    ret = home_path();
    ret += "Library/";
    ret += "Application Support/";
    ret += bundle_id + "/";
#elif (defined __ANDROID__)
    ret = home_path() + bundle_id + "/";
#else
    ret = home_path();
    ret += "." + bundle_id + "/data/";
#endif
    return ret;
}

std::string filesystem::home_path()
{
    std::string ret;
#if (defined __ANDROID__)
    static const std::string android_package = constants::client_name;
    ret = "/data/data/" + android_package;
#else
    if (std::getenv("HOME"))
    {
        ret = std::getenv("HOME");
    }
    else if (std::getenv("USERPOFILE"))
    {
        ret = std::getenv("USERPOFILE");
    }
    else if (std::getenv("HOMEDRIVE") && std::getenv("HOMEPATH"))
    {
        ret = (
            boost::format("%1%%2%") % std::getenv("HOMEDRIVE") %
            std::getenv("HOMEPATH")
        ).str();
    }
    else
    {
        ret = ".";
    }
#endif // __ANDROID__
#if (defined _MSC_VER)
    return ret + "\\";
#else
    return ret + "/";
#endif
}
<|endoftext|>


<commit_before>/*
 *  This file is part of Poedit (http://poedit.net)
 *
 *  Copyright (C) 1999-2015 Vaclav Slavik
 *
 *  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 <wx/filename.h>
#include <wx/log.h>
#include <wx/button.h>
#include <wx/panel.h>
#include <wx/stattext.h>
#include <wx/choice.h>
#include <wx/config.h>
#include <wx/sizer.h>
#include <wx/settings.h>
#include <wx/listctrl.h>
#include <wx/fontenum.h>
#include <wx/ffile.h>
#include <wx/utils.h>
#include <wx/stc/stc.h>

#include "fileviewer.h"
#include "hidpi.h"
#include "utility.h"

FileViewer::FileViewer(wxWindow *parent,
                       const wxString& basePath,
                       const wxArrayString& references,
                       int startAt)
        : wxFrame(parent, -1, _("Source file")),
          m_references(references)
{
    m_basePath = basePath;

    SetName("fileviewer");

    wxPanel *panel = new wxPanel(this, -1);
    wxSizer *sizer = new wxBoxSizer(wxVERTICAL);
    panel->SetSizer(sizer);

    wxSizer *barsizer = new wxBoxSizer(wxHORIZONTAL);
    sizer->Add(barsizer, wxSizerFlags().Expand().PXBorderAll());

    barsizer->Add(new wxStaticText(panel, wxID_ANY,
                                   _("Source file occurrence:")),
                  wxSizerFlags().Center().PXBorder(wxRIGHT));

    wxChoice *choice = new wxChoice(panel, wxID_ANY);
    barsizer->Add(choice, wxSizerFlags(1).Center());

    for (size_t i = 0; i < references.Count(); i++)
        choice->Append(references[i]);
    choice->SetSelection(startAt);

    wxButton *edit = new wxButton(panel, wxID_ANY, MSW_OR_OTHER(_("Open in editor"), _("Open in Editor")));
    barsizer->Add(edit, wxSizerFlags().Center().Border(wxLEFT, PX(10)));

    m_text = new wxStyledTextCtrl(panel, wxID_ANY,
                                  wxDefaultPosition, wxDefaultSize,
                                  wxBORDER_THEME);
    SetupTextCtrl();
    sizer->Add(m_text, 1, wxEXPAND);

    RestoreWindowState(this, wxSize(PX(600), PX(400)));

    wxSizer *topsizer = new wxBoxSizer(wxVERTICAL);
    topsizer->Add(panel, wxSizerFlags(1).Expand());
    SetSizer(topsizer);
    Layout();

    choice->Bind(wxEVT_CHOICE, &FileViewer::OnChoice, this);
    edit->Bind(wxEVT_BUTTON, &FileViewer::OnEditFile, this);

    ShowReference(m_references[startAt]);

#ifdef __WXOSX__
    wxAcceleratorEntry entries[] = {
        { wxACCEL_CMD,  'W', wxID_CLOSE }
    };
    wxAcceleratorTable accel(WXSIZEOF(entries), entries);
    SetAcceleratorTable(accel);

    Bind(wxEVT_MENU, [=](wxCommandEvent&){ Destroy(); }, wxID_CLOSE);
#endif
}

FileViewer::~FileViewer()
{
    SaveWindowState(this);
}

void FileViewer::SetupTextCtrl()
{
    wxStyledTextCtrl& t = *m_text;

    wxFont font = wxSystemSettings::GetFont(wxSYS_DEFAULT_GUI_FONT);

#ifdef __WXGTK__
    font.SetFaceName("monospace");
#else
    static const char *s_monospaced_fonts[] = {
#ifdef __WXMSW__
        "Consolas",
        "Lucida Console",
#endif
#ifdef __WXOSX__
        "Menlo",
        "Monaco",
#endif
        NULL
    };

    for ( const char **f = s_monospaced_fonts; *f; ++f )
    {
        if ( wxFontEnumerator::IsValidFacename(*f) )
        {
            font.SetFaceName(*f);
            break;
        }
    }
#endif

    // style used:
    wxString fontspec = wxString::Format("face:%s,size:%d",
                                         font.GetFaceName().c_str(),
                                         font.GetPointSize());
    const wxString DEFAULT     = fontspec + ",fore:black,back:white";
    const wxString STRING      = fontspec + ",bold,fore:#882d21";
    const wxString COMMENT     = fontspec + ",fore:#487e18";
    const wxString KEYWORD     = fontspec + ",fore:#2f00f9";
    const wxString LINENUMBERS = fontspec + ",fore:#5d8bab";

    // current line marker
    t.MarkerDefine(1, wxSTC_MARK_BACKGROUND, wxNullColour, wxColour(255,255,0));

    // set fonts
    t.StyleSetSpec(wxSTC_STYLE_DEFAULT, DEFAULT);
    t.StyleSetSpec(wxSTC_STYLE_LINENUMBER, LINENUMBERS);

    // line numbers margin size:
    t.SetMarginType(0, wxSTC_MARGIN_NUMBER);
    t.SetMarginWidth(0,
                     t.TextWidth(wxSTC_STYLE_LINENUMBER, "9999 "));
    t.SetMarginWidth(1, 0);
    t.SetMarginWidth(2, 3);

    // set syntax highlighting styling
    t.StyleSetSpec(wxSTC_C_STRING, STRING);
    t.StyleSetSpec(wxSTC_C_COMMENT, COMMENT);
    t.StyleSetSpec(wxSTC_C_COMMENTLINE, COMMENT);

    t.StyleSetSpec(wxSTC_P_STRING, STRING);
    t.StyleSetSpec(wxSTC_P_COMMENTLINE, COMMENT);
    t.StyleSetSpec(wxSTC_P_COMMENTBLOCK, COMMENT);

    t.StyleSetSpec(wxSTC_LUA_STRING, STRING);
    t.StyleSetSpec(wxSTC_LUA_LITERALSTRING, STRING);
    t.StyleSetSpec(wxSTC_LUA_COMMENT, COMMENT);
    t.StyleSetSpec(wxSTC_LUA_COMMENTLINE, COMMENT);

    t.StyleSetSpec(wxSTC_HPHP_HSTRING, STRING);
    t.StyleSetSpec(wxSTC_HPHP_SIMPLESTRING, STRING);
    t.StyleSetSpec(wxSTC_HPHP_COMMENT, COMMENT);
    t.StyleSetSpec(wxSTC_HPHP_COMMENTLINE, COMMENT);

    t.StyleSetSpec(wxSTC_TCL_COMMENT, COMMENT);
    t.StyleSetSpec(wxSTC_TCL_COMMENTLINE, COMMENT);
    t.StyleSetSpec(wxSTC_TCL_BLOCK_COMMENT, COMMENT);

    t.StyleSetSpec(wxSTC_PAS_STRING, STRING);
    t.StyleSetSpec(wxSTC_PAS_COMMENT, COMMENT);
    t.StyleSetSpec(wxSTC_PAS_COMMENT2, COMMENT);
    t.StyleSetSpec(wxSTC_PAS_COMMENTLINE, COMMENT);
}

int FileViewer::GetLexer(const wxString& ext)
{
    struct LexerInfo
    {
        const char *ext;
        int lexer;
    };

    static const LexerInfo s_lexer[] = {
        { "c", wxSTC_LEX_CPP },
        { "cpp", wxSTC_LEX_CPP },
        { "cc", wxSTC_LEX_CPP },
        { "cxx", wxSTC_LEX_CPP },
        { "h", wxSTC_LEX_CPP },
        { "hxx", wxSTC_LEX_CPP },
        { "hpp", wxSTC_LEX_CPP },
        { "py", wxSTC_LEX_PYTHON },
        { "htm", wxSTC_LEX_HTML },
        { "html", wxSTC_LEX_HTML },
        { "php", wxSTC_LEX_PHPSCRIPT },
        { "xml", wxSTC_LEX_XML },
        { "pas", wxSTC_LEX_PASCAL },
        { NULL, -1 }
    };

    wxString e = ext.Lower();

    for ( const LexerInfo *i = s_lexer; i->ext; ++i )
    {
        if ( e == wxString::FromAscii(i->ext) )
            return i->lexer;
    }

    return wxSTC_LEX_NULL;
}

wxFileName FileViewer::GetFilename(wxString ref) const
{
    if ( ref.length() >= 3 &&
         ref[1] == _T(':') &&
         (ref[2] == _T('\\') || ref[2] == _T('/')) )
    {
        // This is an absolute Windows path (c:\foo... or c:/foo...); fix
        // the latter case.
        ref.Replace("/", "\\");
    }

    wxPathFormat pathfmt = ref.Contains(_T('\\')) ? wxPATH_WIN : wxPATH_UNIX;
    wxFileName filename(ref.BeforeLast(_T(':')), pathfmt);

    if ( filename.IsRelative() )
    {
        wxFileName relative(filename);
        wxString basePath(m_basePath);

        // Sometimes, the path in source reference is not relative to the PO
        // file's location, but is relative to e.g. the root directory. See
        // https://code.djangoproject.com/ticket/13936 for exhaustive
        // discussion with plenty of examples.
        //
        // Deal with this by trying parent directories of m_basePath too. So if
        // a file named project/locales/cs/foo.po has a reference to src/main.c,
        // try not only project/locales/cs/src/main.c, but also
        // project/locales/src/main.c and project/src/main.c etc.
        while ( !basePath.empty() )
        {
            filename = relative;
            filename.MakeAbsolute(basePath);
            if ( filename.FileExists() )
            {
                break; // good, found the file
            }
            else
            {
                // remove the last path component
                size_t last = basePath.find_last_of("\\/");
                if ( last == wxString::npos )
                    break;
                else
                    basePath.erase(last);
            }
        }
    }

    return filename;
}

void FileViewer::ShowReference(const wxString& ref)
{
    const wxFileName filename = GetFilename(ref);
    wxFFile file;
    wxString data;

    if ( !filename.IsFileReadable() ||
         !file.Open(filename.GetFullPath()) ||
         !file.ReadAll(&data, wxConvAuto()) )
    {
        wxLogError(_("Error opening file %s!"), filename.GetFullPath().c_str());
        return;
    }

    m_current = ref;

    // support GNOME's xml2po's extension to references in the form of
    // filename:line(xml_node):
    wxString linenumStr = ref.AfterLast(_T(':')).BeforeFirst(_T('('));

    long linenum;
    if (!linenumStr.ToLong(&linenum))
        linenum = 0;

    m_text->SetReadOnly(false);
    m_text->SetValue(data);
    m_text->SetReadOnly(true);

    m_text->MarkerDeleteAll(1);
    m_text->MarkerAdd((int)linenum - 1, 1);

    // Center the highlighted line:
    int lineHeight = m_text->TextHeight((int)linenum);
    int linesInWnd = m_text->GetSize().y / lineHeight;
    m_text->ScrollToLine(wxMax(0, (int)linenum - linesInWnd/2));

}

void FileViewer::OnChoice(wxCommandEvent &event)
{
    ShowReference(m_references[event.GetSelection()]);
}

void FileViewer::OnEditFile(wxCommandEvent&)
{
    wxLaunchDefaultApplication(GetFilename(m_current).GetFullPath());
}
<commit_msg>Use smaller fonts on OS X in the fileviewer<commit_after>/*
 *  This file is part of Poedit (http://poedit.net)
 *
 *  Copyright (C) 1999-2015 Vaclav Slavik
 *
 *  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 <wx/filename.h>
#include <wx/log.h>
#include <wx/button.h>
#include <wx/panel.h>
#include <wx/stattext.h>
#include <wx/choice.h>
#include <wx/config.h>
#include <wx/sizer.h>
#include <wx/settings.h>
#include <wx/listctrl.h>
#include <wx/fontenum.h>
#include <wx/ffile.h>
#include <wx/utils.h>
#include <wx/stc/stc.h>

#include "fileviewer.h"
#include "hidpi.h"
#include "utility.h"

FileViewer::FileViewer(wxWindow *parent,
                       const wxString& basePath,
                       const wxArrayString& references,
                       int startAt)
        : wxFrame(parent, -1, _("Source file")),
          m_references(references)
{
    m_basePath = basePath;

    SetName("fileviewer");

    wxPanel *panel = new wxPanel(this, -1);
    wxSizer *sizer = new wxBoxSizer(wxVERTICAL);
    panel->SetSizer(sizer);
#ifdef __WXOSX__
    panel->SetWindowVariant(wxWINDOW_VARIANT_SMALL);
#endif

    wxSizer *barsizer = new wxBoxSizer(wxHORIZONTAL);
    sizer->Add(barsizer, wxSizerFlags().Expand().PXBorderAll());

    barsizer->Add(new wxStaticText(panel, wxID_ANY,
                                   _("Source file occurrence:")),
                  wxSizerFlags().Center().PXBorder(wxRIGHT));

    wxChoice *choice = new wxChoice(panel, wxID_ANY);
    barsizer->Add(choice, wxSizerFlags(1).Center());

    for (size_t i = 0; i < references.Count(); i++)
        choice->Append(references[i]);
    choice->SetSelection(startAt);

    wxButton *edit = new wxButton(panel, wxID_ANY, MSW_OR_OTHER(_("Open in editor"), _("Open in Editor")));
    barsizer->Add(edit, wxSizerFlags().Center().Border(wxLEFT, PX(10)));

    m_text = new wxStyledTextCtrl(panel, wxID_ANY,
                                  wxDefaultPosition, wxDefaultSize,
                                  wxBORDER_THEME);
    SetupTextCtrl();
    sizer->Add(m_text, 1, wxEXPAND);

    RestoreWindowState(this, wxSize(PX(600), PX(400)));

    wxSizer *topsizer = new wxBoxSizer(wxVERTICAL);
    topsizer->Add(panel, wxSizerFlags(1).Expand());
    SetSizer(topsizer);
    Layout();

    choice->Bind(wxEVT_CHOICE, &FileViewer::OnChoice, this);
    edit->Bind(wxEVT_BUTTON, &FileViewer::OnEditFile, this);

    ShowReference(m_references[startAt]);

#ifdef __WXOSX__
    wxAcceleratorEntry entries[] = {
        { wxACCEL_CMD,  'W', wxID_CLOSE }
    };
    wxAcceleratorTable accel(WXSIZEOF(entries), entries);
    SetAcceleratorTable(accel);

    Bind(wxEVT_MENU, [=](wxCommandEvent&){ Destroy(); }, wxID_CLOSE);
#endif
}

FileViewer::~FileViewer()
{
    SaveWindowState(this);
}

void FileViewer::SetupTextCtrl()
{
    wxStyledTextCtrl& t = *m_text;

    wxFont font = wxSystemSettings::GetFont(wxSYS_DEFAULT_GUI_FONT);

#ifdef __WXGTK__
    font.SetFaceName("monospace");
#else
    static const char *s_monospaced_fonts[] = {
#ifdef __WXMSW__
        "Consolas",
        "Lucida Console",
#endif
#ifdef __WXOSX__
        "Menlo",
        "Monaco",
#endif
        NULL
    };

    for ( const char **f = s_monospaced_fonts; *f; ++f )
    {
        if ( wxFontEnumerator::IsValidFacename(*f) )
        {
            font.SetFaceName(*f);
            break;
        }
    }
#endif

    // style used:
    wxString fontspec = wxString::Format("face:%s,size:%d",
                                         font.GetFaceName().c_str(),
                                      #ifdef __WXOSX__
                                         font.GetPointSize() - 1
                                      #else
                                         font.GetPointSize()
                                      #endif
                                         );
    const wxString DEFAULT     = fontspec + ",fore:black,back:white";
    const wxString STRING      = fontspec + ",bold,fore:#882d21";
    const wxString COMMENT     = fontspec + ",fore:#487e18";
    const wxString KEYWORD     = fontspec + ",fore:#2f00f9";
    const wxString LINENUMBERS = fontspec + ",fore:#5d8bab";

    // current line marker
    t.MarkerDefine(1, wxSTC_MARK_BACKGROUND, wxNullColour, wxColour(255,255,0));

    // set fonts
    t.StyleSetSpec(wxSTC_STYLE_DEFAULT, DEFAULT);
    t.StyleSetSpec(wxSTC_STYLE_LINENUMBER, LINENUMBERS);

    // line numbers margin size:
    t.SetMarginType(0, wxSTC_MARGIN_NUMBER);
    t.SetMarginWidth(0,
                     t.TextWidth(wxSTC_STYLE_LINENUMBER, "9999 "));
    t.SetMarginWidth(1, 0);
    t.SetMarginWidth(2, 3);

    // set syntax highlighting styling
    t.StyleSetSpec(wxSTC_C_STRING, STRING);
    t.StyleSetSpec(wxSTC_C_COMMENT, COMMENT);
    t.StyleSetSpec(wxSTC_C_COMMENTLINE, COMMENT);

    t.StyleSetSpec(wxSTC_P_STRING, STRING);
    t.StyleSetSpec(wxSTC_P_COMMENTLINE, COMMENT);
    t.StyleSetSpec(wxSTC_P_COMMENTBLOCK, COMMENT);

    t.StyleSetSpec(wxSTC_LUA_STRING, STRING);
    t.StyleSetSpec(wxSTC_LUA_LITERALSTRING, STRING);
    t.StyleSetSpec(wxSTC_LUA_COMMENT, COMMENT);
    t.StyleSetSpec(wxSTC_LUA_COMMENTLINE, COMMENT);

    t.StyleSetSpec(wxSTC_HPHP_HSTRING, STRING);
    t.StyleSetSpec(wxSTC_HPHP_SIMPLESTRING, STRING);
    t.StyleSetSpec(wxSTC_HPHP_COMMENT, COMMENT);
    t.StyleSetSpec(wxSTC_HPHP_COMMENTLINE, COMMENT);

    t.StyleSetSpec(wxSTC_TCL_COMMENT, COMMENT);
    t.StyleSetSpec(wxSTC_TCL_COMMENTLINE, COMMENT);
    t.StyleSetSpec(wxSTC_TCL_BLOCK_COMMENT, COMMENT);

    t.StyleSetSpec(wxSTC_PAS_STRING, STRING);
    t.StyleSetSpec(wxSTC_PAS_COMMENT, COMMENT);
    t.StyleSetSpec(wxSTC_PAS_COMMENT2, COMMENT);
    t.StyleSetSpec(wxSTC_PAS_COMMENTLINE, COMMENT);
}

int FileViewer::GetLexer(const wxString& ext)
{
    struct LexerInfo
    {
        const char *ext;
        int lexer;
    };

    static const LexerInfo s_lexer[] = {
        { "c", wxSTC_LEX_CPP },
        { "cpp", wxSTC_LEX_CPP },
        { "cc", wxSTC_LEX_CPP },
        { "cxx", wxSTC_LEX_CPP },
        { "h", wxSTC_LEX_CPP },
        { "hxx", wxSTC_LEX_CPP },
        { "hpp", wxSTC_LEX_CPP },
        { "py", wxSTC_LEX_PYTHON },
        { "htm", wxSTC_LEX_HTML },
        { "html", wxSTC_LEX_HTML },
        { "php", wxSTC_LEX_PHPSCRIPT },
        { "xml", wxSTC_LEX_XML },
        { "pas", wxSTC_LEX_PASCAL },
        { NULL, -1 }
    };

    wxString e = ext.Lower();

    for ( const LexerInfo *i = s_lexer; i->ext; ++i )
    {
        if ( e == wxString::FromAscii(i->ext) )
            return i->lexer;
    }

    return wxSTC_LEX_NULL;
}

wxFileName FileViewer::GetFilename(wxString ref) const
{
    if ( ref.length() >= 3 &&
         ref[1] == _T(':') &&
         (ref[2] == _T('\\') || ref[2] == _T('/')) )
    {
        // This is an absolute Windows path (c:\foo... or c:/foo...); fix
        // the latter case.
        ref.Replace("/", "\\");
    }

    wxPathFormat pathfmt = ref.Contains(_T('\\')) ? wxPATH_WIN : wxPATH_UNIX;
    wxFileName filename(ref.BeforeLast(_T(':')), pathfmt);

    if ( filename.IsRelative() )
    {
        wxFileName relative(filename);
        wxString basePath(m_basePath);

        // Sometimes, the path in source reference is not relative to the PO
        // file's location, but is relative to e.g. the root directory. See
        // https://code.djangoproject.com/ticket/13936 for exhaustive
        // discussion with plenty of examples.
        //
        // Deal with this by trying parent directories of m_basePath too. So if
        // a file named project/locales/cs/foo.po has a reference to src/main.c,
        // try not only project/locales/cs/src/main.c, but also
        // project/locales/src/main.c and project/src/main.c etc.
        while ( !basePath.empty() )
        {
            filename = relative;
            filename.MakeAbsolute(basePath);
            if ( filename.FileExists() )
            {
                break; // good, found the file
            }
            else
            {
                // remove the last path component
                size_t last = basePath.find_last_of("\\/");
                if ( last == wxString::npos )
                    break;
                else
                    basePath.erase(last);
            }
        }
    }

    return filename;
}

void FileViewer::ShowReference(const wxString& ref)
{
    const wxFileName filename = GetFilename(ref);
    wxFFile file;
    wxString data;

    if ( !filename.IsFileReadable() ||
         !file.Open(filename.GetFullPath()) ||
         !file.ReadAll(&data, wxConvAuto()) )
    {
        wxLogError(_("Error opening file %s!"), filename.GetFullPath().c_str());
        return;
    }

    m_current = ref;

    // support GNOME's xml2po's extension to references in the form of
    // filename:line(xml_node):
    wxString linenumStr = ref.AfterLast(_T(':')).BeforeFirst(_T('('));

    long linenum;
    if (!linenumStr.ToLong(&linenum))
        linenum = 0;

    m_text->SetReadOnly(false);
    m_text->SetValue(data);
    m_text->SetReadOnly(true);

    m_text->MarkerDeleteAll(1);
    m_text->MarkerAdd((int)linenum - 1, 1);

    // Center the highlighted line:
    int lineHeight = m_text->TextHeight((int)linenum);
    int linesInWnd = m_text->GetSize().y / lineHeight;
    m_text->ScrollToLine(wxMax(0, (int)linenum - linesInWnd/2));

}

void FileViewer::OnChoice(wxCommandEvent &event)
{
    ShowReference(m_references[event.GetSelection()]);
}

void FileViewer::OnEditFile(wxCommandEvent&)
{
    wxLaunchDefaultApplication(GetFilename(m_current).GetFullPath());
}
<|endoftext|>


<commit_before>#ifndef AI_NETWORKING_H
#define AI_NETWORKING_H

#include <iostream>
#include <time.h>
#include <set>
#include <cfloat>
#include <fstream>
#include <string>
#include <sstream>
#include <algorithm>
#include <bitset>
#include <assert.h>

#ifdef _WIN32
#include <sys/types.h>
#include <Winsock2.h>
#include <Ws2tcpip.h>
#define WINSOCKVERSION MAKEWORD(2,2)
#else
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <netdb.h>
#include <netinet/in.h>
#include <string.h>
#include <sys/types.h>
#endif

#include "hlt.hpp"

namespace detail{
static std::vector< std::vector<unsigned char> > productions;
static int width, height, connection;

static std::string serializeMoveSet(const std::set<hlt::Move> &moves) {
	std::ostringstream oss;
	for(auto a = moves.begin(); a != moves.end(); ++a) oss << a->loc.x << " " << a->loc.y << " " << (int)a->dir << " ";
	return oss.str();
}

static void deserializeMapSize(const std::string & inputString) {
	std::stringstream iss(inputString);
	iss >> width >> height;
}

static void deserializeProductions(const std::string & inputString) {
	std::stringstream iss(inputString);
	productions.resize(height);
	short temp;
	for(auto a = productions.begin(); a != productions.end(); a++) {
		a->resize(width);
		for(auto b = a->begin(); b != a->end(); b++) {
			iss >> temp;
			*b = temp;
		}
	}
}

static hlt::GameMap deserializeMap(const std::string & inputString) {
	std::stringstream iss(inputString);

	hlt::GameMap map(width, height);

	//Set productions
	for(int a = 0; a < map.height; a++) {
		for(int b = 0; b < map.width; b++) {
			map.contents[a][b].production = productions[a][b];
		}
	}

	//Run-length encode of owners
	unsigned short y = 0, x = 0;
	unsigned short counter = 0, owner = 0;
	while(y != map.height) {
		for(iss >> counter >> owner; counter; counter--) {
			map.contents[y][x].owner = owner;
			x++;
			if(x == map.width) {
				x = 0;
				y++;
			}
		}
	}

	for (int a = 0; a < map.contents.size(); a++) {
		for (int b = 0; b < map.contents[a].size(); b++) {
			short strengthShort;
			iss >> strengthShort;
			map.contents[a][b].strength = strengthShort;
		}
	}

	return map;
}
static void sendString(std::string & sendString) {
	sendString.push_back('\n');
	write(connection, sendString.c_str(), sendString.size());
	sendString.pop_back(); //Remove newline.
}

static std::string getString() {
	std::string newString;
	char buffer = 0;
	while(buffer != '\n') {
		assert(read(connection, &buffer, 1) >= 0);
		newString.push_back(buffer);
	}
	return newString;
}
}

static void getInit(int port, unsigned char& playerTag, hlt::GameMap& m) {
	//Connect to port
	detail::connection = socket(AF_INET, SOCK_STREAM, 0);
	assert(detail::connection >= 0);
	struct hostent *server;
	server = gethostbyname("127.0.0.1");
	assert(server != NULL);
	struct sockaddr_in serverAddr;
	bzero((char *) &serverAddr, sizeof(serverAddr));
	serverAddr.sin_family = AF_INET;
	bcopy((char *)server->h_addr, (char *)&serverAddr.sin_addr.s_addr, server->h_length);
	serverAddr.sin_port = htons(port);
	assert(connect(detail::connection, (struct sockaddr *)&serverAddr, sizeof(serverAddr)) >= 0);
	playerTag = (unsigned char)std::stoi(detail::getString());
	detail::deserializeMapSize(detail::getString());
	detail::deserializeProductions(detail::getString());
	m = detail::deserializeMap(detail::getString());

}

static void sendInit(std::string name) {
	detail::sendString(name);
}

static void getFrame(hlt::GameMap& m) {
	m = detail::deserializeMap(detail::getString());
}
static void sendFrame(const std::set<hlt::Move> &moves) {
	std::string serializedMoves = detail::serializeMoveSet(moves);
	detail::sendString(serializedMoves);
}

#endif
<commit_msg>Changed some indenting on c++<commit_after>#ifndef AI_NETWORKING_H
#define AI_NETWORKING_H

#include <iostream>
#include <time.h>
#include <set>
#include <cfloat>
#include <fstream>
#include <string>
#include <sstream>
#include <algorithm>
#include <bitset>
#include <assert.h>

#ifdef _WIN32
	#include <sys/types.h>
	#include <Winsock2.h>
	#include <Ws2tcpip.h>
	#define WINSOCKVERSION MAKEWORD(2,2)
#else
	#include <sys/socket.h>
	#include <sys/ioctl.h>
	#include <arpa/inet.h>
	#include <unistd.h>
	#include <time.h>
	#include <stdio.h>
	#include <stdlib.h>
	#include <netdb.h>
	#include <netinet/in.h>
	#include <string.h>
	#include <sys/types.h>
#endif

#include "hlt.hpp"

namespace detail{
static std::vector< std::vector<unsigned char> > productions;
static int width, height, connection;

static std::string serializeMoveSet(const std::set<hlt::Move> &moves) {
	std::ostringstream oss;
	for(auto a = moves.begin(); a != moves.end(); ++a) oss << a->loc.x << " " << a->loc.y << " " << (int)a->dir << " ";
	return oss.str();
}

static void deserializeMapSize(const std::string & inputString) {
	std::stringstream iss(inputString);
	iss >> width >> height;
}

static void deserializeProductions(const std::string & inputString) {
	std::stringstream iss(inputString);
	productions.resize(height);
	short temp;
	for(auto a = productions.begin(); a != productions.end(); a++) {
		a->resize(width);
		for(auto b = a->begin(); b != a->end(); b++) {
			iss >> temp;
			*b = temp;
		}
	}
}

static hlt::GameMap deserializeMap(const std::string & inputString) {
	std::stringstream iss(inputString);

	hlt::GameMap map(width, height);

	//Set productions
	for(int a = 0; a < map.height; a++) {
		for(int b = 0; b < map.width; b++) {
			map.contents[a][b].production = productions[a][b];
		}
	}

	//Run-length encode of owners
	unsigned short y = 0, x = 0;
	unsigned short counter = 0, owner = 0;
	while(y != map.height) {
		for(iss >> counter >> owner; counter; counter--) {
			map.contents[y][x].owner = owner;
			x++;
			if(x == map.width) {
				x = 0;
				y++;
			}
		}
	}

	for (int a = 0; a < map.contents.size(); a++) {
		for (int b = 0; b < map.contents[a].size(); b++) {
			short strengthShort;
			iss >> strengthShort;
			map.contents[a][b].strength = strengthShort;
		}
	}

	return map;
}
static void sendString(std::string & sendString) {
	sendString.push_back('\n');
	write(connection, sendString.c_str(), sendString.size());
	sendString.pop_back(); //Remove newline.
}

static std::string getString() {
	std::string newString;
	char buffer = 0;
	while(buffer != '\n') {
		assert(read(connection, &buffer, 1) >= 0);
		newString.push_back(buffer);
	}
	return newString;
}
}

static void getInit(int port, unsigned char& playerTag, hlt::GameMap& m) {
	//Connect to port
	detail::connection = socket(AF_INET, SOCK_STREAM, 0);
	assert(detail::connection >= 0);
	struct hostent *server;
	server = gethostbyname("127.0.0.1");
	assert(server != NULL);
	struct sockaddr_in serverAddr;
	bzero((char *) &serverAddr, sizeof(serverAddr));
	serverAddr.sin_family = AF_INET;
	bcopy((char *)server->h_addr, (char *)&serverAddr.sin_addr.s_addr, server->h_length);
	serverAddr.sin_port = htons(port);
	assert(connect(detail::connection, (struct sockaddr *)&serverAddr, sizeof(serverAddr)) >= 0);
	playerTag = (unsigned char)std::stoi(detail::getString());
	detail::deserializeMapSize(detail::getString());
	detail::deserializeProductions(detail::getString());
	m = detail::deserializeMap(detail::getString());

}

static void sendInit(std::string name) {
	detail::sendString(name);
}

static void getFrame(hlt::GameMap& m) {
	m = detail::deserializeMap(detail::getString());
}
static void sendFrame(const std::set<hlt::Move> &moves) {
	std::string serializedMoves = detail::serializeMoveSet(moves);
	detail::sendString(serializedMoves);
}

#endif
<|endoftext|>


<commit_before>/*
 *  This file is part of the KDE libraries
 *  Copyright (C) 2006 Harri Porten (porten@kde.org)
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Library General Public
 *  License as published by the Free Software Foundation; either
 *  version 2 of the License, or (at your option) any later version.
 *
 *  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
 *  Library General Public License for more details.
 *
 *  You should have received a copy of the GNU Library General Public License
 *  along with this library; see the file COPYING.LIB.  If not, write to
 *  the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 *  Boston, MA 02110-1301, USA.
 *
 */

#include "JSLock.h"
#include "interpreter.h"
#include "object.h"
#include "package.h"
#include "function.h"

#include <cstring>
#include <stdlib.h>
#include <stdio.h>
#include <sys/stat.h>
#include <fcntl.h>

#if PLATFORM(WIN_OS)
#  include <windows.h>
#  include <io.h>
#else
#  include <unistd.h>
#endif

#include <kjs_version.h>

enum ExitCode { ErrorNone,
                ErrorUnknownSwitch,
                ErrorMissingArg,
                ErrorReadFile,
                ErrorEval
              };

using std::strcmp;

using namespace KJS;

static void printUsage(const char *app)
{
    fprintf(stderr,
            "Usage: %s\n"
            "  [ -h | -help | --help ]\n"
            "  [ -e <statement> | <script> ]\n"
            "  [-v | -version | --version]\n",
            app);
}

static UString readFile(const char *fileName)
{
    int fd = open(fileName, O_RDONLY);
    if (fd < 0) {
        fprintf(stderr, "Error opening %s", fileName);
        return UString();
    }
    struct stat buf;
    if (fstat(fd, &buf) == -1) {
        fprintf(stderr, "Error stat'ing %s", fileName);
        close(fd);
        return UString();
    }
    int siz = buf.st_size;
    char *c = new char[siz + 1];
    int dataRead = read(fd, c, siz);
    if (dataRead == -1) {
        fprintf(stderr, "Error reading from %s", fileName);
        delete[] c;
        close(fd);
        return UString();
    }
    c[dataRead] = '\0';
    UString s = c;
    delete[] c;
    return s;
}

static ExitCode evaluateFile(Interpreter *interp, const char *fileName);

class GlobalImp : public JSGlobalObject
{
public:
    virtual UString className() const
    {
        return "global";
    }
};

class TestFunctionImp : public JSObject
{
public:
    TestFunctionImp(int i, int length);
    virtual bool implementsCall() const
    {
        return true;
    }
    virtual JSValue *callAsFunction(ExecState *exec,
                                    JSObject *thisObj, const List &args);
    enum { Print, Quit, Load, GC };

private:
    int id;
};

TestFunctionImp::TestFunctionImp(int i, int length)
    : JSObject(), id(i)
{
    putDirect(Identifier("length"), length, DontDelete | ReadOnly | DontEnum);
}

JSValue *TestFunctionImp::callAsFunction(ExecState *exec,
        JSObject * /* thisObj */,
        const List &args)
{
    switch (id) {
    case Print:
        printf("%s\n", args[0]->toString(exec).UTF8String().c_str());
        return jsUndefined();
    case Quit:
        exit(0);
    case GC:
        while (Interpreter::collect()) {}
        break;
    case Load:
        evaluateFile(exec->dynamicInterpreter(), args[0]->toString(exec).UTF8String().c_str());
        break;
    default:
        abort();
    }
    return jsUndefined();
}

static ExitCode evaluateString(Interpreter *interp, const char *fileName,
                               const UString &code,
                               bool printResult = false)
{
    ExecState *exec = interp->globalExec();

    Completion res = interp->evaluate(fileName, 0, code);

    if (res.complType() == Throw) {
        CString msg = res.value()->toString(exec).UTF8String();
        JSObject *resObj = res.value()->toObject(exec);
        CString message = resObj->toString(exec).UTF8String();
        int line = resObj->toObject(exec)->get(exec, "line")->toUInt32(exec);

        if (fileName) {
            fprintf(stderr, "%s (line %d): ", fileName, line);
        }
        fprintf(stderr, "%s\n", msg.c_str());
        return ErrorEval;
    } else if (printResult) {
        if (res.isValueCompletion() && !res.value()->isUndefined()) {
            CString s8 = res.value()->toString(exec).UTF8String();
            if (s8.size() != 0) {
                fprintf(stdout, "%s\n", s8.c_str());
            }
        }
    }

    return ErrorNone;
}

static ExitCode evaluateFile(Interpreter *interp, const char *fileName)
{
    UString code = readFile(fileName);
    if (code.isNull()) {
        return ErrorReadFile;
    }

    return evaluateString(interp, fileName, code);
}

// primitive readline-like function
static char *readLine(const char *prompt)
{
    if (prompt) {
        fprintf(stdout, "%s", prompt);
    }

    const int bsize = 2 << 10;
    char *buffer = static_cast<char *>(malloc(bsize));
    char *s = fgets(buffer, bsize, stdin);
    if (s == 0) {
        // EOF
        fprintf(stdout, "\n");
        free(buffer);
    }
    return s;
}

static ExitCode evaluateInteractive(Interpreter *interp)
{
    char *line;
    while ((line = readLine("JS> ")) != 0) {
        UString code(line);
        free(line);
        evaluateString(interp, 0, code, true);
    }

    return ErrorNone;
}

static ExitCode parseArgs(int argc, char **argv)
{
    JSLock lock;

    GlobalImp *global = new GlobalImp();

    // create interpreter
    RefPtr<Interpreter> interp = new Interpreter(global);

    // add some global extension functions
    ExecState *gexec = interp->globalExec();
    global->put(gexec, "print",
                new TestFunctionImp(TestFunctionImp::Print, 1));
    global->put(gexec, "quit",
                new TestFunctionImp(TestFunctionImp::Quit, 0));
    global->put(gexec, "load",
                new TestFunctionImp(TestFunctionImp::Load, 1));
    global->put(gexec, "gc",
                new TestFunctionImp(TestFunctionImp::GC, 0));

    // enable package support
    StandardGlobalPackage package;
    interp->setGlobalPackage(&package);

    const char *script = 0, *command = 0;
    int ai = 1;
    bool ranOtherScript = false;
    for (ai = 1; ai < argc; ++ai) {
        const char *a = argv[ai];
        if (strcmp(a, "-v") == 0 || strcmp(a, "-version") == 0 ||
                strcmp(a, "--version") == 0) {
            printf("KDE: %s\n", KJS_VERSION_STRING);
            return ErrorNone;
        } else if (strcmp(a, "-h") == 0 || strcmp(a, "-help") == 0 ||
                   strcmp(a, "--help") == 0) {
            printUsage(argv[0]);
            return ErrorNone;
        } else if (strcmp(a, "-e") == 0) {
            ++ai;
            if (argc <= ai) {
                fprintf(stderr, "Missing -e argument.\n");
                return ErrorMissingArg;
            }
            command = argv[ai];
            ++ai;
            break;
        } else if (strcmp(a, "-f") == 0) { // Compatibility mode, for SunSpider
            ++ai;
            if (argc <= ai) {
                fprintf(stderr, "Missing -f argument.\n");
                return ErrorMissingArg;
            }
            ExitCode result = evaluateFile(interp.get(), argv[ai]);
            if (result != ErrorNone) {
                return result;
            }
            ranOtherScript = true;
        } else if (a[0] == '-') {
            fprintf(stderr, "Unknown switch %s.\n", a);
            return ErrorUnknownSwitch;
        } else {
            script = a;
            ++ai;
            break;
        }
    }

    // ###
    if (argc > ai) {
        fprintf(stderr, "Warning: ignoring extra arguments\n");
    }

    if (script) {
        return evaluateFile(interp.get(), script);
    } else if (command) {
        return evaluateString(interp.get(), "(eval)", command);
    } else if (!ranOtherScript) {
        return evaluateInteractive(interp.get());
    }
    return ErrorNone;
}

int main(int argc, char **argv)
{
    return int(parseArgs(argc, argv));
}
<commit_msg>Fix memory leak<commit_after>/*
 *  This file is part of the KDE libraries
 *  Copyright (C) 2006 Harri Porten (porten@kde.org)
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Library General Public
 *  License as published by the Free Software Foundation; either
 *  version 2 of the License, or (at your option) any later version.
 *
 *  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
 *  Library General Public License for more details.
 *
 *  You should have received a copy of the GNU Library General Public License
 *  along with this library; see the file COPYING.LIB.  If not, write to
 *  the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 *  Boston, MA 02110-1301, USA.
 *
 */

#include "JSLock.h"
#include "interpreter.h"
#include "object.h"
#include "package.h"
#include "function.h"

#include <cstring>
#include <stdlib.h>
#include <stdio.h>
#include <sys/stat.h>
#include <fcntl.h>

#if PLATFORM(WIN_OS)
#  include <windows.h>
#  include <io.h>
#else
#  include <unistd.h>
#endif

#include <kjs_version.h>

enum ExitCode { ErrorNone,
                ErrorUnknownSwitch,
                ErrorMissingArg,
                ErrorReadFile,
                ErrorEval
              };

using std::strcmp;

using namespace KJS;

static void printUsage(const char *app)
{
    fprintf(stderr,
            "Usage: %s\n"
            "  [ -h | -help | --help ]\n"
            "  [ -e <statement> | <script> ]\n"
            "  [-v | -version | --version]\n",
            app);
}

static UString readFile(const char *fileName)
{
    int fd = open(fileName, O_RDONLY);
    if (fd < 0) {
        fprintf(stderr, "Error opening %s", fileName);
        return UString();
    }
    struct stat buf;
    if (fstat(fd, &buf) == -1) {
        fprintf(stderr, "Error stat'ing %s", fileName);
        close(fd);
        return UString();
    }
    int siz = buf.st_size;
    char *c = new char[siz + 1];
    int dataRead = read(fd, c, siz);
    if (dataRead == -1) {
        fprintf(stderr, "Error reading from %s", fileName);
        delete[] c;
        close(fd);
        return UString();
    }
    c[dataRead] = '\0';
    UString s = c;
    delete[] c;
    close(fd);
    return s;
}

static ExitCode evaluateFile(Interpreter *interp, const char *fileName);

class GlobalImp : public JSGlobalObject
{
public:
    virtual UString className() const
    {
        return "global";
    }
};

class TestFunctionImp : public JSObject
{
public:
    TestFunctionImp(int i, int length);
    virtual bool implementsCall() const
    {
        return true;
    }
    virtual JSValue *callAsFunction(ExecState *exec,
                                    JSObject *thisObj, const List &args);
    enum { Print, Quit, Load, GC };

private:
    int id;
};

TestFunctionImp::TestFunctionImp(int i, int length)
    : JSObject(), id(i)
{
    putDirect(Identifier("length"), length, DontDelete | ReadOnly | DontEnum);
}

JSValue *TestFunctionImp::callAsFunction(ExecState *exec,
        JSObject * /* thisObj */,
        const List &args)
{
    switch (id) {
    case Print:
        printf("%s\n", args[0]->toString(exec).UTF8String().c_str());
        return jsUndefined();
    case Quit:
        exit(0);
    case GC:
        while (Interpreter::collect()) {}
        break;
    case Load:
        evaluateFile(exec->dynamicInterpreter(), args[0]->toString(exec).UTF8String().c_str());
        break;
    default:
        abort();
    }
    return jsUndefined();
}

static ExitCode evaluateString(Interpreter *interp, const char *fileName,
                               const UString &code,
                               bool printResult = false)
{
    ExecState *exec = interp->globalExec();

    Completion res = interp->evaluate(fileName, 0, code);

    if (res.complType() == Throw) {
        CString msg = res.value()->toString(exec).UTF8String();
        JSObject *resObj = res.value()->toObject(exec);
        CString message = resObj->toString(exec).UTF8String();
        int line = resObj->toObject(exec)->get(exec, "line")->toUInt32(exec);

        if (fileName) {
            fprintf(stderr, "%s (line %d): ", fileName, line);
        }
        fprintf(stderr, "%s\n", msg.c_str());
        return ErrorEval;
    } else if (printResult) {
        if (res.isValueCompletion() && !res.value()->isUndefined()) {
            CString s8 = res.value()->toString(exec).UTF8String();
            if (s8.size() != 0) {
                fprintf(stdout, "%s\n", s8.c_str());
            }
        }
    }

    return ErrorNone;
}

static ExitCode evaluateFile(Interpreter *interp, const char *fileName)
{
    UString code = readFile(fileName);
    if (code.isNull()) {
        return ErrorReadFile;
    }

    return evaluateString(interp, fileName, code);
}

// primitive readline-like function
static char *readLine(const char *prompt)
{
    if (prompt) {
        fprintf(stdout, "%s", prompt);
    }

    const int bsize = 2 << 10;
    char *buffer = static_cast<char *>(malloc(bsize));
    char *s = fgets(buffer, bsize, stdin);
    if (s == 0) {
        // EOF
        fprintf(stdout, "\n");
        free(buffer);
    }
    return s;
}

static ExitCode evaluateInteractive(Interpreter *interp)
{
    char *line;
    while ((line = readLine("JS> ")) != 0) {
        UString code(line);
        free(line);
        evaluateString(interp, 0, code, true);
    }

    return ErrorNone;
}

static ExitCode parseArgs(int argc, char **argv)
{
    JSLock lock;

    GlobalImp *global = new GlobalImp();

    // create interpreter
    RefPtr<Interpreter> interp = new Interpreter(global);

    // add some global extension functions
    ExecState *gexec = interp->globalExec();
    global->put(gexec, "print",
                new TestFunctionImp(TestFunctionImp::Print, 1));
    global->put(gexec, "quit",
                new TestFunctionImp(TestFunctionImp::Quit, 0));
    global->put(gexec, "load",
                new TestFunctionImp(TestFunctionImp::Load, 1));
    global->put(gexec, "gc",
                new TestFunctionImp(TestFunctionImp::GC, 0));

    // enable package support
    StandardGlobalPackage package;
    interp->setGlobalPackage(&package);

    const char *script = 0, *command = 0;
    int ai = 1;
    bool ranOtherScript = false;
    for (ai = 1; ai < argc; ++ai) {
        const char *a = argv[ai];
        if (strcmp(a, "-v") == 0 || strcmp(a, "-version") == 0 ||
                strcmp(a, "--version") == 0) {
            printf("KDE: %s\n", KJS_VERSION_STRING);
            return ErrorNone;
        } else if (strcmp(a, "-h") == 0 || strcmp(a, "-help") == 0 ||
                   strcmp(a, "--help") == 0) {
            printUsage(argv[0]);
            return ErrorNone;
        } else if (strcmp(a, "-e") == 0) {
            ++ai;
            if (argc <= ai) {
                fprintf(stderr, "Missing -e argument.\n");
                return ErrorMissingArg;
            }
            command = argv[ai];
            ++ai;
            break;
        } else if (strcmp(a, "-f") == 0) { // Compatibility mode, for SunSpider
            ++ai;
            if (argc <= ai) {
                fprintf(stderr, "Missing -f argument.\n");
                return ErrorMissingArg;
            }
            ExitCode result = evaluateFile(interp.get(), argv[ai]);
            if (result != ErrorNone) {
                return result;
            }
            ranOtherScript = true;
        } else if (a[0] == '-') {
            fprintf(stderr, "Unknown switch %s.\n", a);
            return ErrorUnknownSwitch;
        } else {
            script = a;
            ++ai;
            break;
        }
    }

    // ###
    if (argc > ai) {
        fprintf(stderr, "Warning: ignoring extra arguments\n");
    }

    if (script) {
        return evaluateFile(interp.get(), script);
    } else if (command) {
        return evaluateString(interp.get(), "(eval)", command);
    } else if (!ranOtherScript) {
        return evaluateInteractive(interp.get());
    }
    return ErrorNone;
}

int main(int argc, char **argv)
{
    return int(parseArgs(argc, argv));
}
<|endoftext|>


<commit_before>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkOpenGLContextBufferId.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/

#include "vtkOpenGLContextBufferId.h"

#include "vtkIntArray.h"
#include <cassert>
#include "vtkObjectFactory.h"
#include "vtkOpenGLTexture.h"
#include "vtkTextureObject.h"
#include "vtkgl.h"
#include "vtkOpenGLRenderWindow.h"

vtkCxxRevisionMacro(vtkOpenGLContextBufferId, "1.1");
vtkStandardNewMacro(vtkOpenGLContextBufferId);

// ----------------------------------------------------------------------------
vtkOpenGLContextBufferId::vtkOpenGLContextBufferId()
{
  this->Texture=0;
}

// ----------------------------------------------------------------------------
vtkOpenGLContextBufferId::~vtkOpenGLContextBufferId()
{
  if(this->Texture!=0)
    {
    vtkErrorMacro("texture should have been released.");
    }
}

// ----------------------------------------------------------------------------
void vtkOpenGLContextBufferId::ReleaseGraphicsResources()
{
  if(this->Texture!=0)
    {
    this->Texture->Delete();
    this->Texture=0;
    }
}

//----------------------------------------------------------------------------
void vtkOpenGLContextBufferId::SetContext(vtkOpenGLRenderWindow *context)
{
  if(this->Context!=context)
    {
    this->ReleaseGraphicsResources();
    this->Context=context;
    this->Modified();
    }
}

//----------------------------------------------------------------------------
vtkOpenGLRenderWindow *vtkOpenGLContextBufferId::GetContext()
{
  return this->Context;
}

// ----------------------------------------------------------------------------
void vtkOpenGLContextBufferId::Allocate()
{
  assert("pre: positive_width" && this->GetWidth()>0);
  assert("pre: positive_height" && this->GetHeight()>0);

  if(this->Texture==0)
    {
    this->Texture=vtkTextureObject::New();
    this->Texture->SetContext(this->Context);
    }
  this->Context->MakeCurrent();
  // 3: RGB
  this->Texture->Allocate2D(this->GetWidth(),this->GetHeight(),3,
                            VTK_UNSIGNED_CHAR);
}

// ----------------------------------------------------------------------------
bool vtkOpenGLContextBufferId::IsAllocated() const
{

  return this->Texture!=0 &&
    this->Texture->GetWidth()==this->Width &&
    this->Texture->GetHeight()==this->Height;
}

// ----------------------------------------------------------------------------
void vtkOpenGLContextBufferId::SetValues(int srcXmin,
                                         int srcYmin)
{
  assert("pre: is_allocated" && this->IsAllocated());

  // copy the current read buffer to the texture.
  this->Texture->CopyFromFrameBuffer(srcXmin,srcYmin,0,0,this->Width,
                                     this->Height);
}

// ----------------------------------------------------------------------------
vtkIdType vtkOpenGLContextBufferId::GetPickedItem(int x, int y)
{
  assert("pre: is_allocated" && this->IsAllocated());

  vtkIdType result=-1;
  if(x<0 || x>=this->Width)
    {
    vtkDebugMacro(<<"x mouse position out of range: x=" << x << " (width="
                    << this->Width <<")");
    }
  else
    {
    if(y<0 || y>=this->Height)
      {
      vtkDebugMacro(<<"y mouse position out of range: y="<< y << " (height="
                      << this->Height << ")");
      }
    else
      {
      this->Context->MakeCurrent();
      // Render texture to current write buffer. Texel x,y is rendered at
      // pixel 0,0.
      GLint savedDrawBuffer;
      glGetIntegerv(GL_DRAW_BUFFER,&savedDrawBuffer);
      bool savedDepthTest=glIsEnabled(GL_DEPTH_TEST)==GL_TRUE;
      bool savedAlphaTest=glIsEnabled(GL_ALPHA_TEST)==GL_TRUE;
      bool savedStencilTest=glIsEnabled(GL_STENCIL_TEST)==GL_TRUE;
      bool savedBlend=glIsEnabled(GL_BLEND)==GL_TRUE;

      if(savedDrawBuffer!=GL_BACK_LEFT)
        {
        glDrawBuffer(GL_BACK_LEFT);
        }
      if(savedDepthTest)
        {
        glDisable(GL_DEPTH_TEST);
        }
      if(savedAlphaTest)
        {
        glDisable(GL_ALPHA_TEST);
        }
      if(savedStencilTest)
        {
        glDisable(GL_STENCIL_TEST);
        }
      if(savedBlend)
        {
        glDisable(GL_BLEND);
        }

      // Fixed-pipeline stuff
      vtkgl::ActiveTexture(vtkgl::TEXTURE0);
      this->Texture->Bind();
      glTexEnvi(GL_TEXTURE_ENV,GL_TEXTURE_ENV_MODE,GL_REPLACE);
      glEnable(GL_TEXTURE_2D);
      this->Texture->CopyToFrameBuffer(x,y,x,y,0,0,this->Width,this->Height);
      glDisable(GL_TEXTURE_2D);

      GLint savedReadBuffer;
      glGetIntegerv(GL_READ_BUFFER,&savedReadBuffer);
      glReadBuffer(GL_BACK_LEFT);

      // Get value from current read buffer at pixel (0,0).
      glPixelStorei(GL_PACK_ALIGNMENT,1);
      unsigned char rgb[3];
      rgb[0]=5;
      rgb[1]=1;
      rgb[2]=8;
      glReadPixels(0,0,1,1,GL_RGB,GL_UNSIGNED_BYTE,rgb);

      if(savedReadBuffer!=GL_BACK_LEFT)
        {
        glReadBuffer(static_cast<GLenum>(savedReadBuffer));
        }
      if(savedDrawBuffer!=GL_BACK_LEFT)
        {
        glDrawBuffer(static_cast<GLenum>(savedDrawBuffer));
        }
      if(savedDepthTest)
        {
        glEnable(GL_DEPTH_TEST);
        }
      if(savedAlphaTest)
        {
        glEnable(GL_ALPHA_TEST);
        }
      if(savedStencilTest)
        {
        glEnable(GL_STENCIL_TEST);
        }
      if(savedBlend)
        {
        glEnable(GL_BLEND);
        }

      int value=(static_cast<int>(rgb[0])<<16)|(static_cast<int>(rgb[1])<<8)
        |static_cast<int>(rgb[2]);

      result=static_cast<vtkIdType>(value-1);

      cout << "rgb=" << static_cast<int>(rgb[0]) << ", " <<
      static_cast<int>(rgb[1]) << "," << static_cast<int>(rgb[2]) <<
      " value=" << value <<" result=" << result<<  endl;

      }
    }

  assert("post: valid_result" && result>=-1 );
  return result;
}

//-----------------------------------------------------------------------------
void vtkOpenGLContextBufferId::PrintSelf(ostream &os, vtkIndent indent)
{
  this->Superclass::PrintSelf(os, indent);
}
<commit_msg>BUG:Removed leftover cout from debugging.<commit_after>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkOpenGLContextBufferId.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/

#include "vtkOpenGLContextBufferId.h"

#include "vtkIntArray.h"
#include <cassert>
#include "vtkObjectFactory.h"
#include "vtkOpenGLTexture.h"
#include "vtkTextureObject.h"
#include "vtkgl.h"
#include "vtkOpenGLRenderWindow.h"

vtkCxxRevisionMacro(vtkOpenGLContextBufferId, "1.2");
vtkStandardNewMacro(vtkOpenGLContextBufferId);

// ----------------------------------------------------------------------------
vtkOpenGLContextBufferId::vtkOpenGLContextBufferId()
{
  this->Texture=0;
}

// ----------------------------------------------------------------------------
vtkOpenGLContextBufferId::~vtkOpenGLContextBufferId()
{
  if(this->Texture!=0)
    {
    vtkErrorMacro("texture should have been released.");
    }
}

// ----------------------------------------------------------------------------
void vtkOpenGLContextBufferId::ReleaseGraphicsResources()
{
  if(this->Texture!=0)
    {
    this->Texture->Delete();
    this->Texture=0;
    }
}

//----------------------------------------------------------------------------
void vtkOpenGLContextBufferId::SetContext(vtkOpenGLRenderWindow *context)
{
  if(this->Context!=context)
    {
    this->ReleaseGraphicsResources();
    this->Context=context;
    this->Modified();
    }
}

//----------------------------------------------------------------------------
vtkOpenGLRenderWindow *vtkOpenGLContextBufferId::GetContext()
{
  return this->Context;
}

// ----------------------------------------------------------------------------
void vtkOpenGLContextBufferId::Allocate()
{
  assert("pre: positive_width" && this->GetWidth()>0);
  assert("pre: positive_height" && this->GetHeight()>0);

  if(this->Texture==0)
    {
    this->Texture=vtkTextureObject::New();
    this->Texture->SetContext(this->Context);
    }
  this->Context->MakeCurrent();
  // 3: RGB
  this->Texture->Allocate2D(this->GetWidth(),this->GetHeight(),3,
                            VTK_UNSIGNED_CHAR);
}

// ----------------------------------------------------------------------------
bool vtkOpenGLContextBufferId::IsAllocated() const
{

  return this->Texture!=0 &&
    this->Texture->GetWidth()==this->Width &&
    this->Texture->GetHeight()==this->Height;
}

// ----------------------------------------------------------------------------
void vtkOpenGLContextBufferId::SetValues(int srcXmin,
                                         int srcYmin)
{
  assert("pre: is_allocated" && this->IsAllocated());

  // copy the current read buffer to the texture.
  this->Texture->CopyFromFrameBuffer(srcXmin,srcYmin,0,0,this->Width,
                                     this->Height);
}

// ----------------------------------------------------------------------------
vtkIdType vtkOpenGLContextBufferId::GetPickedItem(int x, int y)
{
  assert("pre: is_allocated" && this->IsAllocated());

  vtkIdType result=-1;
  if(x<0 || x>=this->Width)
    {
    vtkDebugMacro(<<"x mouse position out of range: x=" << x << " (width="
                    << this->Width <<")");
    }
  else
    {
    if(y<0 || y>=this->Height)
      {
      vtkDebugMacro(<<"y mouse position out of range: y="<< y << " (height="
                      << this->Height << ")");
      }
    else
      {
      this->Context->MakeCurrent();
      // Render texture to current write buffer. Texel x,y is rendered at
      // pixel 0,0.
      GLint savedDrawBuffer;
      glGetIntegerv(GL_DRAW_BUFFER,&savedDrawBuffer);
      bool savedDepthTest=glIsEnabled(GL_DEPTH_TEST)==GL_TRUE;
      bool savedAlphaTest=glIsEnabled(GL_ALPHA_TEST)==GL_TRUE;
      bool savedStencilTest=glIsEnabled(GL_STENCIL_TEST)==GL_TRUE;
      bool savedBlend=glIsEnabled(GL_BLEND)==GL_TRUE;

      if(savedDrawBuffer!=GL_BACK_LEFT)
        {
        glDrawBuffer(GL_BACK_LEFT);
        }
      if(savedDepthTest)
        {
        glDisable(GL_DEPTH_TEST);
        }
      if(savedAlphaTest)
        {
        glDisable(GL_ALPHA_TEST);
        }
      if(savedStencilTest)
        {
        glDisable(GL_STENCIL_TEST);
        }
      if(savedBlend)
        {
        glDisable(GL_BLEND);
        }

      // Fixed-pipeline stuff
      vtkgl::ActiveTexture(vtkgl::TEXTURE0);
      this->Texture->Bind();
      glTexEnvi(GL_TEXTURE_ENV,GL_TEXTURE_ENV_MODE,GL_REPLACE);
      glEnable(GL_TEXTURE_2D);
      this->Texture->CopyToFrameBuffer(x,y,x,y,0,0,this->Width,this->Height);
      glDisable(GL_TEXTURE_2D);

      GLint savedReadBuffer;
      glGetIntegerv(GL_READ_BUFFER,&savedReadBuffer);
      glReadBuffer(GL_BACK_LEFT);

      // Get value from current read buffer at pixel (0,0).
      glPixelStorei(GL_PACK_ALIGNMENT,1);
      unsigned char rgb[3];
      rgb[0]=5;
      rgb[1]=1;
      rgb[2]=8;
      glReadPixels(0,0,1,1,GL_RGB,GL_UNSIGNED_BYTE,rgb);

      if(savedReadBuffer!=GL_BACK_LEFT)
        {
        glReadBuffer(static_cast<GLenum>(savedReadBuffer));
        }
      if(savedDrawBuffer!=GL_BACK_LEFT)
        {
        glDrawBuffer(static_cast<GLenum>(savedDrawBuffer));
        }
      if(savedDepthTest)
        {
        glEnable(GL_DEPTH_TEST);
        }
      if(savedAlphaTest)
        {
        glEnable(GL_ALPHA_TEST);
        }
      if(savedStencilTest)
        {
        glEnable(GL_STENCIL_TEST);
        }
      if(savedBlend)
        {
        glEnable(GL_BLEND);
        }

      int value=(static_cast<int>(rgb[0])<<16)|(static_cast<int>(rgb[1])<<8)
        |static_cast<int>(rgb[2]);

      result=static_cast<vtkIdType>(value-1);
      }
    }

  assert("post: valid_result" && result>=-1 );
  return result;
}

//-----------------------------------------------------------------------------
void vtkOpenGLContextBufferId::PrintSelf(ostream &os, vtkIndent indent)
{
  this->Superclass::PrintSelf(os, indent);
}
<|endoftext|>