Пример #1
0
int main () {
        string s="你好";
        wstring ws=L"你好";

        cout<<s<<endl;
        cout<<wstringtostring(ws)<<endl;
        cout<<narrow(ws)<<endl;

	wcout.imbue(locale(locale(), "", LC_CTYPE));
	// wcout.imbue(locale(""));
        // wcout.imbue(locale_platform);
        wcout<<ws<<endl;
        wcout<<stringtowstring(s)<<endl;
        wcout<<widen(s)<<endl;

        wofstream fout("fout.txt");
        fout.imbue(locale_platform);
        fout<<ws<<endl;
        fout<<stringtowstring(s)<<endl;
        fout<<widen(s)<<endl;

	
//        string in;
//	copy(utf8in(s.begin()), utf8in(s.end()), back_inserter(in));
//	cout<<in<<endl;
	// copy(utf8in(s.begin()), utf8in(s.end()), back_inserter(wvect));
	// cout<<string(utf8in(s.begin()), utf8in(s.end()))<<endl;
}
Пример #2
0
bool init_sentinel() {
  // create synchronization event
  g_crash_event = CreateEventW(NULL, FALSE, FALSE, widen(crash_id).c_str());
  if (!g_crash_event) {
    std::cerr << "Could not initialize crash event object." << std::endl;
  }

  // create shared memory (through MMF)
  auto map_file =
      CreateFileMappingW(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0,
                         BUF_SIZE, widen(mmf_name).c_str());
  if (!map_file) {
    std::cerr << "Could not open MMF (" << crash_id << ")" << std::endl;
    std::cerr << "GetLastError(): " << GetLastError() << std::endl;
    return false;
  }

  g_mmf = reinterpret_cast<char *>(
      MapViewOfFile(map_file, FILE_MAP_ALL_ACCESS, 0, 0, BUF_SIZE));

  // start sentinel.exe
  STARTUPINFOW info = {sizeof(info)};
  PROCESS_INFORMATION processInfo;
  std::stringstream ss;
  ss << "sentinel.exe " << crash_id << " " << mmf_name;
  if (CreateProcessW(widen("sentinel.exe").c_str(),
                     const_cast<wchar_t *>(widen(ss.str()).c_str()), NULL, NULL,
                     TRUE, CREATE_NEW_CONSOLE, NULL, NULL, &info,
                     &processInfo) == 0) {
    return false;
  }

  SetUnhandledExceptionFilter(unhandled_filter);
  return true;
}
Пример #3
0
 StartupInfoEx( LPSTARTUPINFOA si, StringSaver<wchar_t> & s, WideConverter & c )
 {
     static_cast<STARTUPINFOW &>( *this ) = *reinterpret_cast<LPSTARTUPINFOW>( si );
     this->lpReserved = widen( s, c, si->lpReserved );
     this->lpDesktop = widen( s, c, si->lpDesktop );
     this->lpTitle = widen( s, c, si->lpTitle );
 }
