File: Engine.cpp

package info (click to toggle)
goplay 0.9.1%2Bnmu1
  • links: PTS, VCS
  • area: main
  • in suites: buster, stretch
  • size: 728 kB
  • ctags: 453
  • sloc: cpp: 3,431; ansic: 996; makefile: 88; sh: 35
file content (369 lines) | stat: -rw-r--r-- 10,892 bytes parent folder | download
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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
/*
 * Backend engine for game installer UI
 *
 * Copyright (C) 2003--2013  Enrico Zini <enrico@debian.org>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

#include "Engine.h"

#include <wibble/string.h>
#include <wibble/regexp.h>
#include <iostream>
#include <fstream>

using namespace std;
using namespace wibble;
using namespace ept::apt;
using namespace ept::debtags;

Engine::Engine()
	: m_db("/var/lib/apt-xapian-index/index"), m_stem("en"), m_filter_state(ANY), m_dirty(true), m_max(0), m_popcon_validx(-1)
{
	m_qp.set_default_op(Xapian::Query::OP_AND);
        m_qp.set_database(m_db);
        m_qp.set_stemmer(m_stem);
        m_qp.set_stemming_strategy(Xapian::QueryParser::STEM_SOME);
        m_qp.add_prefix("pkg", "XP");
        m_qp.add_boolean_prefix("tag", "XT");
        m_qp.add_boolean_prefix("sec", "XS");

        // Read the Xapian value index used for popcon data
        std::ifstream in;
        in.open("/var/lib/apt-xapian-index/values", ios::in);
        if (!in.is_open() || in.fail())
            m_popcon_validx = -1;
        ERegexp match_line("^app-popcon[ \t]+([0-9]+)", 2);
        string line;
        while (true)
        {
            getline(in, line);
            if (in.fail()) break;
            if (in.eof()) break;
            if (match_line.match(line))
            {
                m_popcon_validx = strtoul(match_line[1].c_str(), 0, 10);
                break;
            }
        }
}

struct EngineMatchDecider : public Xapian::MatchDecider
{
	Engine& e;
	EngineMatchDecider(Engine& e) : e(e) {}

	virtual bool operator()(const Xapian::Document &doc) const
	{
		// Filter out results that apt doesn't know
		if (!e.apt().isValid(doc.get_data()))
			return false;

		// Finally filter by installed state if requested
		Engine::State s = e.getInstalledFilter();
		if (s != Engine::ANY)
		{
			PackageState state = e.apt().state(doc.get_data());
			if (s == Engine::INSTALLED && !state.isInstalled())
				return false;
			if (s == Engine::NOTINSTALLED && state.isInstalled())
				return false;
		}
		return true;
	}
};

static Xapian::Query allGames(Vocabulary& voc, const std::string& facet="game")
{
	set<std::string> games = voc.tags(facet);
	vector<string> terms;
	for (set<std::string>::const_iterator i = games.begin();
			i != games.end(); ++i)
		terms.push_back("XT" + *i);
	return Xapian::Query(Xapian::Query::OP_OR, terms.begin(), terms.end());
}

Xapian::Query Engine::makeQuery()
{
	Xapian::Query query;
	Xapian::Query kwquery;
	Xapian::Query typequery;
	Xapian::Query ifacequery;

	if (!m_filter_keywords.empty())
	{
		// Add prefixes to tag names
		Splitter splitter("[ \t]*,[ \t]*", REG_EXTENDED);
		vector<string> kw;
		for (Splitter::const_iterator i = splitter.begin(m_filter_keywords);
				i != splitter.end(); ++i)
		{
			if (m_vocabulary.hasTag(*i))
				kw.push_back("tag:" + *i);
			else
				kw.push_back(*i);
		}
		bool do_partial = not (kw.size() == 1 and kw[0].size() < 3);

		kwquery = m_qp.parse_query(str::join(kw.begin(), kw.end(), " "),
				Xapian::QueryParser::FLAG_BOOLEAN |
				Xapian::QueryParser::FLAG_LOVEHATE |
				Xapian::QueryParser::FLAG_BOOLEAN_ANY_CASE |
				Xapian::QueryParser::FLAG_WILDCARD |
				(do_partial ? Xapian::QueryParser::FLAG_PARTIAL : 0) |
				Xapian::QueryParser::FLAG_PURE_NOT |
				Xapian::QueryParser::FLAG_SPELLING_CORRECTION);
	}
	if (!m_filter_type.empty())
		typequery = Xapian::Query("XT"+m_filter_type);
	if (!m_filter_iface.empty())
		ifacequery = Xapian::Query("XT"+m_filter_iface);
		
	if (kwquery.empty())
		if (typequery.empty())
			if (ifacequery.empty())
			{
				// If there is no query, default to querying all games
				query = allGames(voc(), mainFacet);
			}
			else
			{
				// Otherwise, all games with given interface
				query = Xapian::Query(Xapian::Query::OP_AND, ifacequery, allGames(voc(), mainFacet));
			}
		else
			if (ifacequery.empty())
				query = typequery;
			else
				query = Xapian::Query(Xapian::Query::OP_AND, ifacequery, typequery);
	else
		if (typequery.empty())
			if (ifacequery.empty())
				query = Xapian::Query(Xapian::Query::OP_AND, kwquery, allGames(voc(), mainFacet));
			else
				query = Xapian::Query(Xapian::Query::OP_AND, kwquery,
							Xapian::Query(Xapian::Query::OP_AND, ifacequery, allGames(voc(), mainFacet)));
		else
			if (ifacequery.empty())
				query = Xapian::Query(Xapian::Query::OP_AND, kwquery, typequery);
			else
				query = Xapian::Query(Xapian::Query::OP_AND, kwquery,
							Xapian::Query(Xapian::Query::OP_AND, typequery, ifacequery));

	// We always want programs, so always AND it here
	return Xapian::Query(Xapian::Query::OP_AND, globalFilter, query);
}

float Engine::read_popcon(const Xapian::Document& doc) const
{
    if (m_popcon_validx == -1) return 0;
    string val = doc.get_value(m_popcon_validx);
    if (val.empty()) return 0;
    return Xapian::sortable_unserialise(val);
}

void Engine::recompute()
{
	EngineMatchDecider md(*this);

	// Clear existing results
	m_results.clear();
	m_types.clear();
	m_interfaces.clear();
	m_res_max = 0;

	//cerr << "Engine recompute:" << endl;

	// Compute the types
	if (!m_filter_type.empty())
	{
		//cerr << "  filter type: " << m_filter_type.fullname() << endl;
		std::string tmp = m_filter_type;
		m_filter_type = std::string();
		Xapian::Enquire enquire(m_db);
		enquire.set_query(makeQuery());

		// Get all the results out of Xapian
		bool done = false;
		for (size_t pos = 0; !done; pos += 50)
		{
			Xapian::MSet matches = enquire.get_mset(pos, 50, 0, 0, &md);
			if (matches.size() < 50)
				done = true;
			for (Xapian::MSetIterator i = matches.begin(); i != matches.end(); ++i)
			{
				// Get all the game and interface tags in the result set
				set<std::string> tags = m_debtags.getTagsOfItem(i.get_document().get_data());
				for (set<std::string>::const_iterator j = tags.begin();
						j != tags.end(); ++j)
					if (voc::getfacet(*j) == mainFacet)
						m_types.insert(*j);
			}
		}
		m_filter_type = tmp;
	} else {
		//cerr << "  no filter type" << endl;
	}

	// Compute the interfaces
	if (!m_filter_iface.empty())
	{
		//cerr << "  filter iface: " << m_filter_iface.fullname() << endl;
		std::string tmp = m_filter_iface;
		m_filter_iface = std::string();
		Xapian::Enquire enquire(m_db);
		enquire.set_query(makeQuery());

		// Get all the results out of Xapian
		bool done = false;
		for (size_t pos = 0; !done; pos += 50)
		{
			Xapian::MSet matches = enquire.get_mset(pos, 50, 0, 0, &md);
			if (matches.size() < 50)
				done = true;
			for (Xapian::MSetIterator i = matches.begin(); i != matches.end(); ++i)
			{
				// Get all the game and interface tags in the result set
				set<std::string> tags = m_debtags.getTagsOfItem(i.get_document().get_data());
				for (set<std::string>::const_iterator j = tags.begin();
						j != tags.end(); ++j)
					if (voc::getfacet(*j) == secondaryFacet)
						m_interfaces.insert(*j);
			}
		}
		m_filter_iface = tmp;
	} else {
		//cerr << "  no filter iface" << endl;
	}

	Xapian::Enquire enquire(m_db);
	enquire.set_query(makeQuery());

	//cerr << "  filter query: " << enquire.get_query().get_description() << endl;

	// Get all the results out of Xapian
	bool done = false;
	for (size_t pos = 0; !done; pos += 50)
	{
		Xapian::MSet matches = enquire.get_mset(pos, 50, 0, 0, &md);
		if (matches.size() < 50)
			done = true;
		for (Xapian::MSetIterator i = matches.begin(); i != matches.end(); ++i)
		{
			// Stop producing if the quality goes below a cutoff point
			// FIXME: hardcoded value, but I can't see a reason to make it
			// configurable yet
			// FIXME: can be done adaptive, and can be done using set_cutoff in the
			// enquire
			//if (i.get_percent() < 40)
				//break;

			Result res;
			Xapian::Document doc = i.get_document();
			res.name = doc.get_data();
			res.popcon = read_popcon(doc);
			res.relevance = i.get_percent();

			if (res.popcon > m_res_max)
				m_res_max = res.popcon;

			m_results.push_back(res);

			// Get all the game and interface tags in the result set
			// only for type or filter when they are not set
			if (m_filter_type.empty() || m_filter_iface.empty())
			{
				set<std::string> tags = m_debtags.getTagsOfItem(res.name);
				for (set<std::string>::const_iterator j = tags.begin();
						j != tags.end(); ++j)
					if (m_filter_type.empty() && voc::getfacet(*j) == mainFacet)
						m_types.insert(*j);
					else if (m_filter_iface.empty() && voc::getfacet(*j) == secondaryFacet)
						m_interfaces.insert(*j);
			}
		}
	}
	// Always keep the currently selected items in the lists
	if (!m_filter_type.empty())
		m_types.insert(m_filter_type);
	if (!m_filter_iface.empty())
		m_interfaces.insert(m_filter_iface);


	if (m_res_max > m_max)
		m_max = m_res_max;

    if (m_filter_keywords.empty())
		sort(m_results.begin(), m_results.end());

	m_dirty = false;
}

std::vector<Result> Engine::related(const std::string& name, int count) const
{
	Xapian::Enquire enquire(m_db);
	
	// Retrieve the document for the given package
	enquire.set_query(Xapian::Query("XP"+name));
	Xapian::MSet matches = enquire.get_mset(0, 1);
	Xapian::MSetIterator mi = matches.begin();
	if (mi == matches.end()) return std::vector<Result>();
	Xapian::Document doc = mi.get_document();

	// Retrieve the list of similar documents
	enquire.set_query(Xapian::Query(Xapian::Query::OP_OR, doc.termlist_begin(), doc.termlist_end()));
	matches = enquire.get_mset(0, count);
	mi = matches.begin();
	if (mi == matches.end()) return std::vector<Result>();
	// Skip the first element, which is the package itself
	vector<Result> results;
	for (++mi; mi != matches.end(); ++mi)
	{
		Result res;
		Xapian::Document doc = mi.get_document();
		res.name = doc.get_data();
		res.popcon = read_popcon(doc);
		res.relevance = mi.get_percent();
		results.push_back(res);
	}
	return results;
}

void Engine::setKeywordFilter(const std::string& keywords)
{
	m_filter_keywords = keywords;
	m_dirty = true;
}

void Engine::setTypeFilter(const std::string& tag)
{
	m_filter_type = tag;
	m_dirty = true;
}

void Engine::setInterfaceFilter(const std::string& tag)
{
	m_filter_iface = tag;
	m_dirty = true;
}

void Engine::setInstalledFilter(State state)
{
	m_filter_state = state;
	m_dirty = true;
}

// vim:set ts=4 sw=4: