-
Notifications
You must be signed in to change notification settings - Fork 0
/
translator.cpp
79 lines (70 loc) · 2.02 KB
/
translator.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
#include "translator.h"
#include "logger.h"
#include <iostream>
#include <fstream>
#include <algorithm>
// Initialize singleton_ to nullptr
Translator* Translator::singleton_ = nullptr;
Translator::Translator() {
clear();
}
Translator* Translator::instance() {
if( singleton_ == nullptr ) {
singleton_ = new Translator();
Logger::debug() << "creating Translator singleton" << Logger::endl;
}
return singleton_;
}
void Translator::kill() {
if( singleton_ != nullptr ) {
Logger::debug() << "destroying Translator singleton" << Logger::endl;
delete singleton_;
singleton_ = nullptr;
}
}
void Translator::clear() {
empty_ = true;
dictionary_.clear();
}
void Translator::readDictionary(const std::string& filename) {
// clear map
clear();
// open file
if( filename == "none") {
return;
}
std::ifstream file(filename);
if (!file) {
Logger::error() << tr("unable to read translator file: ") << filename << Logger::endl;
return;
}
// fill map with entries coming from file
std::string str;
while (std::getline(file, str)) {
str = str.substr(2);
int index = str.find_first_of("','");
if( index > 0 ) {
std::string left = str.substr(0,index);
std::string right = str.substr(index+3);
right = right.substr(0, right.length()-2);
dictionary_.insert(std::pair<std::string, std::string>(left,right) );
}
}
empty_ = (dictionary_.size() == 0);
}
std::string tr(const std::string& str) {
std::string result = Translator::instance()->translate(str);
std::replace(result.begin(), result.end(), '%', '\n');
return result;
}
const std::string& Translator::translate(const std::string& str) {
if( empty_ ) return str;
std::map<std::string, std::string>::iterator it = dictionary_.find(str);
if( it == dictionary_.end() ) {
return str;
}
if( it->second == "" ) {
return str;
}
return it->second;
}