Пример #4
0
void execute_shell(std::string fname, std::string args) {
  WCHAR cDir[MAX_PATH];
  GetCurrentDirectoryW(MAX_PATH, cDir);
  tstring tstr_fname = widen(fname);
  tstring tstr_args = widen(args);
  ShellExecuteW(enigma::hWnd, NULL, tstr_fname.c_str(), tstr_args.c_str(), cDir, SW_SHOW);
}
Пример #5
0
bool create_snapshot(std::string snapshot_src, std::string snapshot_dst)
{
#ifdef _WIN32
	return CopyFolder(widen(snapshot_src), widen(snapshot_dst));
#else
	int rc=system((btrfs_cmd+" subvolume snapshot \""+snapshot_src+"\" \""+snapshot_dst+"\"").c_str());
	system(("chown urbackup:urbackup \""+snapshot_dst+"\"").c_str());
	return rc==0;
#endif
}
Пример #6
0
int
response_type7(int id,int major,int minor,int num,char** buf,int bufsize)
{
  canna_server* svr = &server[id];
  canna_response_type7 res;
  int total,sub,size,offset;
  int i;

  reset(svr);
  if (num == -1) {
    res.maj = major;
    res.min = minor;
    res.size = htons(2);
    res.num = htons(-1);

    if (emit(svr,&res.maj,1)) return -1;
    if (emit(svr,&res.min,1)) return -1;
    if (emit(svr,&res.size,2)) return -1;
    if (emit(svr,&res.num,2)) return -1;
  } else {
    total = 0;
    for (i = 0; i < bufsize; i++) {
      sub = widen(0,0,buf[i],strlen(buf[i])+1);
      if (sub == -1) return -1;
      total += sub;
    }
    size = total * 2;

    res.maj = major;
    res.min = minor;
    res.size = htons(2+size);
    res.num = htons(num);
    res.data = malloc(size);
    offset = 0;
    for (i = 0; i < bufsize; i++) {
      sub = widen(((uint16_t*)res.data) + offset,
		  total - offset,buf[i],strlen(buf[i]) + 1);
      if (sub == -1) break;
      offset += sub;
    }
    if (emit(svr,&res.maj,1)) return -1;
    if (emit(svr,&res.min,1)) return -1;
    if (emit(svr,&res.size,2)) return -1;
    if (emit(svr,&res.num,2)) return -1;
    if (emit(svr,res.data,size)) return -1;
    free(res.data);
  }
  return flush(svr);
}
Пример #7
0
unsigned long long disk_size(std::string drive) {
  DWORD sectorsPerCluster, bytesPerSector, totalClusters, freeClusters;

  tstring tstr_drive = widen(drive);
  tstring tstr_colonslash = widen(":\\");
  tstring tstr_empty = widen("");

  if (tstr_drive.length() == 1) tstr_drive += tstr_colonslash;

  if (!GetDiskFreeSpaceW((tstr_drive == tstr_empty) ? NULL : tstr_drive.c_str(), &sectorsPerCluster, &bytesPerSector,
                         &freeClusters, &totalClusters))
    return 0;

  return (unsigned long long)(totalClusters * sectorsPerCluster) * (unsigned long long)bytesPerSector;
}
Пример #8
0
	void MidiService::play(string file, int volume)
	{
		// Предварительно закрываем предыдущий файл.
		// В один момент времени может проигрываться только один файл MIDI.
		close(true, "");

		// Открываем файл.
		string command = "open \"" + file + "\" type sequencer alias MidiFile";
		wstring wCommand = widen(command);
		LPCWSTR pCommand = wCommand.c_str();
		MCIERROR err = mciSendString(pCommand, NULL, 0, NULL);
		if (err != 0)
		{
			showError("Не удалось открыть MIDI-файл: " + file);
			return;
		}
		// Запускаем проигрывание.
		err = mciSendString(L"play MidiFile from 0", NULL, 0, NULL);
		if (err != 0)
		{
			showError("Не удалось запустить MIDI-файл: " + file);
			return;
		}
		// Устанавливаем громкость проигрываемого файла.
		setVolume(volume);
		// Сохраняем имя файла.
		midiFile = file;
	}
