Initial commit

This commit is contained in:
Přemysl Eric Janouch 2013-05-04 16:14:25 +02:00
commit 4f4a86529a
5 changed files with 1604 additions and 0 deletions

13
.gitignore vendored Normal file
View File

@ -0,0 +1,13 @@
# Backup files
*.*~
# Compile output
/sdcli
*.o
# IDE project files
/sdcli.creator*
/sdcli.includes
/sdcli.files
/sdcli.config
# Blah
/GNUmakefile
/.clang_complete

22
Makefile Normal file
View File

@ -0,0 +1,22 @@
SHELL = /bin/sh
pkgs = ncursesw glib-2.0 gio-2.0
targets = sdcli
CC = clang
CFLAGS = -ggdb -std=gnu99 -Wall -Wextra -Wno-missing-field-initializers \
`pkg-config --cflags $(pkgs)`
LDFLAGS = `pkg-config --libs $(pkgs)`
.PHONY: all clean
all: $(targets)
clean:
rm -f $(targets) *.o
sdcli: sdcli.o stardict.o
$(CC) $^ -o $@ $(LDFLAGS)
%.o: %.c
$(CC) $(CFLAGS) -c $< -o $@

274
sdcli.c Normal file
View File

@ -0,0 +1,274 @@
/*
* StarDict console UI
*
* Copyright (c) 2013, Přemysl Janouch <p.janouch@gmail.com>
* All rights reserved.
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
* SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
* OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
* CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
*/
#define _XOPEN_SOURCE_EXTENDED /**< Yes, we want ncursesw. */
#include <stdio.h>
#include <stdlib.h>
#include <locale.h>
#include <stdarg.h>
#include <limits.h>
#include <glib.h>
#include <gio/gio.h>
#include <ncurses.h>
#include <unistd.h>
#include <poll.h>
#include <errno.h>
#include <signal.h>
#include "stardict.h"
#define KEY_ESCAPE 27 /**< Curses doesn't define this. */
// --- Utilities ---------------------------------------------------------------
static void
display (const gchar *format, ...)
{
va_list ap;
va_start (ap, format);
vw_printw (stdscr, format, ap);
va_end (ap);
refresh ();
}
static gchar *
wchar_to_mb (wchar_t ch)
{
/* Convert the character back to a multi-byte sequence. */
static gchar buffer[MB_LEN_MAX + 1];
size_t len = wcrtomb (buffer, ch, NULL);
/* This shouldn't happen. It would mean that the user has
* somehow managed to enter something inexpressable in the
* current locale. */
if (len == (size_t) -1)
abort ();
/* Here I hope the buffer doesn't overflow. Who uses
* shift states nowadays, anyway? */
if (wcrtomb (buffer + len, L'\0', NULL) == (size_t) -1)
abort ();
return buffer;
}
static const gchar *
wchar_to_mb_escaped (wchar_t ch)
{
switch (ch)
{
case L'\r': return "\\r";
case L'\n': return "\\n";
case L'\t': return "\\t";
default: return wchar_to_mb (ch);
}
}
static int
poll_restart (struct pollfd *fds, nfds_t nfds, int timeout)
{
int ret;
do
ret = poll (fds, nfds, timeout);
while (ret == -1 && errno == EINTR);
return ret;
}
// --- SIGWINCH ----------------------------------------------------------------
static int g_winch_pipe[2]; /**< SIGWINCH signalling pipe. */
static void (*g_old_winch_handler) (int);
static void
winch_handler (int signum)
{
/* Call the ncurses handler. */
if (g_old_winch_handler)
g_old_winch_handler (signum);
/* And wake up the poll() call. */
write (g_winch_pipe[1], "x", 1);
}
static void
install_winch_handler (void)
{
struct sigaction act, oldact;
act.sa_handler = winch_handler;
act.sa_flags = SA_RESTART;
sigemptyset (&act.sa_mask);
sigaction (SIGWINCH, &act, &oldact);
/* Save the ncurses handler. */
if (oldact.sa_handler != SIG_DFL
&& oldact.sa_handler != SIG_IGN)
g_old_winch_handler = oldact.sa_handler;
}
// --- Event handlers ----------------------------------------------------------
typedef struct
{
wint_t code;
guint is_char : 1;
MEVENT mouse;
}
CursesEvent;
static gboolean
process_curses_event (CursesEvent *event)
{
if (!event->is_char)
{
switch (event->code)
{
case KEY_RESIZE:
display ("Screen has been resized to %u x %u\n",
COLS, LINES);
break;
case KEY_MOUSE:
display ("Mouse event at (%d, %d), state %#lx\n",
event->mouse.x, event->mouse.y, event->mouse.bstate);
break;
default:
display ("Keyboard event: non-character: %u\n",
event->code);
}
return TRUE;
}
display ("Keyboard event: character: '%s'\n",
wchar_to_mb_escaped (event->code));
if (event->code == L'q' || event->code == KEY_ESCAPE)
{
display ("Quitting...\n");
return FALSE;
}
return TRUE;
}
static gboolean
process_stdin_input (void)
{
CursesEvent event;
int sta;
while ((sta = get_wch (&event.code)) != ERR)
{
event.is_char = (sta == OK);
if (sta == KEY_CODE_YES && event.code == KEY_MOUSE
&& getmouse (&event.mouse) == ERR)
abort ();
if (!process_curses_event (&event))
return FALSE;
}
return TRUE;
}
static gboolean
process_winch_input (int fd)
{
char c;
read (fd, &c, 1);
return process_stdin_input ();
}
// --- Main --------------------------------------------------------------------
int
main (int argc, char *argv[])
{
static GOptionEntry entries[] =
{
{ NULL }
};
if (!setlocale (LC_ALL, ""))
abort ();
GError *error = NULL;
GOptionContext *ctx = g_option_context_new ("- StarDict console UI");
g_option_context_add_main_entries (ctx, entries, NULL);
if (!g_option_context_parse (ctx, &argc, &argv, &error))
{
g_print ("option parsing failed: %s\n", error->message);
exit (EXIT_FAILURE);
}
if (!initscr ()
|| cbreak () == ERR
|| noecho () == ERR)
abort ();
keypad (stdscr, TRUE); /* Enable character processing. */
nodelay (stdscr, TRUE); /* Don't block on get_wch(). */
mousemask (ALL_MOUSE_EVENTS, NULL);
display ("Press Q, Escape or ^C to quit\n");
if (pipe (g_winch_pipe) == -1)
abort ();
install_winch_handler ();
// --- Message loop ------------------------------------------------------------
struct pollfd pollfd[2];
pollfd[0].fd = fileno (stdin);
pollfd[0].events = POLLIN;
pollfd[1].fd = g_winch_pipe[0];
pollfd[1].events = POLLIN;
while (TRUE)
{
if (poll_restart (pollfd, 3, -1) == -1)
abort ();
if ((pollfd[0].revents & POLLIN)
&& !process_stdin_input ())
break;
if ((pollfd[1].revents & POLLIN)
&& !process_winch_input (pollfd[2].fd))
break;
}
// --- Cleanup -----------------------------------------------------------------
endwin ();
if (close (g_winch_pipe[0]) == -1
|| close (g_winch_pipe[1]) == -1)
abort ();
return 0;
}

