source: tags/arb-6.0/AWTI/AWTI_import.cxx

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