Пример #9
0
std::string environment_get_variable(std::string name) {
  WCHAR buffer[1024];
  tstring tstr_name = widen(name);
  GetEnvironmentVariableW(tstr_name.c_str(), (LPWSTR)&buffer, 1024);

  return shorten(buffer);
}
Пример #10
0
Logger &Logger::operator<<(std::string &val)	
{
#ifndef _SIMPLE_NO_DEBUG
	m_stream << widen(val);
#endif
	return *this;
}
Пример #11
0
bool c_preprocess_none(
  const std::string &file,
  std::ostream &outstream,
  message_handlert &message_handler)
{
  #ifdef _MSC_VER
  std::ifstream infile(widen(file).c_str());
  #else
  std::ifstream infile(file.c_str());
  #endif
  
  if(!infile)
  {
    message_streamt message_stream(message_handler);
    message_stream.error("failed to open `"+file+"'");
    return true;
  }
  
  if(config.ansi_c.mode==configt::ansi_ct::MODE_CODEWARRIOR_C_CPP)
  {
    // special treatment for "/* #line"
    postprocess_codewarrior(infile, outstream);
  }
  else
  {
    char ch;

    while(infile.read(&ch, 1))
      outstream << ch;
  }

  return false;
}
Пример #12
0
void
basic_ios<_CharT, _Traits>::init(basic_streambuf<_CharT, _Traits>* __sb)
{
  this->rdbuf(__sb);
  this->imbue(locale());
  this->tie(0);
  this->_M_set_exception_mask(ios_base::goodbit);
  /*
    this->_M_clear_nothrow(__sb != 0 ? ios_base::goodbit : ios_base::badbit);
	
  The ternary expression above, throws an undefined reference link error (for goodbit and badbit)
  when compiled with GCCE 4.3.2. Replacing ternary statement with an if-else block fixes this.
  */
  if(__sb != 0) {
	this->_M_clear_nothrow(ios_base::goodbit);
  } else {
	this->_M_clear_nothrow(ios_base::badbit);
  }
  ios_base::flags(ios_base::skipws | ios_base::dec);
  ios_base::width(0);
  ios_base::precision(6);
  this->fill(widen(' '));
  // We don't need to worry about any of the three arrays: they are
  // initialized correctly in ios_base's constructor.
}
Пример #13
0
void print_response(HttpResponse& response, TcpClientSocket& socket) {
	std::cout << narrow(widen(response.getStatusLine(), CP_UTF8), CP_OEMCP) << std::endl;
	auto headers = response.getHeaders();
	for (auto it = std::begin(headers), eit = std::end(headers); it != eit; ++it) {
		for (auto vit = std::begin(it->second), veit = std::end(it->second); vit != veit; ++vit) {
			std::cout << it->first << ": " << *vit << std::endl;
		}
	}
	std::cout << "======END OF HEADERS======" << std::endl;

	auto& buffer = response.getBuffer();
	if (response.getIsChunked()) {
		std::cout << "[[CHUNKED ENCODING]]" << std::endl;
		for (auto chunk = buffer.getchunk(); !chunk.empty(); chunk = buffer.getchunk()) {
			std::cout << chunk;
		}
		std::cout << "[[TRAILING HEADERS]]" << std::endl;
		for (auto th = buffer.getline(); !th.empty(); th = buffer.getline()) {
			std::cout << th << std::endl;
		}
	}
	else if (HttpResponse::nlen != response.getContentLength()) {
		std::cout << "[[EXACTLY " << response.getContentLength() << " BYTES]]" << std::endl;
		std::cout << buffer.getcount(response.getContentLength()) << std::endl;
	}
	else {
		std::vector<BYTE> buff(8 * 1024, 0);
		for (auto last = socket.recv_upto(std::begin(buff), std::end(buff));
			last != std::begin(buff); last = socket.recv_upto(std::begin(buff), std::end(buff))) {
				std::cout << std::string(std::begin(buff), last);
		}
	}
	std::cout << std::endl << "======END OF RESPONSE======" << std::endl;
}
Пример #14
0
bool XmlSettingsStore::Save() {
  if (!modified_) {
    return true;
  }
  try {
    modified_ = false;
    std::ofstream out;
    out.open(widen(filename_), std::ios::out | std::ios::trunc);
    out << "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n";
    out << "<settings>\n";
    for (const auto& p : long_settings_) {
      out << "<long name=\"" << p.first << "\" value=\"" << p.second
          << "\"/>\n";
    }
    for (const auto& p : boolean_settings_) {
      std::string value = p.second ? "True" : "False";
      out << "<bool name=\"" << p.first << "\" value=\"" << value << "\"/>\n";
    }
    for (const auto& p : string_settings_) {
      std::string attribute = p.second;
      XML_Escape(attribute, true /* attribute */);
      out << "<string name=\"" << p.first << "\" value=\"" << attribute
          << "\"/>\n";
    }
    out << "</settings>\n";
    out.close();
  } catch (...) {
    // TODO(localize).
    m_pMsgs->Message("Failed to save the settings", true /* interrupt */);
    return false;
  }
  return true;
}
Пример #15
0
void WrappedID3D11DeviceContext::AddEvent(D3D11ChunkType type, string description, ResourceId ctx)
{
	if(ctx == ResourceId()) ctx = m_pDevice->GetResourceManager()->GetOriginalID(m_ResourceID);

	if(GetType() == D3D11_DEVICE_CONTEXT_DEFERRED)
	{
		m_pDevice->GetImmediateContext()->AddEvent(type, description, ctx);
		return;
	}

	FetchAPIEvent apievent;

	apievent.context = ctx;
	apievent.fileOffset = m_CurChunkOffset;
	apievent.eventID = m_CurEventID;

	apievent.eventDesc = widen(description);

	Callstack::Stackwalk *stack = m_pSerialiser->GetLastCallstack();
	if(stack)
	{
		create_array(apievent.callstack, stack->NumLevels());
		memcpy(apievent.callstack.elems, stack->GetAddrs(), sizeof(uint64_t)*stack->NumLevels());
	}

	m_CurEvents.push_back(apievent);

	if(m_State == READING)
		m_Events.push_back(apievent);
}
Пример #16
0
int directory_exists(std::string dname) {
  DWORD file_attr;
  tstring tstr_dname = widen(dname);
  file_attr = GetFileAttributesW(tstr_dname.c_str());
  return (file_attr != INVALID_FILE_ATTRIBUTES &&
    (file_attr & FILE_ATTRIBUTE_DIRECTORY));
}
Пример #17
0
	implementation(size_t output_channels, size_t input_channels, size_t output_sample_rate, size_t input_sample_rate, AVSampleFormat output_sample_format, AVSampleFormat input_sample_format)
		: output_channels_(output_channels)
		, output_sample_format_(output_sample_format)
		, input_channels_(input_channels)
		, input_sample_format_(input_sample_format)
	{
		if(input_channels		!= output_channels || 
		   input_sample_rate	!= output_sample_rate ||
		   input_sample_format	!= output_sample_format)
		{	
			auto resampler = av_audio_resample_init(output_channels,		input_channels,
													output_sample_rate,		input_sample_rate,
													output_sample_format,	input_sample_format,
													16, 10, 0, 0.8);

			buffer2_.resize(AVCODEC_MAX_AUDIO_FRAME_SIZE*2);

			char sample_fmt_string[200];
			av_get_sample_fmt_string(sample_fmt_string, 200, input_sample_format);

			CASPAR_LOG(warning) << L"[audio-resampler]"		
								<< L" sample-rate: "	<< input_sample_rate 
								<< L" channels: "		<< input_channels 
								<< L" sample-fmt: "		<< widen(sample_fmt_string);

			if(resampler)
				resampler_.reset(resampler, audio_resample_close);
			else
				BOOST_THROW_EXCEPTION(caspar_exception());
		}		
	}
