source: tags/ms_r17q3/AWTI/AWTI_import.cxx

Last change on this file was 16564, checked in by westram, 7 years ago
  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 52.8 KB
Line 
1// ============================================================= //
2//                                                               //
3//   File      : AWTI_import.cxx                                 //
4//   Purpose   :                                                 //
5//                                                               //
6//   Institute of Microbiology (Technical University Munich)     //
7//   http://www.arb-home.de/                                     //
8//                                                               //
9// ============================================================= //
10
11#include "awti_imp_local.hxx"
12
13#include <FileWatch.h>
14#include <seqio.hxx>
15#include <item_sel_list.h>
16#include <awt.hxx>
17
18#include <aw_advice.hxx>
19#include <aw_file.hxx>
20#include <AW_rename.hxx>
21#include <aw_msg.hxx>
22#include <aw_question.hxx>
23
24#include <GenomeImport.h>
25#include <GEN.hxx>
26#include <adGene.h>
27#include <arb_progress.h>
28#include <arb_strbuf.h>
29#include <arb_str.h>
30#include <macros.hxx>
31
32#include <climits>
33#include <unistd.h>
34#include <gb_aci.h>
35#include "awti_edit.hxx"
36
37using namespace std;
38using namespace SEQIO;
39
40#define MAX_COMMENT_LINES 2000
41
42
43inline const char *name_only(const char *fullpath) {
44    const char *lslash = strrchr(fullpath, '/');
45    return lslash ? lslash+1 : fullpath;
46}
47
48
49inline GB_ERROR not_in_match_error(const char *cmd) {
50    return GBS_global_string("Command '%s' may only appear after 'MATCH'", cmd);
51}
52
53inline bool wants_import_genome(AW_root *awr) { return awr->awar(AWAR_IMPORT_GENOM_DB)->read_int() == IMP_GENOME_FLATFILE; }
54
55static char *encode_escaped_chars(char *com) {
56    // Encodes the escape sequences "\\n", "\\t" and "\\0" to their corresponding characters
57    // Other occurrences of "\\" are removed.
58
59    char *result, *s, *d;
60    int   ch;
61
62    s = d = result = ARB_strdup(com);
63    while ((ch = *(s++))) {
64        switch (ch) {
65            case '\\':
66                ch = *(s++); if (!ch) { s--; break; };
67                switch (ch) {
68                    case 'n':   *(d++) = '\n'; break;
69                    case 't':   *(d++) = '\t'; break;
70                    case '0':   *(d++) = '\0'; break;
71                    default:    *(d++) = ch; break;
72                }
73                break;
74            default:
75                *(d++) = ch;
76        }
77    }
78    *d = 0;
79    return result;
80}
81
82static GB_ERROR read_import_format(const char *fullfile, import_format *ifo, bool *var_set, bool included) {
83    GB_ERROR  error = 0;
84    FILE     *in    = fopen(fullfile, "rt");
85
86    import_match *m = ifo->match;
87
88    if (!in) {
89        const char *name = name_only(fullfile);
90
91        if (included) {
92            error = GB_export_IO_error("including", name);
93        }
94        else {
95            error = strchr(name, '*')
96                ? "Please use 'AUTO DETECT' or manually select an import format"
97                : GB_IO_error("loading import filter", name);
98        }
99    }
100    else {
101        char   *s1, *s2;
102        size_t  lineNumber    = 0;
103        bool    include_error = false;
104
105        while (!error && read_string_pair(in, s1, s2, lineNumber)) {
106
107#define GLOBAL_COMMAND(cmd) (!error && strcmp(s1, cmd) == 0)
108#define MATCH_COMMAND(cmd)  (!error && strcmp(s1, cmd) == 0 && (m || !(error = not_in_match_error(cmd))))
109
110            if (GLOBAL_COMMAND("MATCH")) {
111                m = new import_match;
112
113                m->defined_at = GBS_global_string_copy("%zi,%s", lineNumber, name_only(fullfile));
114                m->next       = ifo->match; // this concatenates the filters to the front -> the list is reversed below
115                ifo->match    = m;
116                m->match      = encode_escaped_chars(s2);
117                m->type       = GB_STRING;
118
119                if (ifo->autotag) m->mtag = ARB_strdup(ifo->autotag); // will be overwritten by TAG command
120            }
121            else if (MATCH_COMMAND("SRT"))         { reassign(m->srt, s2); }
122            else if (MATCH_COMMAND("ACI"))         { reassign(m->aci, s2); }
123            else if (MATCH_COMMAND("WRITE"))       { reassign(m->write, s2); }
124            else if (MATCH_COMMAND("WRITE_INT"))   { reassign(m->write, s2); m->type = GB_INT; }
125            else if (MATCH_COMMAND("WRITE_FLOAT")) { reassign(m->write, s2); m->type = GB_FLOAT; }
126            else if (MATCH_COMMAND("APPEND"))      { reassign(m->append, s2); }
127            else if (MATCH_COMMAND("SETVAR")) {
128                if (strlen(s2) != 1 || s2[0]<'a' || s2[0]>'z') {
129                    error = "Allowed variable names are a-z";
130                }
131                else {
132                    var_set[s2[0]-'a'] = true;
133                    reassign(m->setvar, s2);
134                }
135            }
136            else if (MATCH_COMMAND("TAG")) {
137                if (s2[0]) reassign(m->mtag, s2);
138                else error = "Empty TAG is not allowed";
139            }
140            else if (GLOBAL_COMMAND("AUTODETECT"))               { reassign(ifo->autodetect,    s2); }
141            else if (GLOBAL_COMMAND("SYSTEM"))                   { reassign(ifo->system,        s2); }
142            else if (GLOBAL_COMMAND("NEW_FORMAT"))               { reassign(ifo->new_format,    s2); ifo->new_format_lineno = lineNumber; }
143            else if (GLOBAL_COMMAND("BEGIN"))                    { reassign(ifo->begin,         s2); }
144            else if (GLOBAL_COMMAND("FILETAG"))                  { reassign(ifo->filetag,       s2); }
145            else if (GLOBAL_COMMAND("SEQUENCESRT"))              { reassign(ifo->sequencesrt,   s2); }
146            else if (GLOBAL_COMMAND("SEQUENCEACI"))              { reassign(ifo->sequenceaci,   s2); }
147            else if (GLOBAL_COMMAND("SEQUENCEEND"))              { reassign(ifo->sequenceend,   s2); }
148            else if (GLOBAL_COMMAND("END"))                      { reassign(ifo->end,           s2); }
149            else if (GLOBAL_COMMAND("AUTOTAG"))                  { reassign(ifo->autotag,       s2); }
150            else if (GLOBAL_COMMAND("SEQUENCESTART"))            { reassign(ifo->sequencestart, s2); ifo->read_this_sequence_line_too = 1; }
151            else if (GLOBAL_COMMAND("SEQUENCEAFTER"))            { reassign(ifo->sequencestart, s2); ifo->read_this_sequence_line_too = 0; }
152            else if (GLOBAL_COMMAND("KEYWIDTH"))                 { ifo->tab            = atoi(s2); }
153            else if (GLOBAL_COMMAND("SEQUENCECOLUMN"))           { ifo->sequencecolumn = atoi(s2); }
154            else if (GLOBAL_COMMAND("CREATE_ACC_FROM_SEQUENCE")) { ifo->autocreateacc  = 1; }
155            else if (GLOBAL_COMMAND("DONT_GEN_NAMES"))           { ifo->noautonames    = 1; }
156            else if (GLOBAL_COMMAND("DESCRIPTION"))              { appendTo(ifo->description, '\n', s2); }
157            else if (GLOBAL_COMMAND("INCLUDE")) {
158                char *dir         = AW_extract_directory(fullfile);
159                char *includeFile = GBS_global_string_copy("%s/%s", dir, s2);
160
161                error = read_import_format(includeFile, ifo, var_set, true);
162                if (error) include_error = true;
163
164                free(includeFile);
165                free(dir);
166            }
167            else {
168                bool ifnotset  = GLOBAL_COMMAND("IFNOTSET");
169                bool setglobal = GLOBAL_COMMAND("SETGLOBAL");
170
171                if (ifnotset || setglobal) {
172                    if (s2[0]<'a' || s2[0]>'z') {
173                        error = "Allowed variable names are a-z";
174                    }
175                    else {
176                        int off = 1;
177                        while (isblank(s2[off])) off++;
178                        if (!s2[off]) error = GBS_global_string("Expected two arguments in '%s'", s2);
179                        else {
180                            char        varname = s2[0];
181                            const char *arg2    = s2+off;
182
183                            if (ifnotset) {
184                                if (ifo->variable_errors.get(varname)) {
185                                    error = GBS_global_string("Redefinition of IFNOTSET %c", varname);
186                                }
187                                else {
188                                    ifo->variable_errors.set(varname, arg2);
189                                }
190                            }
191                            else {
192                                awti_assert(setglobal);
193                                ifo->global_variables.set(varname, arg2);
194                                var_set[varname-'a'] = true;
195                            }
196                        }
197                    }
198                }
199                else if (!error) {
200                    error = GBS_global_string("Unknown command '%s'", s1);
201                }
202            }
203
204            free(s1);
205            free(s2);
206        }
207
208        if (error) {
209            error = GBS_global_string("%sin line %zi of %s '%s':\n%s",
210                                      include_error ? "included " : "",
211                                      lineNumber,
212                                      included ? "file" : "import format",
213                                      name_only(fullfile),
214                                      error);
215        }
216
217        fclose(in);
218
219#undef MATCH_COMMAND
220#undef GLOBAL_COMMAND
221    }
222
223    return error;
224}
225
226GB_ERROR ArbImporter::read_format(const char *file) {
227    char *fullfile = ARB_strdup(GB_path_in_ARBHOME(file));
228
229    delete ifo;
230    ifo = new import_format;
231
232    bool var_set[IFS_VARIABLES];
233    for (int i = 0; i<IFS_VARIABLES; i++) var_set[i] = false;
234
235    GB_ERROR error = read_import_format(fullfile, ifo, var_set, false);
236
237
238    for (int i = 0; i<IFS_VARIABLES && !error; i++) {
239        bool ifnotset = ifo->variable_errors.get(i+'a');
240        if (var_set[i]) {
241            bool isglobal = ifo->global_variables.get(i+'a');
242            if (!ifnotset && !isglobal) { // don't warn if variable is global
243                error = GBS_global_string("Warning: missing IFNOTSET for variable '%c'", 'a'+i);
244            }
245        }
246        else {
247            if (ifnotset) {
248                error = GBS_global_string("Warning: useless IFNOTSET for unused variable '%c'", 'a'+i);
249            }
250        }
251    }
252
253    // reverse order of match list (was appended backwards during creation)
254    if (ifo->match) ifo->match = ifo->match->reverse(0);
255
256    free(fullfile);
257
258    return error;
259}
260
261import_match::import_match() :
262    match(NULL),
263    aci(NULL),
264    srt(NULL),
265    mtag(NULL),
266    append(NULL),
267    write(NULL),
268    setvar(NULL),
269    type(GB_NONE),
270    defined_at(NULL),
271    next(NULL)
272{
273}
274
275import_match::~import_match() {
276    free(match);
277    free(aci);
278    free(srt);
279    free(mtag);
280    free(append);
281    free(write);
282    free(setvar);
283    free(defined_at);
284
285    delete next;
286}
287
288import_format::import_format() :
289    autodetect(NULL),
290    system(NULL),
291    new_format(NULL),
292    new_format_lineno(0),
293    tab(0),
294    description(NULL),
295    begin(NULL),
296    sequencestart(NULL),
297    read_this_sequence_line_too(0),
298    sequenceend(NULL),
299    sequencesrt(NULL),
300    sequenceaci(NULL),
301    filetag(NULL),
302    autotag(NULL),
303    sequencecolumn(0),
304    autocreateacc(0),
305    noautonames(0),
306    end(NULL),
307    b1(NULL),
308    b2(NULL),
309    match(NULL)
310{
311}
312
313import_format::~import_format() {
314    free(autodetect);
315    free(system);
316    free(new_format);
317    free(description);
318    free(begin);
319    free(sequencestart);
320    free(sequenceend);
321    free(sequencesrt);
322    free(sequenceaci);
323    free(filetag);
324    free(autotag);
325    free(end);
326    free(b1);
327    free(b2);
328
329    delete match;
330}
331
332
333static int cmp_ift(const void *p0, const void *p1, void *) {
334    return ARB_stricmp((const char *)p0, (const char *)p1);
335}
336
337void ArbImporter::detect_format(AW_root *root) {
338    StrArray files;
339    {
340        AW_awar       *awar_dirs = root->awar(AWAR_IMPORT_FORMATDIR);
341        ConstStrArray  dirs;
342        GBT_split_string(dirs, awar_dirs->read_char_pntr(), ":", true);
343        for (unsigned i = 0; i<dirs.size(); ++i) GBS_read_dir(files, dirs[i], "*.ift");
344    }
345    files.sort(cmp_ift, NULL);
346
347    char     buffer[AWTI_IMPORT_CHECK_BUFFER_SIZE+10];
348    GB_ERROR error = 0;
349
350    int matched       = -1;
351    int first         = -1;
352    int matched_count = 0;
353
354    AW_awar *awar_filter   = root->awar(AWAR_IMPORT_FORMATNAME);
355    char    *prev_selected = awar_filter->read_string();
356
357    // read start of (1st) file to import into 'buffer'
358    {
359        FILE *test = 0;
360        {
361            char *f = root->awar(AWAR_IMPORT_FILENAME)->read_string();
362
363            if (f[0]) {
364                const char *com = GBS_global_string("cat %s 2>/dev/null", f);
365                test            = popen(com, "r");
366            }
367            free(f);
368            if (!test) error = "No input file specified -> cannot detect anything";
369        }
370        if (test) {
371            int size = fread(buffer, 1, AWTI_IMPORT_CHECK_BUFFER_SIZE, test);
372            pclose(test);
373            if (size>=0) buffer[size] = 0;
374        }
375        else {
376            buffer[0] = 0;
377        }
378    }
379
380    for (int idx = 0; files[idx] && !error; ++idx) {
381        const char *filtername = files[idx];
382        awar_filter->write_string(filtername);
383
384        GB_ERROR form_err = read_format(filtername);
385        if (form_err) {
386            aw_message(form_err);
387        }
388        else {
389            if (ifo->autodetect) {      // detectable
390                char *autodetect = encode_escaped_chars(ifo->autodetect);
391                if (GBS_string_matches(buffer, autodetect, GB_MIND_CASE)) {
392                    // format found!
393                    matched_count++;
394                    if (matched == -1) matched = idx; // remember first/next found format
395                    if (first == -1) first     = idx; // remember first found format
396
397                    if (strcmp(filtername, prev_selected) == 0) { // previously selected filter
398                        matched = -1; // select next (or first.. see below)
399                    }
400                }
401                free(autodetect);
402            }
403        }
404
405        delete ifo; ifo = 0;
406    }
407
408    const char *select = 0;
409    if (!error) {
410        switch (matched_count) {
411            case 0:
412                AW_advice("Not all formats can be auto-detected.\n"
413                          "Some need to be selected manually.",
414                          AW_ADVICE_TOGGLE,
415                          "No format auto-detected",
416                          "arb_import.hlp");
417
418                select = "unknown.ift";
419                break;
420
421            default:
422                AW_advice("Several import filters matched during auto-detection.\n"
423                          "Click 'AUTO DETECT' again to select next matching import-filter.",
424                          AW_ADVICE_TOGGLE,
425                          "Several formats detected",
426                          "arb_import.hlp");
427
428                // fall-through
429            case 1:
430                if (matched == -1) {
431                    // wrap around to top (while searching next matching filter)
432                    // or re-select the one matching filter (if it was previously selected)
433                    awti_assert(first != -1);
434                    matched = first;
435                }
436                awti_assert(matched != -1);
437                select = files[matched];  // select 1st matching filter
438                break;
439        }
440    }
441    else {
442        select = prev_selected;
443        aw_message(error);
444    }
445
446    awar_filter->write_string(select);
447    free(prev_selected);
448}
449
450int ArbImporter::next_file() {
451    if (in) fclose(in);
452    if (current_file_idx<0) current_file_idx = 0;
453
454    int result = 1;
455    while (result == 1 && filenames[current_file_idx]) {
456        const char *origin_file_name = filenames[current_file_idx++];
457
458        const char *sorigin   = strrchr(origin_file_name, '/');
459        if (!sorigin) sorigin = origin_file_name;
460        else sorigin++;
461
462        GB_ERROR  error          = 0;
463        char     *mid_file_name  = 0;
464        char     *dest_file_name = 0;
465
466        if (ifo2 && ifo2->system) {
467            {
468                const char *sorigin_nameonly            = strrchr(sorigin, '/');
469                if (!sorigin_nameonly) sorigin_nameonly = sorigin;
470
471                char *mid_name = GB_unique_filename(sorigin_nameonly, "tmp");
472                mid_file_name  = GB_create_tempfile(mid_name);
473                free(mid_name);
474
475                if (!mid_file_name) error = GB_await_error();
476            }
477
478            if (!error) {
479                char *srt = GBS_global_string_copy("$<=%s:$>=%s", origin_file_name, mid_file_name);
480                char *sys = GBS_string_eval(ifo2->system, srt);
481
482                arb_progress::show_comment(GBS_global_string("exec '%s'", ifo2->system));
483
484                error                        = GBK_system(sys);
485                if (!error) origin_file_name = mid_file_name;
486
487                free(sys);
488                free(srt);
489            }
490        }
491
492        if (!error && ifo->system) {
493            {
494                const char *sorigin_nameonly            = strrchr(sorigin, '/');
495                if (!sorigin_nameonly) sorigin_nameonly = sorigin;
496
497                char *dest_name = GB_unique_filename(sorigin_nameonly, "tmp");
498                dest_file_name  = GB_create_tempfile(dest_name);
499                free(dest_name);
500
501                if (!dest_file_name) error = GB_await_error();
502            }
503
504            awti_assert(dest_file_name || error);
505
506            if (!error) {
507                char *srt = GBS_global_string_copy("$<=%s:$>=%s", origin_file_name, dest_file_name);
508                char *sys = GBS_string_eval(ifo->system, srt);
509
510                arb_progress::show_comment(GBS_global_string("Converting File %s", ifo->system));
511
512                error                        = GBK_system(sys);
513                if (!error) origin_file_name = dest_file_name;
514
515                free(sys);
516                free(srt);
517            }
518        }
519
520        if (!error) {
521            in = fopen(origin_file_name, "r");
522
523            if (in) {
524                result = 0;
525            }
526            else {
527                error = GBS_global_string("Error: Cannot open file %s\n", origin_file_name);
528            }
529        }
530
531        if (mid_file_name) {
532            awti_assert(GB_is_privatefile(mid_file_name, false));
533            GB_unlink_or_warn(mid_file_name, &error);
534            free(mid_file_name);
535        }
536        if (dest_file_name) {
537            GB_unlink_or_warn(dest_file_name, &error);
538            free(dest_file_name);
539        }
540
541        if (error) aw_message(error);
542    }
543
544    return result;
545}
546
547char *ArbImporter::read_line(int tab, char *sequencestart, char *sequenceend) {
548    /* two modes:   tab == 0 -> read single lines,
549       different files are separated by sequenceend,
550       tab != 0 join lines that start after position tab,
551       joined lines are separated by '|'
552       except lines that match sequencestart
553       (they may be part of sequence if read_this_sequence_line_too = 1 */
554
555    static char *in_queue  = 0;     // read data
556    static int   b2offset  = 0;
557    const int    BUFSIZE   = 8000;
558    const char  *SEPARATOR = "|";   // line separator
559
560    if (!ifo->b1) ARB_calloc(ifo->b1, BUFSIZE);
561    if (!ifo->b2) ARB_calloc(ifo->b2, BUFSIZE);
562
563    if (!in) {
564        if (next_file()) {
565            if (in_queue) {
566                char *s = in_queue;
567                in_queue = 0;
568                return s;
569            }
570            return 0;
571        }
572    }
573
574
575    if (!tab) {
576        if (in_queue) {
577            char *s = in_queue;
578            in_queue = 0;
579            return s;
580        }
581        char *p = fgets_smartLF(ifo->b1, BUFSIZE-3, in);
582        if (!p) {
583            sprintf(ifo->b1, "%s", sequenceend);
584            if (in) { fclose(in); in = 0; }
585            p = ifo->b1;
586        }
587        int len = strlen(p)-1;
588        while (len>=0) {
589            if (p[len] == '\n' || p[len] == 13) p[len--] = 0;
590            else break;
591        }
592        return ifo->b1;
593    }
594
595    b2offset = 0;
596    ifo->b2[0] = 0;
597
598    if (in_queue) {
599        b2offset = 0;
600        strncpy(ifo->b2+b2offset, in_queue, BUFSIZE - 4- b2offset);
601        b2offset += strlen(ifo->b2+b2offset);
602        in_queue = 0;
603        if (GBS_string_matches(ifo->b2, sequencestart, GB_MIND_CASE)) return ifo->b2;
604    }
605    while (1) {
606        char *p = fgets_smartLF(ifo->b1, BUFSIZE-3, in);
607        if (!p) {
608            if (in) { fclose(in); in = 0; }
609            break;
610        }
611        int len = strlen(p)-1;
612        while (len>=0) {
613            if (p[len] == '\n' || p[len] == 13) p[len--] = 0;
614            else break;
615        }
616
617
618        if (GBS_string_matches(ifo->b1, sequencestart, GB_MIND_CASE)) {
619            in_queue = ifo->b1;
620            return ifo->b2;
621        }
622
623        int i;
624        for (i=0; i<=tab; i++) if (ifo->b1[i] != ' ') break;
625
626        if (i < tab) {
627            in_queue = ifo->b1;
628            return ifo->b2;
629        }
630        strncpy(ifo->b2+b2offset, SEPARATOR, BUFSIZE - 4- b2offset);
631        b2offset += strlen(ifo->b2+b2offset);
632
633        p = ifo->b1;
634        if (b2offset>0) while (*p==' ') p++;    // delete spaces in second line
635
636        strncpy(ifo->b2+b2offset, p, BUFSIZE - 4- b2offset);
637        b2offset += strlen(ifo->b2+b2offset);
638    }
639    in_queue = 0;
640    return ifo->b2;
641}
642
643static void write_entry(GBDATA *gb_main, GBDATA *gbd, const char *key, const char *str, const char *tag, int append, GB_TYPES type) {
644    if (!gbd) return;
645
646    {
647        while (str[0] == ' ' || str[0] == '\t' || str[0] == '|') str++;
648        int i = strlen(str)-1;
649        while (i >= 0 && (str[i] == ' ' || str[i] == '\t' || str[i] == '|' || str[i] == 13)) {
650            i--;
651        }
652
653        if (i<0) return;
654
655        i++;
656        if (str[i]) { // need to cut trailing whitespace?
657            char *copy = ARB_strndup(str, i);
658            write_entry(gb_main, gbd, key, copy, tag, append, type);
659            free(copy);
660            return;
661        }
662    }
663
664    GBDATA *gbk = GB_entry(gbd, key);
665
666    if (type != GB_STRING) {
667        if (!gbk) gbk=GB_create(gbd, key, type);
668        switch (type) {
669            case GB_INT:
670                GB_write_int(gbk, atoi(str));
671                break;
672            case GB_FLOAT:
673                GB_write_float(gbk, GB_atof(str));
674                break;
675            default:
676                awti_assert(0);
677                break;
678        }
679        return;
680    }
681
682    if (!gbk || !append) {
683        if (!gbk) gbk=GB_create(gbd, key, GB_STRING);
684
685        if (tag) {
686            GBS_strstruct *s = GBS_stropen(10000);
687            GBS_chrcat(s, '[');
688            GBS_strcat(s, tag);
689            GBS_strcat(s, "] ");
690            GBS_strcat(s, str);
691            char *val = GBS_strclose(s);
692            GB_write_string(gbk, val);
693            free(val);
694        }
695        else {
696            if (strcmp(key, "name") == 0) {
697                char *nstr = GBT_create_unique_species_name(gb_main, str);
698                GB_write_string(gbk, nstr);
699                free(nstr);
700            }
701            else {
702                GB_write_string(gbk, str);
703            }
704        }
705        return;
706    }
707
708    const char *strin = GB_read_char_pntr(gbk);
709
710    int   len    = strlen(str) + strlen(strin);
711    int   taglen = tag ? (strlen(tag)+2) : 0;
712    char *buf    = ARB_calloc<char>(len+2+taglen+1);
713
714    if (tag) {
715        char *regexp = ARB_alloc<char>(taglen+3);
716        sprintf(regexp, "*[%s]*", tag);
717
718        if (!GBS_string_matches(strin, regexp, GB_IGNORE_CASE)) { // if tag does not exist yet
719            sprintf(buf, "%s [%s] %s", strin, tag, str); // prefix with tag
720        }
721        free(regexp);
722    }
723
724    if (buf[0] == 0) {
725        sprintf(buf, "%s %s", strin, str);
726    }
727
728    GB_write_string(gbk, buf);
729    free(buf);
730    return;
731}
732
733static string expandSetVariables(const SetVariables& variables, const string& source, bool& error_occurred, const import_format *ifo) {
734    string                 dest;
735    string::const_iterator norm_start = source.begin();
736    string::const_iterator p          = norm_start;
737    error_occurred                    = false;
738
739    while (p != source.end()) {
740        if (*p == '$') {
741            ++p;
742            if (*p == '$') { // '$$' -> '$'
743                dest.append(1, *p);
744            }
745            else { // real variable
746                const string *value = variables.get(*p);
747                if (!value) {
748                    const string *user_error = ifo->variable_errors.get(*p);
749
750                    char *error = 0;
751                    if (user_error) {
752                        error = GBS_global_string_copy("%s (variable '$%c' not set yet)", user_error->c_str(), *p);
753                    }
754                    else {
755                        error = GBS_global_string_copy("Variable '$%c' not set (missing SETVAR or SETGLOBAL?)", *p);
756                    }
757
758                    dest.append(GBS_global_string("<%s>", error));
759                    GB_export_error(error);
760                    free(error);
761                    error_occurred = true;
762                }
763                else {
764                    dest.append(*value);
765                }
766            }
767            ++p;
768        }
769        else {
770            dest.append(1, *p);
771            ++p;
772        }
773    }
774    return dest;
775}
776
777GB_ERROR ArbImporter::read_data(char *ali_name, int security_write) {
778    char *p;
779    while (1) { // search start of entry
780        p = read_line(0, ifo->sequencestart, ifo->sequenceend);
781        if (!p || !ifo->begin || GBS_string_matches(p, ifo->begin, GB_MIND_CASE)) break;
782    }
783    if (!p) return "Cannot find start of file: Wrong format or empty file";
784
785    static int counter       = 0; // note: dont reset counter (used for field 'name', improves uniqueness if no nameserver is used)
786    const  int start_counter = counter;
787
788    GBDATA  *gb_species_data = GBT_get_species_data(gb_import_main);
789    GBL_env  env(gb_import_main, NULL);
790
791    while (p) {
792        SetVariables variables(ifo->global_variables);
793
794        counter++;
795        const int  rel_counter = counter-start_counter;
796        GBDATA    *gb_species  = GB_create_container(gb_species_data, "species");
797
798        {
799            char text[100];
800            if (rel_counter % 10 == 0) {
801                sprintf(text, "Reading species %i", rel_counter);
802                arb_progress::show_comment(text);
803            }
804
805            sprintf(text, "spec%i", counter);
806            GBT_readOrCreate_char_pntr(gb_species, "name", text); // set default if missing
807        }
808
809        if (filenames[1]) {      // multiple files !!!
810            const char *f = strrchr(filenames[current_file_idx-1], '/');
811            if (!f) f = filenames[current_file_idx-1];
812            else f++;
813            write_entry(gb_import_main, gb_species, "file", f, ifo->filetag, 0, GB_STRING);
814        }
815
816        static bool  never_warn = false;
817        int          max_line   = never_warn ? INT_MAX : MAX_COMMENT_LINES;
818        GBL_call_env callEnv(gb_species, env);
819
820        for (int line=0; line<=max_line; line++) {
821            if (line == max_line) {
822                char *msg = GBS_global_string_copy("A database entry in file '%s' is longer than %i lines.\n"
823                                                   " * possible reasons: wrong input format or very long comment/data\n"
824                                                   " * please examine imported data if you decide to continue\n",
825                                                   filenames[current_file_idx] ? filenames[current_file_idx] : "<unknown>",
826                                                   line);
827
828                switch (aw_question("import_long_lines", msg, "Continue Reading,Continue Reading (Never ask again),Abort")) {
829                    case 0:
830                        max_line *= 2;
831                        break;
832                    case 1:
833                        max_line = INT_MAX;
834                        never_warn = true;
835                        break;
836                    case 2:
837                        break;
838                }
839
840                free(msg);
841            }
842            GB_ERROR error = 0;
843            if (strlen(p) > ifo->tab) {
844                for (import_match *match = ifo->match; !error && match; match=match->next) {
845                    const char *what_error = 0;
846                    if (GBS_string_matches(p, match->match, GB_MIND_CASE)) {
847                        char *dup = p+ifo->tab;
848                        while (*dup == ' ' || *dup == '\t') dup++;
849
850                        char *s    = 0;
851                        char *dele = 0;
852
853                        if (match->srt) {
854                            bool   err_flag;
855                            string expanded = expandSetVariables(variables, match->srt, err_flag, ifo);
856                            if (err_flag) error = GB_await_error();
857                            else {
858                                dele           = s = GBS_string_eval_in_env(dup, expanded.c_str(), callEnv);
859                                if (!s) error  = GB_await_error();
860                            }
861                            if (error) what_error = "SRT";
862                        }
863                        else {
864                            s = dup;
865                        }
866
867                        if (!error && match->aci) {
868                            bool   err_flag;
869                            string expanded     = expandSetVariables(variables, match->aci, err_flag, ifo);
870                            if (err_flag) error = GB_await_error();
871                            else {
872                                dup  = dele;
873                                dele = s = GB_command_interpreter_in_env(s, expanded.c_str(), callEnv);
874                                if (!s) error = GB_await_error();
875                                free(dup);
876                            }
877                            if (error) what_error = "ACI";
878                        }
879
880                        if (!error && (match->append || match->write)) {
881                            char *field = 0;
882                            char *tag   = 0;
883
884                            {
885                                bool   err_flag;
886                                string expanded_field = expandSetVariables(variables, string(match->append ? match->append : match->write), err_flag, ifo);
887                                if (err_flag) error   = GB_await_error();
888                                else   field          = GBS_string_2_key(expanded_field.c_str());
889                                if (error) what_error = match->append ? "APPEND" : "WRITE";
890                            }
891
892                            if (!error && match->mtag) {
893                                bool   err_flag;
894                                string expanded_tag = expandSetVariables(variables, string(match->mtag), err_flag, ifo);
895                                if (err_flag) error = GB_await_error();
896                                else   tag          = GBS_string_2_key(expanded_tag.c_str());
897                                if (error) what_error = "TAG";
898                            }
899
900                            if (!error) {
901                                write_entry(gb_import_main, gb_species, field, s, tag, match->append != 0, match->type);
902                            }
903                            free(tag);
904                            free(field);
905                        }
906
907                        if (!error && match->setvar) variables.set(match->setvar[0], s);
908                        free(dele);
909                    }
910
911                    if (error) {
912                        error = GBS_global_string("'%s'\nin %s of MATCH (defined at #%s)", error, what_error, match->defined_at);
913                    }
914                }
915            }
916
917            if (error) {
918                return GBS_global_string("%s\nwhile parsing line #%i of species #%i", error, line, rel_counter);
919            }
920
921            if (GBS_string_matches(p, ifo->sequencestart, GB_MIND_CASE)) goto read_sequence;
922
923            p = read_line(ifo->tab, ifo->sequencestart, ifo->sequenceend);
924            if (!p) break;
925        }
926        return GB_export_errorf("No Start of Sequence found (%i lines read)", max_line);
927
928    read_sequence :
929        {
930            char          *sequence;
931            GBS_strstruct *strstruct = GBS_stropen(5000);
932            int            linecnt;
933
934            for (linecnt = 0; ; linecnt++) {
935                if (linecnt || !ifo->read_this_sequence_line_too) {
936                    p = read_line(0, ifo->sequencestart, ifo->sequenceend);
937                }
938                if (!p) break;
939                if (ifo->sequenceend && GBS_string_matches(p, ifo->sequenceend, GB_MIND_CASE)) break;
940                if (strlen(p) <= ifo->sequencecolumn) continue;
941                GBS_strcat(strstruct, p+ifo->sequencecolumn);
942            }
943            sequence = GBS_strclose(strstruct);
944
945            GBDATA *gb_data = GBT_create_sequence_data(gb_species, ali_name, "data", GB_STRING, security_write);
946            if (ifo->sequencesrt) {
947                char *h = GBS_string_eval_in_env(sequence, ifo->sequencesrt, callEnv);
948                if (!h) return GB_await_error();
949                freeset(sequence, h);
950            }
951
952            if (ifo->sequenceaci) {
953                char *h = GB_command_interpreter_in_env(sequence, ifo->sequenceaci, callEnv);
954                free(sequence);
955                if (!h) return GB_await_error();
956                sequence = h;
957            }
958
959            GB_write_string(gb_data, sequence);
960
961            GBDATA *gb_acc = GB_search(gb_species, "acc", GB_FIND);
962            if (!gb_acc && ifo->autocreateacc) {
963                char buf[100];
964                long id = GBS_checksum(sequence, 1, ".-");
965                sprintf(buf, "ARB_%lX", id);
966                gb_acc = GB_search(gb_species, "acc", GB_STRING);
967                GB_write_string(gb_acc, buf);
968            }
969            free(sequence);
970        }
971        while (1) {             // go to the start of an species
972            if (!p || !ifo->begin || GBS_string_matches(p, ifo->begin, GB_MIND_CASE)) break;
973            p = read_line(0, ifo->sequencestart, ifo->sequenceend);
974        }
975    }
976    return 0;
977}
978
979GB_ERROR ArbImporter::import_data(AW_root *awr, const char *mask, bool keep_found_IDs) {
980    // Import sequences into new or existing database
981    // if 'keep_found_IDs' is true => do not ask (mode used by format-tester)
982
983    awti_assert(!GB_have_error());
984
985    bool     is_genom_db             = false;
986    bool     delete_db_type_if_error = false; // delete db type (genome/normal) in case of error ?
987    GB_ERROR error                   = 0;
988
989    {
990        bool           read_genom_db = wants_import_genome(awr);
991        GB_transaction ta(gb_import_main);
992
993        delete_db_type_if_error = (GB_entry(gb_import_main, GENOM_DB_TYPE) == 0);
994        is_genom_db             = GEN_is_genome_db(gb_import_main, read_genom_db);
995
996        if (read_genom_db!=is_genom_db) {
997            if (is_genom_db) {
998                error = "You can only import whole genom sequences into a genom database.";
999            }
1000            else {
1001                error = "You can't import whole genom sequences into a non-genom ARB database.";
1002            }
1003            awti_assert(!GB_have_error());
1004            return error;
1005        }
1006    }
1007
1008    GB_change_my_security(gb_import_main, 6);
1009
1010    GB_begin_transaction(gb_import_main); // first transaction start
1011    char *ali_name;
1012    {
1013        char *ali = awr->awar(AWAR_IMPORT_ALI)->read_string();
1014        ali_name = GBS_string_eval(ali, SRT_AUTOCORRECT_ALINAME);
1015        free(ali);
1016    }
1017
1018    error = GBT_check_alignment_name(ali_name);
1019
1020    int ali_protection = awr->awar(AWAR_IMPORT_ALI_PROTECTION)->read_int();
1021    if (!error) {
1022        char *ali_type;
1023        ali_type = awr->awar(AWAR_IMPORT_ALI_TYPE)->read_string();
1024
1025        if (is_genom_db && strcmp(ali_type, "dna")!=0) {
1026            error = "You must set the alignment type to dna when importing genom sequences.";
1027        }
1028        else {
1029            GBT_create_alignment(gb_import_main, ali_name, 2000, 0, ali_protection, ali_type);
1030        }
1031        free(ali_type);
1032    }
1033
1034    bool ask_generate_names = true;
1035
1036    if (!error) {
1037        if (is_genom_db) {
1038            // import genome flatfile into ARB-genome database:
1039
1040            StrArray fnames;
1041            GBS_read_dir(fnames, mask, NULL);
1042            if (fnames.empty()) {
1043                error = GB_have_error() ? GB_await_error() : GBS_global_string("No file matched '%s'", mask);
1044            }
1045            else {
1046                int successfull_imports = 0;
1047                int failed_imports      = 0;
1048                int count;
1049
1050                for (count = 0; fnames[count]; ++count) ; // count filenames
1051
1052                GBDATA *gb_species_data = GBT_get_species_data(gb_import_main);
1053                ImportSession import_session(gb_species_data, count*10);
1054
1055                // close the above transaction and do each importfile in separate transaction
1056                // to avoid that all imports are undone by transaction abort happening in case of error
1057                GB_commit_transaction(gb_import_main);
1058
1059                arb_progress progress("Reading input files", count);
1060
1061                for (int curr = 0; !error && fnames[curr]; ++curr) {
1062                    GB_ERROR error_this_file =  0;
1063
1064                    GB_begin_transaction(gb_import_main);
1065                    {
1066                        const char *lslash = strrchr(fnames[curr], '/');
1067                        progress.subtitle(GBS_global_string("%i/%i: %s", curr+1, count, lslash ? lslash+1 : fnames[curr]));
1068                    }
1069
1070#if defined(DEBUG)
1071                    fprintf(stderr, "import of '%s'\n", fnames[curr]);
1072#endif // DEBUG
1073                    error_this_file = GI_importGenomeFile(import_session, fnames[curr], ali_name);
1074
1075                    if (!error_this_file) {
1076                        GB_commit_transaction(gb_import_main);
1077                        successfull_imports++;
1078                        delete_db_type_if_error = false;
1079                    }
1080                    else { // error occurred during import
1081                        error_this_file = GBS_global_string("'%s' not imported\nReason: %s", fnames[curr], error_this_file);
1082                        GB_warningf("Import error: %s", error_this_file);
1083                        GB_abort_transaction(gb_import_main);
1084                        failed_imports++;
1085                    }
1086
1087                    progress.inc_and_check_user_abort(error);
1088                }
1089
1090                if (!successfull_imports) {
1091                    error = "Nothing has been imported";
1092                }
1093                else {
1094                    GB_warningf("%i of %i files were imported with success", successfull_imports, (successfull_imports+failed_imports));
1095                }
1096
1097                // now open another transaction to "undo" the transaction close above
1098                GB_begin_transaction(gb_import_main);
1099            }
1100        }
1101        else {
1102            // import to non-genome ARB-db :
1103
1104            {
1105                // load import filter:
1106                char *file = awr->awar(AWAR_IMPORT_FORMATNAME)->read_string();
1107
1108                if (!strlen(file)) {
1109                    error = "Please select a form";
1110                }
1111                else {
1112                    error = read_format(file);
1113                    if (!error && ifo->new_format) {
1114                        ifo2 = ifo;
1115                        ifo  = 0;
1116
1117                        error = read_format(ifo2->new_format);
1118                        if (!error) {
1119                            if (ifo->new_format) {
1120                                error = GBS_global_string("in line %zi of import filter '%s':\n"
1121                                                          "Only one level of form nesting (NEW_FORMAT) allowed",
1122                                                          ifo->new_format_lineno, name_only(ifo2->new_format));
1123                            }
1124                        }
1125                        if (error) {
1126                            error = GBS_global_string("in format used in line %zi of '%s':\n%s",
1127                                                      ifo2->new_format_lineno, name_only(file), error);
1128                        }
1129                    }
1130                }
1131                free(file);
1132            }
1133
1134            GBS_read_dir(filenames, mask, NULL);
1135            if (filenames.empty()) {
1136                error = GB_have_error() ? GB_await_error() : GBS_global_string("No file matched '%s'", mask);
1137            }
1138
1139            if (!error) {
1140                arb_progress progress("Reading input files");
1141
1142                error = read_data(ali_name, ali_protection);
1143                if (error) {
1144                    error = GBS_global_string("Error: %s\nwhile reading file %s", error, filenames[current_file_idx-1]);
1145                }
1146                else {
1147                    if (ifo->noautonames || (ifo2 && ifo2->noautonames)) {
1148                        ask_generate_names = false;
1149                    }
1150                    else {
1151                        ask_generate_names = true;
1152                    }
1153                }
1154            }
1155
1156            delete ifo;  ifo  = 0;
1157            delete ifo2; ifo2 = 0;
1158
1159            if (in) { fclose(in); in = 0; }
1160
1161            filenames.erase();
1162            current_file_idx = 0;
1163        }
1164    }
1165    free(ali_name);
1166
1167    if (error) {
1168        GB_abort_transaction(gb_import_main);
1169
1170        if (delete_db_type_if_error) {
1171            // delete db type, if it was initialized above
1172            // (avoids 'can't import'-error, if file-type (genome-file/species-file) is changed after a failed try)
1173            GB_transaction  ta(gb_import_main);
1174            GBDATA         *db_type = GB_entry(gb_import_main, GENOM_DB_TYPE);
1175            if (db_type) GB_delete(db_type);
1176        }
1177    }
1178    else {
1179        arb_progress progress("Checking and Scanning database", 2+ask_generate_names); // 2 or 3 passes
1180        progress.subtitle("Pass 1: Check entries");
1181
1182        // scan for hidden/unknown fields :
1183        species_field_selection_list_rescan(gb_import_main, RESCAN_REFRESH);
1184        if (is_genom_db) gene_field_selection_list_rescan(gb_import_main, RESCAN_REFRESH);
1185
1186        GBT_mark_all(gb_import_main, 1);
1187        progress.inc();
1188        progress.subtitle("Pass 2: Check sequence lengths");
1189        GBT_check_data(gb_import_main, 0);
1190
1191        GB_commit_transaction(gb_import_main);
1192        progress.inc();
1193
1194        if (ask_generate_names && !keep_found_IDs) {
1195            if (aw_question("generate_short_names",
1196                            "It's recommended to generate unique species identifiers now.\n",
1197                            "Generate unique species IDs,Use found IDs") == 0)
1198            {
1199                progress.subtitle("Pass 3: Generate unique species IDs");
1200                error = AW_select_nameserver(gb_import_main, gb_main_4_nameserver);
1201                if (!error) {
1202                    error = AWTC_pars_names(gb_import_main);
1203                }
1204            }
1205            progress.inc();
1206        }
1207    }
1208
1209    GB_change_my_security(gb_import_main, 0);
1210
1211    // gb_main_4_nameserver = NULL; // this was only needed once. may interfere with import-tester
1212
1213    awti_assert(!GB_have_error());
1214    return error;
1215}
1216
1217void ArbImporter::import_and_continueOnSuccess(AW_window *aww) {
1218    AW_root  *awr   = aww->get_root();
1219    char     *mask  = awr->awar(AWAR_IMPORT_FILENAME)->read_string();
1220    GB_ERROR  error = import_data(awr, mask, false);
1221    if (error) {
1222        aw_message(error);
1223    }
1224    else {
1225        aww->hide(); // import window stays open in case of error
1226        after_import_cb(awr);
1227    }
1228    free(mask);
1229}
1230
1231class AliNameAndType {
1232    string name_, type_;
1233public:
1234    AliNameAndType(const char *ali_name, const char *ali_type) : name_(ali_name), type_(ali_type) {}
1235
1236    const char *name() const { return name_.c_str(); }
1237    const char *type() const { return type_.c_str(); }
1238};
1239
1240static AliNameAndType last_ali("ali_new", "rna"); // last selected ali for plain import (aka non-flatfile import)
1241
1242
1243void AWTI_import_set_ali_and_type(AW_root *awr, const char *ali_name, const char *ali_type, GBDATA *gbmain) {
1244    bool           switching_to_GENOM_ALIGNMENT = strcmp(ali_name, GENOM_ALIGNMENT) == 0;
1245    static GBDATA *last_valid_gbmain            = 0;
1246
1247    if (gbmain) last_valid_gbmain = gbmain;
1248
1249    AW_awar *awar_name = awr->awar(AWAR_IMPORT_ALI);
1250    AW_awar *awar_type = awr->awar(AWAR_IMPORT_ALI_TYPE);
1251
1252    if (switching_to_GENOM_ALIGNMENT) {
1253        // read and store current settings
1254        char *curr_ali_name = awar_name->read_string();
1255        char *curr_ali_type = awar_type->read_string();
1256
1257        last_ali = AliNameAndType(curr_ali_name, curr_ali_type);
1258
1259        free(curr_ali_name);
1260        free(curr_ali_type);
1261    }
1262
1263    awar_name->write_string(ali_name);
1264    awar_type->write_string(ali_type);
1265
1266    if (last_valid_gbmain) { // detect default write protection for alignment
1267        GB_transaction ta(last_valid_gbmain);
1268        GBDATA *gb_ali            = GBT_get_alignment(last_valid_gbmain, ali_name);
1269        int     protection_to_use = 4;         // default protection
1270
1271        if (gb_ali) {
1272            GBDATA *gb_write_security = GB_entry(gb_ali, "alignment_write_security");
1273            if (gb_write_security) {
1274                protection_to_use = GB_read_int(gb_write_security);
1275            }
1276        }
1277        else {
1278            GB_clear_error();
1279        }
1280        awr->awar(AWAR_IMPORT_ALI_PROTECTION)->write_int(protection_to_use);
1281    }
1282}
1283
1284static void genom_flag_changed(AW_root *awr) {
1285    if (wants_import_genome(awr)) {
1286        AWTI_import_set_ali_and_type(awr, GENOM_ALIGNMENT, "dna", 0);
1287        awr->awar(AWAR_IMPORT_FORMATFILTER)->write_string(".fit"); // *hack* to hide normal import filters
1288    }
1289    else {
1290        AWTI_import_set_ali_and_type(awr, last_ali.name(), last_ali.type(), 0);
1291        awr->awar(AWAR_IMPORT_FORMATFILTER)->write_string(".ift");
1292    }
1293}
1294
1295// --------------------------------------------------------------------------------
1296
1297static ArbImporter *importer = NULL;
1298
1299void AWTI_cleanup_importer() {
1300    if (importer) {
1301#if defined(DEBUG)
1302        AWT_browser_forget_db(importer->peekImportDB());
1303#endif
1304        delete importer; // closes the import DB if it still is owned by the 'importer'
1305        importer = NULL;
1306    }
1307}
1308
1309static void import_window_close_cb(AW_window *aww, bool *doExit) {
1310    if (importer) {
1311        AWTI_cleanup_importer();
1312        if (*doExit) exit(EXIT_SUCCESS);
1313        else AW_POPDOWN(aww);
1314    }
1315    else {
1316        AW_POPDOWN(aww);
1317    }
1318}
1319
1320static void import_and_continue_cb(AW_window *aww) { importer->import_and_continueOnSuccess(aww); }
1321static void detect_input_format_cb(AW_window *aww) {
1322    if (wants_import_genome(aww->get_root())) {
1323        aw_message("Only works together with 'Import selected format'");
1324    }
1325    else {
1326        importer->detect_format(aww->get_root());
1327    }
1328}
1329
1330static void update_format_description(const char *ift) {
1331    const char *description = NULL;
1332    GB_ERROR    err         = importer->read_format(ift);
1333
1334    if (err) {
1335        description = GBS_global_string("Error reading format:\n%s", err);
1336    }
1337    else {
1338        const import_format *ifo = importer->peek_format();
1339
1340        if      (!ifo || !ift[0])   description = "<no format selected>";
1341        else if (!ifo->description) description = "<no description>";
1342        else                        description = ifo->description;
1343    }
1344    AW_root::SINGLETON->awar(AWAR_IMPORT_FORMAT_DESC)->write_string(description);
1345}
1346
1347void AWTI_set_importDB_pointer(GBDATA*& dbPtr) {
1348    awti_assert(importer);
1349    GBDATA *gb_imain = importer->peekImportDB();
1350    awti_assert(gb_imain);
1351    awti_assert(!dbPtr || dbPtr == gb_imain);
1352    dbPtr = gb_imain;
1353}
1354GBDATA *AWTI_acquire_imported_DB_and_cleanup_importer() {
1355    awti_assert(importer && importer->peekImportDB());
1356    GBDATA *gb_imported_main = importer->takeImportDB();
1357    AWTI_cleanup_importer();
1358    return gb_imported_main;
1359}
1360
1361static void create_import_awars(AW_root *awr, const char *def_importname) {
1362    {
1363        GBS_strstruct path(500);
1364        path.cat(GB_path_in_arbprop("filter"));
1365        path.put(':');
1366        path.cat(GB_path_in_ARBLIB("import"));
1367
1368        AW_create_fileselection_awars(awr, AWAR_IMPORT_FILEBASE,   ".",             "",     def_importname);
1369        AW_create_fileselection_awars(awr, AWAR_IMPORT_FORMATBASE, path.get_data(), ".ift", "*");
1370    }
1371
1372    awr->awar_string(AWAR_IMPORT_FORMAT_DESC,    "<undefined>");
1373    awr->awar_string(AWAR_IMPORT_ALI,            "<undefined>"); // these defaults are never used
1374    awr->awar_string(AWAR_IMPORT_ALI_TYPE,       "<undefined>"); // they are overwritten by AWTI_import_set_ali_and_type
1375    awr->awar_int   (AWAR_IMPORT_ALI_PROTECTION, 0);             // which is called via genom_flag_changed() below
1376
1377    awr->awar_int(AWAR_IMPORT_GENOM_DB, IMP_PLAIN_SEQUENCE);
1378    awr->awar_int(AWAR_IMPORT_AUTOCONF, 1);
1379
1380    awr->awar(AWAR_IMPORT_GENOM_DB)->add_callback(genom_flag_changed);
1381    genom_flag_changed(awr);
1382}
1383
1384void AWTI_open_import_window(AW_root *awr, const char *def_importname, bool do_exit, GBDATA *gb_main, const RootCallback& after_import_cb) {
1385    static AW_window_simple *aws = 0;
1386
1387    if (!importer) {
1388        importer = new ArbImporter(after_import_cb);
1389
1390#if defined(DEBUG)
1391        AWT_announce_db_to_browser(importer->peekImportDB(), "New database (import)");
1392#endif // DEBUG
1393
1394        importer->set_db_4_nameserver(gb_main);
1395        if (!gb_main) {
1396            // control macros via temporary import DB (if no main DB available)
1397            GB_ERROR error = configure_macro_recording(awr, "ARB_IMPORT", importer->peekImportDB());
1398            aw_message_if(error);
1399        }
1400        else {
1401            awti_assert(got_macro_ability(awr));
1402        }
1403    }
1404
1405    static bool doExit;
1406    doExit = do_exit; // change/set behavior of CLOSE button
1407
1408    if (aws) {
1409        if (def_importname) {
1410            awr->awar(AWAR_IMPORT_FILENAME)->write_string(def_importname);
1411        }
1412    }
1413    else {
1414        create_import_awars(awr, def_importname);
1415
1416        aws = new AW_window_simple;
1417
1418        aws->init(awr, "ARB_IMPORT", "ARB IMPORT");
1419        aws->load_xfig("awt/import_db.fig");
1420
1421        aws->at("close");
1422        aws->callback(makeWindowCallback(import_window_close_cb, &doExit));
1423        aws->create_button("CLOSE", "CLOSE", "C");
1424
1425        aws->at("help");
1426        aws->callback(makeHelpCallback("arb_import.hlp"));
1427        aws->create_button("HELP", "HELP", "H");
1428
1429        AW_create_fileselection(aws, AWAR_IMPORT_FILEBASE,   "imp_", "PWD",     ANY_DIR,    true);  // select import filename
1430        AW_create_fileselection(aws, AWAR_IMPORT_FORMATBASE, "",     "ARBHOME", MULTI_DIRS, false); // select import filter
1431
1432        aws->at("auto");
1433        aws->callback(detect_input_format_cb);
1434        aws->create_autosize_button("AUTO_DETECT", "AUTO DETECT", "A");
1435
1436        aws->at("ali");
1437        aws->create_input_field(AWAR_IMPORT_ALI, 4);
1438
1439        aws->at("type");
1440        aws->create_option_menu(AWAR_IMPORT_ALI_TYPE, true);
1441        aws->insert_option        ("dna",     "d", "dna");
1442        aws->insert_default_option("rna",     "r", "rna");
1443        aws->insert_option        ("protein", "p", "ami");
1444        aws->update_option_menu();
1445
1446        aws->at("protect");
1447        aws->create_option_menu(AWAR_IMPORT_ALI_PROTECTION, true);
1448        aws->insert_option("0", "0", 0);
1449        aws->insert_option("1", "1", 1);
1450        aws->insert_option("2", "2", 2);
1451        aws->insert_option("3", "3", 3);
1452        aws->insert_default_option("4", "4", 4);
1453        aws->insert_option("5", "5", 5);
1454        aws->insert_option("6", "6", 6);
1455        aws->update_option_menu();
1456
1457        aws->at("genom");
1458        aws->create_toggle_field(AWAR_IMPORT_GENOM_DB);
1459        aws->sens_mask(AWM_EXP);
1460        aws->insert_toggle("Import genome data in EMBL, GenBank or DDBJ format", "e", IMP_GENOME_FLATFILE);
1461        aws->sens_mask(AWM_ALL);
1462        aws->insert_toggle("Import selected format", "f", IMP_PLAIN_SEQUENCE);
1463        aws->update_toggle_field();
1464
1465        aws->at("autoconf");
1466        aws->create_toggle(AWAR_IMPORT_AUTOCONF);
1467
1468        aws->at("desc");
1469        aws->create_text_field(AWAR_IMPORT_FORMAT_DESC);
1470
1471        aws->at("go");
1472        aws->callback(import_and_continue_cb);
1473        aws->highlight();
1474        aws->create_button("GO", "GO", "G", "+");
1475
1476        aws->at("test");
1477        aws->callback(AWTI_activate_import_test_window);
1478        aws->create_button("TEST", "Test", "T");
1479
1480        static FileWatch fwatch(AWAR_IMPORT_FORMATNAME, makeFileChangedCallback(update_format_description));
1481    }
1482    aws->activate();
1483}
1484
1485// --------------------------------------------------------------------------------
1486
1487#ifdef UNIT_TESTS
1488#ifndef TEST_UNIT_H
1489#include <test_unit.h>
1490#endif
1491
1492static void after_import_test_cb(AW_root*) {}
1493
1494void TEST_import_filters_loadable() {
1495    GB_shell    shell;
1496    ArbImporter testImporter(makeRootCallback(after_import_test_cb));
1497
1498    // Test that delivered filters are loadable w/o error:
1499    StrArray impFilt;
1500    GBS_read_dir(impFilt, GB_path_in_ARBLIB("import"), "/\\.ift$/"); // all filters in ../lib/import
1501    TEST_EXPECT_EQUAL(impFilt.size(), 9);                            // amount of import filters
1502
1503    for (int i = 0; impFilt[i]; ++i) {
1504        const char *name = strrchr(impFilt[i], '/')+1;
1505        TEST_ANNOTATE(name);
1506        TEST_EXPECT_NO_ERROR(testImporter.read_format(impFilt[i]));
1507
1508        if (strcmp(name, "fasta_wgap.ift") == 0) {
1509            TEST_EXPECT_EQUAL(testImporter.peek_format()->description,
1510                              "Imports sequences in FASTA format (does not remove gaps)\n"
1511                              "Expected header: '>id fullname|...'");
1512        }
1513    }
1514}
1515
1516#endif // UNIT_TESTS
1517
1518// --------------------------------------------------------------------------------
1519
Note: See TracBrowser for help on using the repository browser.