Updated copyright text/header in most source files.
[geda-gaf/peter-b.git] / libgeda / src / s_clib.c
blobb06f13ed90cf8de9f878cdd09543cbc63353d474
1 /* gEDA - GPL Electronic Design Automation
2 * libgeda - gEDA's library
3 * Copyright (C) 1998-2010 gEDA Contributors (see ChangeLog for details)
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111 USA
20 /*! \file s_clib.c
21 * \brief The component library system
23 * <B>clib</B> stands for component library.
25 * The <b>component library</b> is made up of a number of
26 * <b>component sources</b>, each of which in turn makes available a
27 * number of component <b>symbols</b>. Each source may be either a
28 * directory on disk containing symbol files, a command in the system
29 * PATH which can generate gEDA symbol data (e.g. from a database),
30 * or a Scheme function which can do likewise. A component source is
31 * represented by a #CLibSource instance.
33 * The component library system manages component sources and
34 * symbols, and abstracts the interface to the underlying storage.
36 * To initialise the component library, s_clib_init() is called. To
37 * clean up when it is no longer needed, s_clib_free() should be
38 * called.
40 * A directory which contains one or more symbol files in gEDA
41 * format may be used as a component source. Each symbol file should
42 * have a filename ending in ".sym" (case insensitive). A
43 * component source based on a directory can be added using
44 * s_clib_add_directory(). Symbol files with filenames starting with
45 * a period "." are ignored.
47 * An executable program in the system search path may be used as a
48 * component source, and it must conform with the specification given
49 * on page \ref libcmds. A component source based on a command may
50 * be added using s_clib_add_command().
52 * Scheme functions may be used as a component source; for more
53 * information, please see page \ref libscms. A component source
54 * based on Scheme functions may be added using s_clib_add_scm().
56 * Each symbol is identified by its \b name, which is stored in the
57 * saved schematic file. The name must be a valid for storage in a
58 * gEDA schematic file as the "basename" of a "component" object.
59 * For symbols from directory sources, the filename of the symbol is
60 * taken as the symbol name. For a command source, the name may be
61 * any permissible string. Guidelines to follow:
63 * -# Do not begin a symbol name with "EMBEDDED"
64 * -# Do not use whitespace, or any of the characters "<tt>/:!*?</tt>".
65 * -# Try to use unique names.
67 * The component database may be queried using s_clib_search(). A
68 * null-terminated buffer containing symbol data (suitable for
69 * loading using o_read_buffer()) may be obtained using
70 * s_clib_symbol_get_data(). If an exact symbol name is known, the
71 * symbol data may be requested directly using
72 * s_clib_symbol_get_data_by_name().
75 * \section libcmds Library Commands
77 * A program or set of programs can be used as a component source. The procedure used to add such a source from a gEDA rc file is:
79 * <code>
80 * (component-library-command listcmd getcmd name)
81 * </code>
83 * This is implemented by g_rc_component_library_command(), which is
84 * a wrapper for s_clib_add_command().
86 * The list command will be executed with no further arguments, and
87 * should output a list of available symbol names on stdout. The get
88 * command will have a symbol name appended to it as the final
89 * argument, and should output gEDA symbol data on stdout.
91 * If the command cannot successfully complete, it should exit with
92 * non-zero exit status. Anything it has output on stdout will be
93 * ignored, and any stderr output displayed to the user.
95 * \section libscms Library Scheme Procedures
97 * A set of Scheme procedures can be used as a component source. The
98 * procedure used to add such a source from a gEDA rc file is:
100 * <code>
101 * (component-library-funcs listfunc getfunc name)
102 * </code>
104 * This is implemented by g_rc_component_library_funcs(), which is a
105 * wrapper for s_clib_add_scm().
107 * \b listfunc and \b getfunc must both be Guile procedures. \b
108 * listfunc takes no arguments, and returns a list of symbol
109 * names. \b getfunc takes a symbol name as an argument, and returns
110 * gEDA symbol data in a string, or \b \#f if not known.
113 #include <config.h>
115 #include <stdio.h>
116 #include <glib.h>
118 #ifdef HAVE_STRING_H
119 #include <string.h>
120 #endif
122 #ifdef HAVE_LIBDMALLOC
123 #include <dmalloc.h>
124 #endif
126 #ifdef HAVE_SYS_WAIT_H
127 #include <sys/wait.h>
128 #else
129 #define WIFSIGNALED(x) 0
130 #define WTERMSIG(x) 0
131 #define WIFEXITED(x) 1
132 #define WEXITSTATUS(x) 0
133 #endif
135 #include <time.h>
137 #include "libgeda_priv.h"
139 /* Constant definitions
140 * ===================
143 /*! All symbols in directory sources end with this string. Must be
144 * lowercase. */
145 #define SYM_FILENAME_FILTER ".sym"
147 /*! Library command mode used to fetch list of symbols */
148 #define CLIB_LIST_CMD "list"
150 /*! Library command mode used to fetch symbol data */
151 #define CLIB_DATA_CMD "get"
153 /*! Maximum number of symbol cache entries */
154 #define CLIB_MAX_SYMBOL_CACHE 128
155 /*! When symbol cache gets full, remove down to this level */
156 #define CLIB_MIN_SYMBOL_CACHE 96
158 /* Type definitions
159 * ================
162 /*! Valid types of component source */
163 enum CLibSourceType {
164 CLIB_NONE = 0,
165 /*! Directory source */
166 CLIB_DIR,
167 /*! Command source */
168 CLIB_CMD,
169 /*! Guile function source */
170 CLIB_SCM,
173 /*! Stores data about a particular component source */
174 struct _CLibSource {
175 /*! Type of source */
176 enum CLibSourceType type;
177 /*! Name of source */
178 gchar *name;
179 /*! Available symbols (#CLibSymbol) */
180 GList *symbols;
182 /*! Path to directory */
183 gchar *directory;
185 /*! Command & arguments for listing symbols */
186 gchar *list_cmd;
187 /*! Command & arguments for retrieving symbol data */
188 gchar *get_cmd;
190 /*! Scheme function for listing symbols */
191 SCM list_fn;
192 /*! Scheme function for retrieving symbol data */
193 SCM get_fn;
196 /*! Stores data about a particular symbol */
197 struct _CLibSymbol {
198 /*! The source this symbol is available from */
199 CLibSource *source;
200 /*! The name of this symbol */
201 gchar *name;
204 /*! Symbol data cache entry */
205 typedef struct _CacheEntry CacheEntry;
206 struct _CacheEntry {
207 /*! Pointer to symbol */
208 CLibSymbol *ptr;
209 /*! Symbol data */
210 gchar *data;
211 /*! Last access */
212 time_t accessed;
215 /* Static variables
216 * ================
219 /*! Holds the list of all known component sources */
220 static GList *clib_sources = NULL;
222 /*! Caches results of s_clib_search(). The key of the hashtable is a
223 * string describing the search that was carried out, and the value
224 * is a list of symbol pointers. */
225 static GHashTable *clib_search_cache = NULL;
227 /*! Caches symbol data. The key of the hashtable is a symbol pointer,
228 * and the value is a #CacheEntry structure containing the data and
229 * the time it was last used. */
230 static GHashTable *clib_symbol_cache = NULL;
232 /* Local static functions
233 * ======================
235 static void free_symbol (gpointer data, gpointer user_data);
236 static void free_symbol_cache_entry (gpointer data);
237 static void free_source (gpointer data, gpointer user_data);
238 static gint compare_source_name (gconstpointer a, gconstpointer b);
239 static gint compare_symbol_name (gconstpointer a, gconstpointer b);
240 static void cache_find_oldest (gpointer key, gpointer value, gpointer user_data);
241 static gchar *run_source_command (const gchar *command);
242 static CLibSymbol *source_has_symbol (const CLibSource *source,
243 const gchar *name);
244 static gchar *uniquify_source_name (const gchar *name);
245 static void refresh_directory (CLibSource *source);
246 static void refresh_command (CLibSource *source);
247 static void refresh_scm (CLibSource *source);
248 static gchar *get_data_directory (const CLibSymbol *symbol);
249 static gchar *get_data_command (const CLibSymbol *symbol);
250 static gchar *get_data_scm (const CLibSymbol *symbol);
252 /*! \brief Initialise the component library.
253 * \par Function Description
254 * Resets and initialises the component library.
256 * \warning This function must be called before any other functions
257 * from s_clib.c.
259 void s_clib_init ()
261 if (clib_sources != NULL) {
262 s_clib_free ();
265 if (clib_search_cache != NULL) {
266 s_clib_flush_search_cache();
267 } else {
268 clib_search_cache = g_hash_table_new_full ((GHashFunc) g_str_hash,
269 (GEqualFunc)g_str_equal,
270 (GDestroyNotify) g_free,
271 (GDestroyNotify) g_list_free);
274 if (clib_symbol_cache != NULL) {
275 s_clib_flush_symbol_cache();
276 } else {
277 clib_symbol_cache =
278 g_hash_table_new_full ((GHashFunc) g_direct_hash,
279 (GEqualFunc) g_direct_equal,
280 NULL,
281 (GDestroyNotify) free_symbol_cache_entry);
285 /*! \brief Iterator callback for freeing a symbol.
286 * \par Function Description
287 * Private function used only in s_clib.c.
289 static void free_symbol (gpointer data, gpointer user_data)
291 CLibSymbol *symbol = data;
292 if (symbol != NULL) {
293 if (symbol->source != NULL) {
294 symbol->source = NULL;
296 if (symbol->name != NULL) {
297 g_free (symbol->name);
298 symbol->name = NULL;
300 g_free(symbol);
304 /*! \brief Iterator callback for freeing a symbol cache entry.
305 * \par Function Description
306 * Private function used only in s_clib.c.
308 static void free_symbol_cache_entry (gpointer data)
310 CacheEntry *entry = data;
311 g_return_if_fail (entry != NULL);
312 g_free (entry->data);
313 g_free (entry);
316 /*! \brief Iterator callback for freeing a source.
317 * \par Function Description
318 * Private function used only in s_clib.c.
320 static void free_source (gpointer data, gpointer user_data)
322 CLibSource *source = data;
323 if (source != NULL) {
324 if (source->name != NULL) {
325 g_free (source->name);
326 source->name = NULL;
328 if (source->symbols != NULL) {
329 g_list_foreach (source->symbols, (GFunc) free_symbol, NULL);
330 g_list_free (source->symbols);
331 source->symbols = NULL;
333 if (source->directory != NULL) {
334 g_free (source->directory);
335 source->directory = NULL;
337 if (source->list_cmd != NULL) {
338 g_free (source->list_cmd);
339 source->list_cmd = NULL;
341 if (source->get_cmd != NULL) {
342 g_free (source->get_cmd);
343 source->get_cmd = NULL;
345 if (source->type == CLIB_SCM) {
346 scm_gc_unprotect_object (source->list_fn);
347 scm_gc_unprotect_object (source->get_fn);
352 /*! \brief Free all memory used by the component library.
353 * \par Function Description
354 * Should be called at program exit to clean up any remaining data
355 * being used by the component library system.
357 void s_clib_free ()
359 if (clib_sources != NULL) {
360 g_list_foreach (clib_sources, (GFunc) free_source, NULL);
361 g_list_free (clib_sources);
362 clib_sources = NULL;
366 /*! \brief Compare two component sources by name.
367 * \par Function Description
368 * Compare two component sources by name, case-insensitively.
369 * Typically used when calling g_list_sort(). Private function used
370 * only in s_clib.c. Argument order is as strcasecmp().
372 * \param a First source to compare
373 * \param b Second source to compare
375 * \return As strcasecmp().
377 static gint compare_source_name (gconstpointer a, gconstpointer b)
379 const CLibSource *src1 = a;
380 const CLibSource *src2 = b;
382 g_assert (src1 != NULL);
383 g_assert (src2 != NULL);
385 g_assert (src1->name != NULL);
386 g_assert (src2->name != NULL);
388 return strcasecmp(src1->name, src2->name);
391 /*! \brief Compare two component symbols by name.
392 * \par Function Description
393 * Compare two component symbols by name, case-insensitively.
394 * Typically used when calling g_list_sort(). Private function used
395 * only in s_clib.c. Argument order is as strcasecmp().
397 * \param a First symbol to compare
398 * \param b Second symbol to compare
400 * \return As strcasecmp().
402 static gint compare_symbol_name (gconstpointer a, gconstpointer b)
404 const CLibSymbol *sym1 = a;
405 const CLibSymbol *sym2 = b;
407 g_assert (sym1 != NULL);
408 g_assert (sym2 != NULL);
410 g_assert (sym1->name != NULL);
411 g_assert (sym2->name != NULL);
413 return strcasecmp(sym1->name, sym2->name);
416 /*! \brief Iterator callback for finding oldest symbol cache entry
417 * \par Function Description
418 * Private function used only in s_clib.c.
420 static void cache_find_oldest (gpointer key,
421 gpointer value,
422 gpointer user_data)
424 CacheEntry *current = value;
425 CacheEntry **oldest = user_data;
427 if (current->accessed < (*oldest)->accessed) {
428 *oldest = current;
432 /*! \brief Execute a library command.
433 * \par Function Description
434 * Execute a library command, returning the standard output, or \b
435 * NULL if the command fails for some reason. The system \b PATH is
436 * used to find the program to execute.
437 * The command can write messages to the standard error output. They
438 * are forwarded to the libgeda logging mechanism.
440 * Private function used only in s_clib.c.
442 * \todo This is probably generally useful.
444 * \param command Command string to execute.
445 * \return The program's output, or \b NULL on failure.
447 static gchar *run_source_command (const gchar *command)
449 gchar *standard_output = NULL;
450 gchar *standard_error = NULL;
451 gint exit_status;
452 GError *e = NULL;
453 gboolean success = FALSE;
455 g_return_val_if_fail((command != NULL), NULL);
457 g_spawn_command_line_sync (command,
458 &standard_output,
459 &standard_error,
460 &exit_status,
461 &e);
463 if (e != NULL) {
464 s_log_message (_("Library command failed [%s]: %s\n"), command,
465 e->message);
466 g_error_free (e);
468 } else if (WIFSIGNALED(exit_status)) {
469 s_log_message (_("Library command failed [%s]: Uncaught signal %i.\n"),
470 command, WTERMSIG(exit_status));
472 } else if (WIFEXITED(exit_status) && WEXITSTATUS(exit_status)) {
473 s_log_message (_("Library command failed [%s]\n"), command);
474 s_log_message(_("Error output was:\n%s\n"), standard_error);
476 } else {
477 success = TRUE;
480 /* forward library command messages */
481 if (success && standard_error != NULL)
482 s_log_message ("%s", standard_error);
484 g_free (standard_error);
486 if (success) return standard_output;
488 g_free (standard_output);
489 return NULL;
492 /*! \brief Get a list of available component sources.
493 * \par Function Description
494 * Gets the current list of sources.
495 * \warning The GList returned should be freed when no longer
496 * needed. The returned value is not guaranteed to remain valid over
497 * calls to s_clib_add_directory() or s_clib_add_command().
498 * \return A \b GList of CLibSource.
500 GList *s_clib_get_sources (const gboolean sorted)
502 GList *l = g_list_copy(clib_sources);
503 if (sorted) {
504 l = g_list_sort (l, (GCompareFunc) compare_source_name);
506 return l;
509 /*! \brief Find any symbols within a source with a given name.
510 * \par Function Description
511 * Iterates through the symbol list of the given source, checking if
512 * there is already a symbol with the given name. If there is
513 * such a symbol, it is returned.
515 * \param source The source to check.
516 * \param name The symbol name to look for.
517 * \return The matching symbol, or \b NULL if no match was found.
519 static CLibSymbol *source_has_symbol (const CLibSource *source,
520 const gchar *name)
522 GList *symlist;
523 CLibSymbol *symbol;
525 for (symlist = g_list_first(source->symbols);
526 symlist != NULL;
527 symlist = g_list_next(symlist)) {
529 symbol = (CLibSymbol *) symlist->data;
531 if (strcmp (symbol->name, name) == 0) return symbol;
534 return NULL;
537 /*! \brief Make sure a source name is unique.
538 * \par Function Description
539 * Checks if a source already exists with the given \a name. If one
540 * does, appends a number to the source name. If \a name is not
541 * already in use, returns it as is. The return value is always a
542 * newly-allocated string, and should be freed.
543 * it.
545 static gchar *uniquify_source_name (const gchar *name)
547 gchar *newname = NULL;
548 gint i = 0;
550 if (s_clib_get_source_by_name (name) == NULL) {
551 return g_strdup (name);
554 do {
555 g_free (newname);
556 i++;
557 newname = g_strdup_printf ("%s<%i>", name, i);
558 } while (s_clib_get_source_by_name (newname) != NULL);
560 s_log_message (_("Library name [%s] already in use. Using [%s].\n"),
561 name, newname);
563 return newname;
566 /*! \brief Rescan a directory for symbols.
567 * \par Function Description
568 * Rescans a directory for symbols.
570 * \todo Does this need to do something more sane with subdirectories
571 * than just skipping them silently?
573 * Private function used only in s_clib.c.
575 static void refresh_directory (CLibSource *source)
577 CLibSymbol *symbol;
578 GDir *dir;
579 const gchar *entry;
580 gchar *low_entry;
581 gchar *fullpath;
582 gboolean isfile;
583 GError *e = NULL;
585 g_return_if_fail (source != NULL);
586 g_return_if_fail (source->type == CLIB_DIR);
588 /* Clear the current symbol list */
589 g_list_foreach (source->symbols, (GFunc) free_symbol, NULL);
590 g_list_free (source->symbols);
591 source->symbols = NULL;
593 /* Open the directory for reading. */
594 dir = g_dir_open (source->directory, 0, &e);
596 if (e != NULL) {
597 s_log_message (_("Failed to open directory [%s]: %s\n"),
598 source->directory, e->message);
599 g_error_free (e);
600 return;
603 while ((entry = g_dir_read_name (dir)) != NULL) {
604 /* skip ".", ".." & hidden files */
605 if (entry[0] == '.') continue;
607 /* skip subdirectories (for now) */
608 fullpath = g_build_filename (source->directory, entry, NULL);
609 isfile = g_file_test (fullpath, G_FILE_TEST_IS_REGULAR);
610 g_free (fullpath);
611 if (!isfile) continue;
613 /* skip filenames that we already know about. */
614 if (source_has_symbol (source, entry) != NULL) continue;
616 /* skip filenames which don't have the right suffix. */
617 low_entry = g_utf8_strdown (entry, -1);
618 if (!g_str_has_suffix (low_entry, SYM_FILENAME_FILTER)) {
619 g_free (low_entry);
620 continue;
622 g_free (low_entry);
624 /* Create and add new symbol record */
625 symbol = g_new0 (CLibSymbol, 1);
626 symbol->source = source;
627 symbol->name = g_strdup(entry);
629 /* Prepend because it's faster and it doesn't matter what order we
630 * add them. */
631 source->symbols = g_list_prepend (source->symbols, symbol);
634 entry = NULL;
635 g_dir_close (dir);
637 /* Now sort the list of symbols by name. */
638 source->symbols = g_list_sort (source->symbols,
639 (GCompareFunc) compare_symbol_name);
641 s_clib_flush_search_cache();
642 s_clib_flush_symbol_cache();
645 /*! \brief Re-poll a library command for symbols.
646 * \par Function Description
647 * Runs a library command, requesting a list of available symbols,
648 * and updates the source with the new list.
650 * Private function used only in s_clib.c.
652 static void refresh_command (CLibSource *source)
654 gchar *cmdout;
655 TextBuffer *tb;
656 const gchar *line;
657 CLibSymbol *symbol;
658 gchar *name;
660 g_return_if_fail (source != NULL);
661 g_return_if_fail (source->type == CLIB_CMD);
663 /* Clear the current symbol list */
664 g_list_foreach (source->symbols, (GFunc) free_symbol, NULL);
665 g_list_free (source->symbols);
666 source->symbols = NULL;
668 /* Run the command to get the list of symbols */
669 cmdout = run_source_command (source->list_cmd);
670 if (cmdout == NULL) return;
672 /* Use a TextBuffer to help reading out the lines of the output */
673 tb = s_textbuffer_new (cmdout, -1);
675 while (1) {
676 line = s_textbuffer_next_line (tb);
677 if (line == NULL) break;
678 if (line[0] == '.') continue; /* TODO is this sane? */
680 name = remove_nl(g_strdup(line));
682 /* skip symbols already known about */
683 if (source_has_symbol (source, name) != NULL) {
684 g_free (name);
685 continue;
688 symbol = g_new0 (CLibSymbol, 1);
689 symbol->source = source;
690 symbol->name = name;
692 /* Prepend because it's faster and it doesn't matter what order we
693 * add them. */
694 source->symbols = g_list_prepend (source->symbols, symbol);
697 s_textbuffer_free (tb);
698 g_free (cmdout);
700 /* Sort all symbols by name. */
701 source->symbols = g_list_sort (source->symbols,
702 (GCompareFunc) compare_symbol_name);
704 s_clib_flush_search_cache();
705 s_clib_flush_symbol_cache();
708 /*! \brief Re-poll a scheme procedure for symbols.
709 * \par Function Description
710 * Calls a Scheme procedure to obtain a list of available symbols,
711 * and updates the source with the new list
713 * Private function used only in s_clib.c.
715 static void refresh_scm (CLibSource *source)
717 SCM symlist;
718 SCM symname;
719 CLibSymbol *symbol;
720 char *tmp;
722 g_return_if_fail (source != NULL);
723 g_return_if_fail (source->type == CLIB_SCM);
725 /* Clear the current symbol list */
726 g_list_foreach (source->symbols, (GFunc) free_symbol, NULL);
727 g_list_free (source->symbols);
728 source->symbols = NULL;
730 symlist = scm_call_0 (source->list_fn);
732 if (SCM_NCONSP (symlist) && (symlist != SCM_EOL)) {
733 s_log_message (_("Failed to scan library [%s]: Scheme function returned non-list\n"),
734 source->name);
735 return;
738 while (symlist != SCM_EOL) {
739 symname = SCM_CAR (symlist);
740 if (!scm_is_string (symname)) {
741 s_log_message (_("Non-string symbol name while scanning library [%s]\n"),
742 source->name);
743 } else {
744 symbol = g_new0 (CLibSymbol, 1);
745 symbol->source = source;
747 /* Need to make sure that the correct free() function is called
748 * on strings allocated by Guile. */
749 tmp = scm_to_locale_string (symname);
750 symbol->name = g_strdup(tmp);
751 free (tmp);
753 /* Prepend because it's faster and it doesn't matter what order we
754 * add them. */
755 source->symbols = g_list_prepend (source->symbols, symbol);
758 symlist = SCM_CDR (symlist);
761 /* Now sort the list of symbols by name. */
762 source->symbols = g_list_sort (source->symbols,
763 (GCompareFunc) compare_symbol_name);
765 s_clib_flush_search_cache();
766 s_clib_flush_symbol_cache();
769 /*! \brief Rescan all available component libraries.
770 * \par Function Description
771 * Resets the list of symbols available from each source, and
772 * repopulates it from scratch. Useful e.g. for checking for new
773 * symbols.
775 * \bug Disabled for now because it would break cached CLibSymbols used
776 * all over the place (e.g. in #st_object).
778 void s_clib_refresh ()
780 GList *sourcelist;
781 CLibSource *source;
783 for (sourcelist = clib_sources;
784 sourcelist != NULL;
785 sourcelist = g_list_next(sourcelist)) {
787 source = (CLibSource *) sourcelist->data;
788 switch (source->type)
790 case CLIB_DIR:
791 refresh_directory(source);
792 break;
793 case CLIB_CMD:
794 refresh_command (source);
795 break;
796 case CLIB_SCM:
797 refresh_scm (source);
798 break;
799 default:
800 g_critical("s_clib_refresh: source %p has bad source type %i\n",
801 source, (gint) source->type);
802 break;
807 /*! \brief Get a named component source.
808 * \par Function Description
809 * Iterates through the known component sources, checking if there is
810 * a source with the given \a name.
812 * \param name The source name to look for.
814 * \return The matching source, or \b NULL if no match was found.
816 const CLibSource *s_clib_get_source_by_name (const gchar *name)
818 GList *sourcelist;
819 CLibSource *source;
821 for (sourcelist = clib_sources;
822 sourcelist != NULL;
823 sourcelist = g_list_next(sourcelist)) {
825 source = (CLibSource *) sourcelist->data;
826 if (strcmp (source->name, name) == 0) {
827 return source;
831 return NULL;
834 /*! \brief Add a directory of symbol files to the library
835 * \par Function Description
836 * Adds a directory containing symbol files to the library. Only
837 * files ending with #SYM_FILENAME_FILTER are considered to be symbol
838 * files. A \a name may be specified for the source; if \a name is
839 * \b NULL, the basename of the directory as returned by
840 * g_path_get_basename() is used.
842 * \param directory The path of the directory to add.
843 * \param name A descriptive name for the directory.
844 * \return The #CLibSource associated with the directory.
846 const CLibSource *s_clib_add_directory (const gchar *directory,
847 const gchar *name)
849 CLibSource *source;
850 gchar *intname, *realname;
852 if (directory == NULL) {
853 return NULL;
856 if (name == NULL) {
857 intname = g_path_get_basename (directory);
858 realname = uniquify_source_name (intname);
859 g_free (intname);
860 } else {
861 realname = uniquify_source_name (name);
864 source = g_new0 (CLibSource, 1);
865 source->type = CLIB_DIR;
866 source->directory = g_strdup (directory);
867 source->name = realname;
869 refresh_directory (source);
871 /* Sources added later get scanned earlier */
872 clib_sources = g_list_prepend (clib_sources, source);
874 return source;
877 /*! \brief Add symbol-generating commands to the library
878 * \par Function Description
879 * Adds a set of commands which can generate symbols to the
880 * library. \a list_cmd and \a get_cmd should be strings consisting
881 * of an executable name followed by any arguments required.
882 * Executables are resolved using the current PATH. See page \ref
883 * libcmds for more information on library commands.
885 * \param list_cmd The executable & arguments used to list available
886 * symbols.
887 * \param get_cmd The executable & arguments used to retrieve symbol
888 * data.
889 * \param name A descriptive name for the component source.
890 * \return The CLibSource associated with the component source.
892 const CLibSource *s_clib_add_command (const gchar *list_cmd,
893 const gchar *get_cmd,
894 const gchar *name)
896 CLibSource *source;
897 gchar *realname;
899 if (name == NULL) {
900 s_log_message (_("Cannot add library: name not specified\n"));
901 return NULL;
904 realname = uniquify_source_name (name);
906 if (list_cmd == NULL || get_cmd == NULL) {
907 s_log_message (_("Cannot add library [%s]: both 'list' and "
908 "'get' commands must be specified.\n"),
909 realname);
912 source = g_new0 (CLibSource, 1);
913 source->type = CLIB_CMD;
914 source->name = realname;
916 source->list_cmd = g_strdup (list_cmd);
917 source->get_cmd = g_strdup (get_cmd);
919 refresh_command (source);
921 /* Sources added later get sacnned earlier */
922 clib_sources = g_list_prepend (clib_sources, source);
924 return source;
927 /*! \brief Add symbol-generating Scheme procedures to the library.
928 * \par Function Description
929 * Adds a source to the library based on Scheme procedures. See page
930 * \ref libscms for more information. Two procedures are required: \a
931 * listfunc must return a Scheme list of symbol names, and \a getfunc
932 * must return a string containing symbol data when passed a symbol
933 * name.
935 * \param listfunc A Scheme function returning a list of symbols.
936 * \param getfunc A Scheme function returning symbol data.
937 * \param name A descriptive name for the component source.
939 * \return The new CLibSource.
941 const CLibSource *s_clib_add_scm (SCM listfunc, SCM getfunc, const gchar *name)
943 CLibSource *source;
944 gchar *realname;
946 if (name == NULL) {
947 s_log_message (_("Cannot add library: name not specified\n"));
948 return NULL;
951 realname = uniquify_source_name (name);
953 if (scm_is_false (scm_procedure_p (listfunc))
954 && scm_is_false (scm_procedure_p (getfunc))) {
955 s_log_message (_("Cannot add Scheme-library [%s]: callbacks must be closures\n"),
956 realname);
957 return NULL;
960 source = g_new0 (CLibSource, 1);
961 source->type = CLIB_SCM;
962 source->name = realname;
963 source->list_fn = scm_gc_protect_object (listfunc);
964 source->get_fn = scm_gc_protect_object (getfunc);
966 refresh_scm (source);
968 clib_sources = g_list_prepend (clib_sources, source);
970 return source;
973 /*! \brief Get the name of a source.
974 * \par Function Description
975 * Get the name of a source for use e.g. in displaying a GUI.
977 * \param source Source to be examined.
978 * \return Name of source.
980 const gchar *s_clib_source_get_name (const CLibSource *source)
982 if (source == NULL) return NULL;
983 return source->name;
986 /*! \brief Get a list of symbols available from a given source.
987 * \par Function Description
988 * Get a \b GList containing all of the symbols available from \a
989 * source.
991 * \warning The returned \b GList will not be consistent over a call to
992 * s_clib_refresh(). It should be freed when no longer needed.
994 * \param source Source to be examined.
995 * \return A \b GList of #CLibSymbol.
997 GList *s_clib_source_get_symbols (const CLibSource *source)
999 if (source == NULL) return NULL;
1000 return g_list_copy(source->symbols);
1004 /*! \brief Get the name of a symbol.
1005 * \par Function Description
1006 * Get the name of a symbol. The symbol name uniquely identifies it
1007 * to libgeda.
1009 * \param symbol Symbol to be examined.
1010 * \return Name of symbol.
1012 const gchar *s_clib_symbol_get_name (const CLibSymbol *symbol)
1014 if (symbol == NULL) return NULL;
1015 return symbol->name;
1018 /*! \brief Get a filename for editing a symbol.
1019 * \par Function Description
1020 * Get the filename of the file a symbol was loaded from, if possible
1021 * (e.g. to allow loading for user editing).
1023 * \warning The returned string should be freed when no longer
1024 * needed.
1026 * \todo This is hack until there is a way to edit documents in
1027 * gschem which do not have a file in the filesystem associated with
1028 * them.
1030 * \deprecated This function is a temporary workaround.
1032 * \param symbol Symbol to be examined.
1033 * \return Filename of symbol.
1035 gchar *s_clib_symbol_get_filename (const CLibSymbol *symbol)
1037 if (symbol == NULL) return NULL;
1039 if (symbol->source->type != CLIB_DIR) return NULL;
1041 return g_build_filename(symbol->source->directory, symbol->name, NULL);
1044 /*! \brief Get the source to which a symbol belongs.
1045 * \par Function Description
1046 * Get the source which a symbol is associated.
1048 * \param symbol Symbol to be examined.
1049 * \return Source which owns symbol.
1051 const CLibSource *s_clib_symbol_get_source (const CLibSymbol *symbol)
1053 if (symbol == NULL) return NULL;
1054 return symbol->source;
1057 /*! \brief Get symbol data from a directory source.
1058 * \par Function Description
1059 * Get symbol data from a directory data source. The return value
1060 * should be free()'d when no longer needed.
1062 * Private function used only in s_clib.c.
1064 * \param symbol Symbol to get data for.
1065 * \return Allocated buffer containing symbol data.
1067 static gchar *get_data_directory (const CLibSymbol *symbol)
1069 gchar *filename = NULL;
1070 gchar *data = NULL;
1071 GError *e = NULL;
1073 g_return_val_if_fail ((symbol != NULL), NULL);
1074 g_return_val_if_fail ((symbol->source->type == CLIB_DIR), NULL);
1076 filename = g_build_filename(symbol->source->directory,
1077 symbol->name, NULL);
1079 g_file_get_contents (filename, &data, NULL, &e);
1081 if (e != NULL) {
1082 s_log_message (_("Failed to load symbol from file [%s]: %s\n"),
1083 filename, e->message);
1084 g_error_free (e);
1087 g_free (filename);
1088 return data;
1091 /*! \brief Get symbol data from a library command.
1092 * \par Function Description
1093 * Get symbol data from a library command. The return value should
1094 * be free()'d when no longer needed.
1096 * Private function used only in s_clib.c.
1098 * \param symbol Symbol to get data for.
1099 * \return Allocated buffer containing symbol data.
1101 static gchar *get_data_command (const CLibSymbol *symbol)
1103 gchar *command;
1104 gchar *result;
1106 g_return_val_if_fail ((symbol != NULL), NULL);
1107 g_return_val_if_fail ((symbol->source->type == CLIB_CMD), NULL);
1109 command = g_strdup_printf ("%s %s", symbol->source->get_cmd,
1110 symbol->name);
1112 result = run_source_command ( command );
1114 g_free (command);
1116 return result;
1119 /*! \brief Get symbol data from a Scheme-based component source.
1120 * \par Function Description
1121 * Get symbol data from a Scheme-based component source. The return
1122 * value should be free()'d when no longer needed.
1124 * Private function used only in s_clib.c.
1126 * \param symbol Symbol to get data for.
1127 * \return Allocated buffer containing symbol data.
1129 static gchar *get_data_scm (const CLibSymbol *symbol)
1131 SCM symdata;
1132 char *tmp;
1133 gchar *result;
1135 g_return_val_if_fail ((symbol != NULL), NULL);
1136 g_return_val_if_fail ((symbol->source->type == CLIB_SCM), NULL);
1138 symdata = scm_call_1 (symbol->source->get_fn,
1139 scm_from_locale_string (symbol->name));
1141 if (!scm_is_string (symdata)) {
1142 s_log_message (_("Failed to load symbol data [%s] from source [%s]\n"),
1143 symbol->name, symbol->source->name);
1144 return NULL;
1147 /* Need to make sure that the correct free() function is called
1148 * on strings allocated by Guile. */
1149 tmp = scm_to_locale_string (symdata);
1150 result = g_strdup(tmp);
1151 free (tmp);
1153 return result;
1156 /*! \brief Get symbol data.
1157 * \par Function Description
1158 * Get the unparsed gEDA-format data corresponding to a symbol from
1159 * the symbol's data source. The return value should be free()'d
1160 * when no longer needed.
1162 * On failure, returns \b NULL (the error will be logged).
1164 * \param symbol Symbol to get data for.
1165 * \return Allocated buffer containing symbol data.
1167 gchar *s_clib_symbol_get_data (const CLibSymbol *symbol)
1169 CacheEntry *cached;
1170 gchar *data;
1171 gpointer symptr;
1172 gint n;
1174 g_return_val_if_fail ((symbol != NULL), NULL);
1175 g_return_val_if_fail ((symbol->source != NULL), NULL);
1177 /* Trickery to bypass effects of const */
1178 symptr = (gpointer) symbol;
1180 /* First, try the cache. */
1181 cached = g_hash_table_lookup (clib_symbol_cache, symptr);
1182 if (cached != NULL) {
1183 cached->accessed = time(NULL);
1184 return g_strdup(cached->data);
1187 /* If the symbol wasn't found in the cache, get it directly. */
1188 switch (symbol->source->type)
1190 case CLIB_DIR:
1191 data = get_data_directory (symbol);
1192 break;
1193 case CLIB_CMD:
1194 data = get_data_command (symbol);
1195 break;
1196 case CLIB_SCM:
1197 data = get_data_scm (symbol);
1198 break;
1199 default:
1200 g_critical("s_clib_symbol_get_data: source %p has bad source type %i\n",
1201 symbol->source, (gint) symbol->source->type);
1202 return NULL;
1205 if (data == NULL) return NULL;
1207 /* Cache the symbol data */
1208 cached = g_new (CacheEntry, 1);
1209 cached->ptr = (CLibSymbol *) symptr;
1210 cached->data = g_strdup (data);
1211 cached->accessed = time (NULL);
1212 g_hash_table_insert (clib_symbol_cache, symptr, cached);
1214 /* Clean out the cache if it's too full */
1215 n = g_hash_table_size (clib_symbol_cache);
1216 if (n > CLIB_MAX_SYMBOL_CACHE) {
1217 for ( ; n > CLIB_MIN_SYMBOL_CACHE; n--) {
1218 g_hash_table_foreach (clib_symbol_cache,
1219 (GHFunc) cache_find_oldest,
1220 &cached);
1221 g_hash_table_remove (clib_symbol_cache, cached->ptr);
1225 return data;
1229 /*! \brief Find all symbols matching a pattern.
1231 * \par Function Description
1232 * Searches the library, returning all symbols whose
1233 * names match \a pattern.
1235 * Two search modes are available: \b CLIB_EXACT, where \a pattern is
1236 * compared to the symbol name using strcmp(), and \b CLIB_GLOB,
1237 * where \a pattern is assumed to be a glob pattern (see the GLib
1238 * documentation for details of the glob syntax applicable).
1240 * \warning The #CLibSymbol instances in the \b GList returned belong
1241 * to the component library, and should be considered constants; they
1242 * should not be manipulated or free()'d. On the other hand, the \b
1243 * GList returned must be freed with \b g_list_free() when no longer
1244 * needed. Note that the values returned will be invalidated by a
1245 * call to s_clib_free() or s_clib_refresh().
1247 * \param pattern The pattern to match against.
1248 * \param mode The search mode to use.
1249 * \return A \b GList of matching #CLibSymbol structures.
1251 GList *s_clib_search (const gchar *pattern, const CLibSearchMode mode)
1253 GList *sourcelist;
1254 GList *symlist;
1255 GList *result = NULL;
1256 CLibSource *source;
1257 CLibSymbol *symbol;
1258 GPatternSpec *globpattern = NULL;
1259 gchar *key;
1260 gchar keytype;
1262 if (pattern == NULL) return NULL;
1264 /* Use different cache keys depending on what sort of search is being done */
1265 switch (mode)
1267 case CLIB_GLOB:
1268 keytype = 'g';
1269 break;
1270 case CLIB_EXACT:
1271 keytype = 's';
1272 break;
1273 default:
1274 g_critical ("s_clib_search: Bad search mode %i\n", mode);
1275 return NULL;
1277 key = g_strdup_printf("%c%s", keytype, pattern);
1279 /* Check to see if the query is already in the cache */
1280 result = (GList *) g_hash_table_lookup (clib_search_cache, key);
1281 if (result != NULL) {
1282 g_free (key);
1283 return g_list_copy (result);
1286 if (mode == CLIB_GLOB) {
1287 globpattern = g_pattern_spec_new(pattern);
1290 for (sourcelist = clib_sources;
1291 sourcelist != NULL;
1292 sourcelist = g_list_next(sourcelist)) {
1294 source = (CLibSource *) sourcelist->data;
1296 for (symlist = source->symbols;
1297 symlist != NULL;
1298 symlist = g_list_next(symlist)) {
1300 symbol = (CLibSymbol *) symlist->data;
1302 switch (mode)
1304 case CLIB_EXACT:
1305 if (strcmp (pattern, symbol->name) == 0) {
1306 result = g_list_prepend (result, symbol);
1308 break;
1309 case CLIB_GLOB:
1310 if (g_pattern_match_string (globpattern, symbol->name)) {
1311 result = g_list_prepend (result, symbol);
1313 break;
1318 result = g_list_reverse (result);
1320 if (globpattern != NULL) {
1321 g_pattern_spec_free (globpattern);
1324 g_hash_table_insert (clib_search_cache, key, g_list_copy (result));
1325 /* __don't__ free key here, it's stored by the hash table! */
1327 return result;
1333 /*! \brief Flush the symbol name lookup cache.
1334 * \par Function Description
1335 * Clears the hashtable which caches the results of s_clib_search().
1336 * You shouldn't ever need to call this, as all functions which
1337 * invalidate the cache are supposed to make sure it's flushed.
1339 void s_clib_flush_search_cache ()
1341 g_hash_table_remove_all (clib_search_cache); /* Introduced in glib 2.12 */
1345 /*! \brief Flush the symbol data cache.
1346 * \par Function Description
1347 * Clears the hashtable which caches the results of s_clib_symbol_get_data().
1348 * You shouldn't ever need to call this, as all functions which
1349 * invalidate the cache are supposed to make sure it's flushed.
1351 void s_clib_flush_symbol_cache ()
1353 g_hash_table_remove_all (clib_symbol_cache); /* Introduced in glib 2.12 */
1356 /*! \brief Get symbol structure for a given symbol name.
1357 * \par Function Description
1358 * Return the first symbol found with the given \a name. If more
1359 * than one matching symbol is found or no matches are found at all,
1360 * emits a log message warning the user.
1362 * \param name The symbol name to match against.
1363 * \return The first matching symbol, or NULL if none found.
1365 const CLibSymbol *s_clib_get_symbol_by_name (const gchar *name)
1367 GList *symlist = NULL;
1368 const CLibSymbol *retval;
1370 symlist = s_clib_search (name, CLIB_EXACT);
1372 if (symlist == NULL) {
1373 s_log_message (_("Component [%s] was not found in the component library\n"),
1374 name);
1375 return NULL;
1378 if (g_list_next (symlist) != NULL) { /* More than one symbol */
1379 s_log_message (_("More than one component found with name [%s]\n"),
1380 name);
1383 retval = (CLibSymbol *) symlist->data;
1384 g_list_free (symlist);
1386 return retval;
1389 /*! \brief Get symbol data for a given symbol name.
1390 * \par Function Description
1391 * Return the data for the first symbol found with the given name.
1392 * This is a helper function for the schematic load system, as it
1393 * will always want to load symbols given only their name.
1395 * On failure, returns \b NULL (the error will be logged).
1397 * \param name The symbol name to match against.
1398 * \return Allocated buffer containing symbol data.
1400 gchar *s_clib_symbol_get_data_by_name (const gchar *name)
1402 const CLibSymbol *symbol;
1404 symbol = s_clib_get_symbol_by_name (name);
1405 if (symbol == NULL) return NULL;
1406 return s_clib_symbol_get_data (symbol);
1409 /*! \brief Get a list of symbols used.
1410 * \par Function Description
1412 * Scan a #TOPLEVEL structure's object list looking for symbols, and
1413 * return them in a list.
1415 * \warning The #CLibSymbol instances in the \b GList returned belong
1416 * to the component library, and should be considered constants; they
1417 * should not be manipulated or free()'d. On the other hand, the \b
1418 * GList returned must be freed with \b g_list_free() when no longer
1419 * needed. Note that the values returned will be invalidated by a
1420 * call to s_clib_free() or s_clib_refresh().
1422 * \bug Only includes components which are not embedded, but they
1423 * should (probably) also appear in the list.
1425 * \param toplevel #TOPLEVEL structure to scan.
1426 * \return GList of symbols.
1428 GList *s_toplevel_get_symbols (const TOPLEVEL *toplevel)
1430 GList *result = NULL;
1431 GList *iter = NULL;
1432 OBJECT *o = NULL;
1433 PAGE *page;
1434 GList *symlist = NULL;
1435 CLibSymbol *sym = NULL;
1436 const GList *p_iter;
1437 const GList *o_iter;
1439 g_return_val_if_fail ((toplevel != NULL), NULL);
1441 for ( p_iter = geda_list_get_glist( toplevel->pages );
1442 p_iter != NULL;
1443 p_iter = g_list_next( p_iter )) {
1444 page = (PAGE *)p_iter->data;
1445 for (o_iter = s_page_objects (page);
1446 o_iter != NULL;
1447 o_iter = g_list_next (o_iter)) {
1448 o = (OBJECT *)o_iter->data;
1449 if (o->type != OBJ_COMPLEX) continue;
1450 if (o->complex_basename == NULL) continue;
1452 /* Since we're not looking at embedded symbols, the first
1453 * component with the given name will be the one we need.
1454 * N.b. we don't use s_clib_get_symbol_by_name() because it's
1455 * spammeh. */
1456 symlist = s_clib_search (o->complex_basename, CLIB_EXACT);
1457 if (symlist == NULL) continue;
1458 sym = (CLibSymbol *) symlist->data;
1459 g_list_free (symlist);
1461 /* We do the list insertion by evilly comparing pointers. This
1462 * is okay, because we always take the first symbol with the
1463 * given name, and symbol pointers don't change while this
1464 * function is running (we hope). Note that this creates a
1465 * sorted list.*/
1466 for (iter = result;
1467 iter != NULL;
1468 iter = g_list_next(iter)) {
1469 if (iter->data == sym) {
1470 break; /* Already in list */
1472 if (compare_symbol_name (iter->data, sym) > 0) {
1473 /* not in list yet, and gone past point where it should go */
1474 result = g_list_insert_before (result, iter, sym);
1475 break;
1478 if (iter == NULL) {
1479 /* not in list yet, and at end of list */
1480 result = g_list_append (result, sym);
1485 return result;