Пример #18
0
bool WrappedOpenGL::Serialise_glClearBufferfi(GLenum buffer, GLint drawbuffer, GLfloat depth, GLint stencil)
{
	SERIALISE_ELEMENT(GLenum, buf, buffer);
	SERIALISE_ELEMENT(int32_t, draw, drawbuffer);
	SERIALISE_ELEMENT(float, d, depth);
	SERIALISE_ELEMENT(int32_t, s, stencil);
	
	if(m_State <= EXECUTING)
		m_Real.glClearBufferfi(buf, draw, d, s);
	
	const string desc = m_pSerialiser->GetDebugStr();

	if(m_State == READING)
	{
		AddEvent(CLEARBUFFERFI, desc);
		string name = "glClearBufferfi(" +
						ToStr::Get(buf) + ", " +
						ToStr::Get(draw) + ")";

		FetchDrawcall draw;
		draw.name = widen(name);
		draw.flags |= eDraw_Clear;

		AddDrawcall(draw, true);
	}

	return true;
}
Пример #19
0
ResourceId ReplayRenderer::BuildCustomShader(const wchar_t *entry, const wchar_t *source, const uint32_t compileFlags, ShaderStageType type, rdctype::wstr *errors)
{
	ResourceId id;
	string errs;
	
	switch(type)
	{
		case eShaderStage_Vertex:
		case eShaderStage_Hull:
		case eShaderStage_Domain:
		case eShaderStage_Geometry:
		case eShaderStage_Pixel:
		case eShaderStage_Compute:
			break;
		default:
			RDCERR("Unexpected type in BuildShader!");
			return ResourceId();
	}

	m_pDevice->BuildCustomShader(narrow(source), narrow(entry), compileFlags, type, &id, &errs);

	if(id != ResourceId())
		m_CustomShaders.insert(id);
	
	if(errors) *errors = widen(errs);

	return id;
}
Пример #20
0
bool WrappedOpenGL::Serialise_glClearBufferuiv(GLenum buffer, GLint drawbuffer, const GLuint *value)
{
	SERIALISE_ELEMENT(GLenum, buf, buffer);
	SERIALISE_ELEMENT(int32_t, draw, drawbuffer);
	
	{
		uint32_t v[4];
		if(value) memcpy(v, value, sizeof(v));

		m_pSerialiser->Serialise<4>("value", v);
		
		if(m_State <= EXECUTING)
			m_Real.glClearBufferuiv(buf, draw, v);
	}
	
	const string desc = m_pSerialiser->GetDebugStr();

	if(m_State == READING)
	{
		AddEvent(CLEARBUFFERUI, desc);
		string name = "glClearBufferuiv(" +
						ToStr::Get(buf) + ", " +
						ToStr::Get(draw) + ")";

		FetchDrawcall draw;
		draw.name = widen(name);
		draw.flags |= eDraw_Clear;

		AddDrawcall(draw, true);
	}

	return true;
}
Пример #21
0
void console_message_handlert::print(
  unsigned level,
  const std::string &message)
{
  if(verbosity<level)
    return;

  #ifdef _WIN32
  HANDLE out_handle=
    GetStdHandle((level>1)?STD_OUTPUT_HANDLE:STD_ERROR_HANDLE);

  // We use UTF16 when we write to the console,
  // but we write UTF8 otherwise.

  DWORD consoleMode;
  if(GetConsoleMode(out_handle, &consoleMode))
  {
    // writing to the console
    std::wstring wide_message=widen(message);

    DWORD number_written;

    WriteConsoleW(
      out_handle, wide_message.c_str(),
      (DWORD)wide_message.size(), &number_written, NULL);

    WriteConsoleW(out_handle, L"\r\n", 2, &number_written, NULL);
  }
  else
  {
    // writing to a file

    if(level>=4)
    {
      std::cout << message << '\n';

      if(level<=6)
        std::cout << std::flush;
    }
    else
      std::cerr << message << '\n' << std::flush;
  }
  #else
  // We flush after messages of level 6 or lower.
  // We don't for messages of level 7 or higher to improve performance,
  // in particular when writing to NFS.
  // Messages level 3 or lower go to cerr, messages level 4 or
  // above go to cout.

  if(level>=4)
  {
    std::cout << message << '\n';

    if(level<=6)
      std::cout << std::flush;
  }
  else
    std::cerr << message << '\n' << std::flush;
  #endif
}
Пример #22
0
 result_type operator()(From const &from, Traits const &tr) const
 {
     widen_fun<Traits> widen(tr);
     To to(
         boost::make_transform_iterator(detail::data_begin(from), widen)
       , boost::make_transform_iterator(detail::data_end(from), widen)
     );
     return to;
 }