1081
stardict.c Normal file

File diff suppressed because it is too large Load Diff

214
stardict.h Normal file
View File

@ -0,0 +1,214 @@
/*
* stardict.h: StarDict API
*
* This module doesn't cover all the functionality available to StarDict
* dictionaries, it should however be good enough for most of them that are
* freely available on the Internet.
*
* Copyright (c) 2013, Přemysl Janouch <p.janouch@gmail.com>
* All rights reserved.
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
* SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
* OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
* CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
*/
#ifndef STARDICT_H
#define STARDICT_H
/** An object intended for interacting with a dictionary. */
typedef struct stardict_dict StardictDict;
typedef struct stardict_dict_class StardictDictClass;
/** Overall information about a particular dictionary. */
typedef struct stardict_info StardictInfo;
/** Handles the task of moving around the dictionary. */
typedef struct stardict_iterator StardictIterator;
typedef struct stardict_iterator_class StardictIteratorClass;
/** Contains the decoded data for a single word definition. */
typedef struct stardict_entry StardictEntry;
typedef struct stardict_entry_class StardictEntryClass;
/** A single field of a word definition. */
typedef struct stardict_entry_field StardictEntryField;
/* GObject boilerplate. */
#define STARDICT_TYPE_DICT (stardict_dict_get_type ())
#define STARDICT_DICT(obj) \
(G_TYPE_CHECK_INSTANCE_CAST ((obj), \
STARDICT_TYPE_DICT, StardictDict))
#define STARDICT_IS_DICT(obj) \
(G_TYPE_CHECK_INSTANCE_TYPE ((obj), \
STARDICT_TYPE_DICT))
#define STARDICT_DICT_CLASS(klass) \
(G_TYPE_CHECK_CLASS_CAST ((klass), \
STARDICT_TYPE_DICT, StardictDictClass))
#define STARDICT_IS_DICT_CLASS(klass) \
(G_TYPE_CHECK_CLASS_TYPE ((klass), \
STARDICT_TYPE_DICT))
#define STARDICT_DICT_GET_CLASS(obj) \
(G_TYPE_INSTANCE_GET_CLASS ((obj), \
STARDICT_TYPE_DICT, StardictDictClass))
#define STARDICT_TYPE_ITERATOR (stardict_iterator_get_type ())
#define STARDICT_ITERATOR(obj) \
(G_TYPE_CHECK_INSTANCE_CAST ((obj), \
STARDICT_TYPE_ITERATOR, StardictIterator))
#define STARDICT_IS_ITERATOR(obj) \
(G_TYPE_CHECK_INSTANCE_TYPE ((obj), \
STARDICT_TYPE_ITERATOR))
#define STARDICT_ITERATOR_CLASS(klass) \
(G_TYPE_CHECK_CLASS_CAST ((klass), \
STARDICT_TYPE_ITERATOR, StardictIteratorClass))
#define STARDICT_IS_ITERATOR_CLASS(klass) \
(G_TYPE_CHECK_CLASS_TYPE ((klass), \
STARDICT_TYPE_ITERATOR))
#define STARDICT_ITERATOR_GET_CLASS(obj) \
(G_TYPE_INSTANCE_GET_CLASS ((obj), \
STARDICT_TYPE_ITERATOR, StardictIteratorClass))
#define STARDICT_TYPE_ENTRY (stardict_entry_get_type ())
#define STARDICT_ENTRY(obj) \
(G_TYPE_CHECK_INSTANCE_CAST ((obj), \
STARDICT_TYPE_ENTRY, StardictEntry))
#define STARDICT_IS_ENTRY(obj) \
(G_TYPE_CHECK_INSTANCE_TYPE ((obj), \
STARDICT_TYPE_ENTRY))
#define STARDICT_ENTRY_CLASS(klass) \
(G_TYPE_CHECK_CLASS_CAST ((klass), \
STARDICT_TYPE_ENTRY, StardictEntryClass))
#define STARDICT_IS_ENTRY_CLASS(klass) \
(G_TYPE_CHECK_CLASS_TYPE ((klass), \
STARDICT_TYPE_ENTRY))
#define STARDICT_ENTRY_GET_CLASS(obj) \
(G_TYPE_INSTANCE_GET_CLASS ((obj), \
STARDICT_TYPE_ENTRY, StardictEntryClass))
// --- Errors ------------------------------------------------------------------
/** General error type. */
typedef enum {
STARDICT_ERROR_FILE_NOT_FOUND, //!< Some file was not found
STARDICT_ERROR_INVALID_DATA //!< Dictionary contains invalid data
} StardictError;
#define STARDICT_ERROR (stardict_error_quark ())
GQuark stardict_error_quark (void);
// --- Dictionary information --------------------------------------------------
const gchar *stardict_info_get_path (StardictInfo *sdi) G_GNUC_PURE;
const gchar *stardict_info_get_book_name (StardictInfo *sdi) G_GNUC_PURE;
gsize stardict_info_get_word_count (StardictInfo *sd) G_GNUC_PURE;
void stardict_info_free (StardictInfo *sdi);
GList *stardict_list_dictionaries (const gchar *path);
// --- Dictionaries ------------------------------------------------------------
struct stardict_dict
{
GObject parent_instance;
StardictInfo * info; //!< General information about the dict
GArray * index; //!< Word index
GArray * synonyms; //!< Synonyms
gpointer dict; //!< Dictionary data
gsize dict_length; //!< Length of the dict data in bytes
};
struct stardict_dict_class
{
GObjectClass parent_class;
};
GType stardict_dict_get_type (void);
StardictDict *stardict_dict_new (const gchar *filename, GError **error);
StardictDict *stardict_dict_new_from_info (StardictInfo *sdi, GError **error);
StardictInfo *stardict_dict_get_info (StardictDict *sd);
gchar **stardict_dict_get_synonyms (StardictDict *sd, const gchar *word);
StardictIterator *stardict_dict_search
(StardictDict *sd, const gchar *word, gboolean *success);
// --- Dictionary iterators ----------------------------------------------------
struct stardict_iterator
{
GObject parent_instance;
StardictDict * owner; //!< The related dictionary
gint64 offset; //!< Index within the dictionary
};
struct stardict_iterator_class
{
GObjectClass parent_class;
};
GType stardict_iterator_get_type (void);
StardictIterator *stardict_iterator_new (StardictDict *sd, guint32 index);
const gchar *stardict_iterator_get_word (StardictIterator *sdi) G_GNUC_PURE;
StardictEntry *stardict_iterator_get_entry (StardictIterator *sdi);
gboolean stardict_iterator_is_valid (StardictIterator *sdi) G_GNUC_PURE;
gint64 stardict_iterator_get_offset (StardictIterator *sdi) G_GNUC_PURE;
void stardict_iterator_set_offset
(StardictIterator *sdi, gint64 offset, gboolean relative);
/** Go to the next entry. */
#define stardict_iterator_next(sdi) \
(stardict_iterator_set_offset (sdi, 1, TRUE))
/** Go to the previous entry. */
#define stardict_iterator_prev(sdi) \
(stardict_iterator_set_offset (sdi, -1, TRUE))
// --- Dictionary entries ------------------------------------------------------
typedef enum {
STARDICT_FIELD_MEANING = 'm', //!< Word's purely textual meaning
STARDICT_FIELD_LOCALE = 'l', //!< Locale-dependent meaning
STARDICT_FIELD_PANGO = 'g', //!< Pango text markup language
STARDICT_FIELD_PHONETIC = 't', //!< English phonetic string
STARDICT_FIELD_XDXF = 'x', //!< xdxf language
STARDICT_FIELD_YB_KANA = 'y', //!< Chinese YinBiao or Japanese KANA
STARDICT_FIELD_POWERWORD = 'k', //!< KingSoft PowerWord's data
STARDICT_FIELD_MEDIAWIKI = 'w', //!< MediaWiki markup language
STARDICT_FIELD_HTML = 'h', //!< HTML codes
STARDICT_FIELD_RESOURCE = 'r', //!< Resource file list
STARDICT_FIELD_WAV = 'W', //!< WAV file
STARDICT_FIELD_PICTURE = 'P', //!< Picture file
STARDICT_FIELD_X = 'X' //!< Reserved, experimental extensions
} StardictEntryFieldType;
struct stardict_entry_field
{
gchar type; //!< Type of entry (EntryFieldType)
gpointer data; //!< Raw data or null-terminated string
gsize data_size; //!< Size of data, includding any \0
};
struct stardict_entry
{
GObject parent_instance;
GList * fields; //!< List of StardictEntryField's
};
struct stardict_entry_class
{
GObjectClass parent_class;
};
GType stardict_entry_get_type (void);
const GList *stardict_entry_get_fields (StardictEntry *sde) G_GNUC_PURE;
#endif /* ! STARDICT_H */