Imported version 0.2-1
[mstardict] / src / lib / dict_client.hpp
1 #ifndef _DICT_CLINET_HPP_
2 #define _DICT_CLINET_HPP_
3
4 #include <glib.h>
5 #include <string>
6 #include <memory>
7 #include <map>
8 #include <vector>
9
10 #include "sigc++/sigc++.h"
11
12 namespace DICT {
13         struct Definition {
14                 std::string word_;
15                 std::string data_;
16
17                 Definition(const gchar *word): word_(word) {}
18         };
19         typedef std::vector<Definition> DefList;
20
21         class Cmd {
22         public:
23                 enum State {
24                         START, DATA, FINISH
25                 } state_;
26
27                 Cmd() : state_(START) {}
28                 virtual ~Cmd() {}
29                 virtual const std::string& query() { return query_; }
30                 virtual bool parse(gchar *str, int code) = 0;
31
32                 void send(GIOChannel *channel, GError *&err);
33                 const DefList& result() const { return reslist_; }
34         protected:
35                 std::string query_;
36                 DefList reslist_;
37         };
38 };
39
40 class DictClient {
41 public:
42         typedef std::vector<size_t> IndexList;
43         typedef std::list<std::string> StringList;
44
45         static sigc::signal<void, const std::string&> on_error_;
46         static sigc::signal<void, const IndexList&> on_simple_lookup_end_;
47         static sigc::signal<void, const StringList&> on_complex_lookup_end_;
48
49         DictClient(const char *host, int port = 2628);
50         ~DictClient();
51         void lookup_simple(const gchar *word);
52         void lookup_with_rule(const gchar *word);
53         void lookup_with_fuzzy(const gchar *word);
54         const gchar *get_word(size_t index) const;
55         const gchar *get_word_data(size_t index) const;
56 private:
57         int sd_;
58         GIOChannel *channel_;
59         guint source_id_;
60         std::string host_;
61         int port_;
62         bool is_connected_;
63         std::auto_ptr<DICT::Cmd> cmd_;
64         typedef std::map<size_t, DICT::Definition> DefMap;
65         DefMap defmap_;
66         size_t last_index_;
67         bool simple_lookup_;
68
69         void disconnect();
70         static gboolean on_io_event(GIOChannel *, GIOCondition, gpointer);
71         static int get_status_code(gchar *line);
72         void connect();
73     static void on_resolved(gpointer data, struct hostent *ret);
74         bool parse(gchar *line, int status_code);
75 };
76
77 #endif//!_DICT_CLINET_HPP_