Пример #23
0
bool remove_subvolume(std::string subvolume_folder)
{
#ifdef _WIN32
	return os_remove_nonempty_dir(widen(subvolume_folder));
#else
	int rc=system((btrfs_cmd+" subvolume delete \""+subvolume_folder+"\"").c_str());
	return rc==0;
#endif
}	
Пример #24
0
 CreateProcessParams( char const * appName, char * commandLine,
     LPSECURITY_ATTRIBUTES procAttr, LPSECURITY_ATTRIBUTES threadAttr,
     BOOL inherit, DWORD flags, void * env, char const * curDir,
     LPSTARTUPINFOA pStartupInfo )
     :
     stringSaver_( new StringSaver<wchar_t>() ),
     lpApplicationName( widen( appName ) ),
     lpCommandLine( widen( commandLine ) ),
     lpProcessAttributes( procAttr ),
     lpThreadAttributes( threadAttr ),
     bInheritHandles( inherit ),
     dwCreationFlags( flags ),
     environment( env, ( flags & CREATE_UNICODE_ENVIRONMENT ) != 0 ),
     lpCurrentDirectory( widen( curDir ) ),
     startupInfo( pStartupInfo, *stringSaver_, converter_ )
 {
     postProcessArgs();
 }
Пример #25
0
  void serialize(std::vector<byte> & v) const {
    insert_obj(v, sizeof(WORD), _pt_size);

    auto font_name = widen(_name);
    insert_data(v, 1,
                (byte *) font_name.c_str(),
                (byte *) (font_name.c_str() +
                          font_name.size() + 1));
  }
Пример #26
0
BOOL LASwriterTXT::open(const CHAR* file_name, const LASheader* header, const CHAR* parse_string, const CHAR* separator)
{
  if (file_name == 0)
  {
    fprintf(stderr,"ERROR: file name pointer is zero\n");
    return FALSE;
  }

  file = fopen(widen(file_name).c_str(), widen("w").c_str());

  if (file == 0)
  {
    fprintf(stderr, "ERROR: cannot open file '%s'\n", file_name);
    return FALSE;
  }

  close_file = TRUE;

  return open(file, header, parse_string, separator);
}
Пример #27
0
std::wstring WMessageResourceBundle::getValue(const WMessage& message)
{
  std::wstring result;

  for (unsigned i = 0; i < messageResources_.size(); ++i) {
    if (messageResources_[i]->getValue(message, result))
      return result;
  }

  return L"??" + widen(message.key()) + L"??";
}
Пример #28
0
bool create_snapshot(int mode, std::string snapshot_src, std::string snapshot_dst)
{
#ifdef _WIN32
	return CopyFolder(widen(snapshot_src), widen(snapshot_dst));
#else
	if(mode==mode_btrfs)
	{
		int rc=exec_wait(find_btrfs_cmd(), true, "subvolume", "snapshot", snapshot_src.c_str(), snapshot_dst.c_str(), NULL);
		chown_dir(snapshot_dst);
		return rc==0;
	}
	else if(mode==mode_zfs)
	{
		zfs_elevate();
		int rc=exec_wait(find_zfs_cmd(), true, "clone", (snapshot_src+"@ro").c_str(), snapshot_dst.c_str(), NULL);
		chown_dir(snapshot_dst);
		return rc==0;
	}
	return false;
#endif
}
Пример #29
0
std::string toUTF8(const std::string& s)
{
#ifndef WT_NO_STD_WSTRING
  return toUTF8(widen(s));
#else
  // You may want to rewrite this for your system
  std::string retval = s;
  for(std::size_t i = 0; i < retval.size(); ++i)
    if (retval[i] > 127) retval[i] = '?';
  return s;
#endif
}
Пример #30
0
bool set_working_directory(string dname) {
  tstring tstr_dname = widen(dname);
  replace(tstr_dname.begin(), tstr_dname.end(), '/', '\\');
  if (SetCurrentDirectoryW(tstr_dname.c_str()) != 0) {
    WCHAR wstr_buffer[MAX_PATH + 1];
    if (GetCurrentDirectoryW(MAX_PATH + 1, wstr_buffer) != 0) {
      working_directory = add_slash(shorten(wstr_buffer));
      return true;
    }
  }

  return false;
}