source: trunk/EDIT4/ED4_cursor.cxx

Last change on this file was 19393, checked in by westram, 10 months ago
  • reintegrates 'ali' into 'trunk'
    • refactored misused enum
    • support for helix pairs:
      • drop non-standard defs
      • add more user defs
    • change defaults
    • add several predefined configs (esp. for IUPAC ambiguity codes)
  • adds: log:branches/ali@19376:19392
  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 60.7 KB
Line 
1#include <cctype>
2#include <climits>
3
4#include <arbdbt.h>
5#include <aw_awars.hxx>
6#include <AW_helix.hxx>
7#include <BI_basepos.hxx>
8#include <aw_msg.hxx>
9#include <arb_progress.h>
10#include <aw_root.hxx>
11#include <iupac.h>
12
13#include <ed4_extern.hxx>
14
15#include "ed4_class.hxx"
16#include "ed4_edit_string.hxx"
17#include "ed4_tools.hxx"
18#include "ed4_awars.hxx"
19#include "ed4_ProteinViewer.hxx"
20#include "ed4_seq_colors.hxx"
21
22#include <arb_strbuf.h>
23#include <arb_defs.h>
24
25/* --------------------------------------------------------------------------------
26   CursorShape
27   -------------------------------------------------------------------------------- */
28
29#define MAXLINES  30
30#define MAXPOINTS (2*MAXLINES)
31
32class ED4_CursorShape {
33    int points;
34    int xpos[MAXPOINTS];
35    int ypos[MAXPOINTS];
36
37    int lines;
38    int start[MAXLINES];
39    int end[MAXLINES];
40
41    int char_width;
42
43    bool reverse;
44
45    int point(int x, int y) {
46        e4_assert(points<MAXPOINTS);
47        if (reverse) {
48            xpos[points] = char_width-x;
49        }
50        else {
51            xpos[points] = x;
52        }
53        ypos[points] = y;
54        return points++;
55    }
56    int line(int p1, int p2) {
57        e4_assert(p1>=0 && p1<points);
58        e4_assert(p2>=0 && p2<points);
59
60        e4_assert(lines<MAXLINES);
61        start[lines] = p1;
62        end[lines] = p2;
63
64        return lines++;
65    }
66    int horizontal_line(int x, int y, int half_width) {
67        return line(point(x-half_width, y), point(x+half_width, y));
68    }
69
70public:
71
72    ED4_CursorShape(ED4_CursorType type, int term_height, int character_width, bool reverse_cursor);
73    ~ED4_CursorShape() {}
74
75    void draw(AW_device *device, int x, int y) const {
76        e4_assert(lines);
77        for (int l=0; l<lines; l++) {
78            int p1 = start[l];
79            int p2 = end[l];
80            device->line(ED4_G_CURSOR, xpos[p1]+x, ypos[p1]+y, xpos[p2]+x, ypos[p2]+y, AW_SCREEN);
81        }
82        device->flush();
83    }
84
85    void get_bounding_box(int x, int y, int &xmin, int &ymin, int &xmax, int &ymax) const {
86        e4_assert(points);
87        xmin = ymin = INT_MAX;
88        xmax = ymax = INT_MIN;
89        for (int p=0; p<points; p++) {
90            if (xpos[p]<xmin)      { xmin = xpos[p]; }
91            else if (xpos[p]>xmax) { xmax = xpos[p]; }
92            if (ypos[p]<ymin)      { ymin = ypos[p]; }
93            else if (ypos[p]>ymax) { ymax = ypos[p]; }
94        }
95
96        xmin += x; xmax += x;
97        ymin += y; ymax += y;
98    }
99
100
101};
102
103ED4_CursorShape::ED4_CursorShape(ED4_CursorType typ, /* int x, int y, */ int term_height, int character_width, bool reverse_cursor) {
104    lines      = 0;
105    points     = 0;
106    reverse    = reverse_cursor;
107    char_width = character_width;
108
109    int x = 0;
110    int y = 0;
111
112    switch (typ) {
113#define UPPER_OFFSET    (-1)
114#define LOWER_OFFSET    (term_height-1)
115#define CWIDTH          (character_width)
116
117        case ED4_RIGHT_ORIENTED_CURSOR_THIN:
118        case ED4_RIGHT_ORIENTED_CURSOR: {
119            // --CWIDTH--
120            //
121            // 0--------1               UPPER_OFFSET (from top)
122            // |3-------4
123            // ||
124            // ||
125            // ||
126            // ||
127            // ||
128            // ||
129            // 25                       LOWER_OFFSET (from top)
130            //
131            //
132            //  x
133
134            if (typ == ED4_RIGHT_ORIENTED_CURSOR) { // non-thin version
135                int p0 = point(x-1, y+UPPER_OFFSET);
136
137                line(p0, point(x+CWIDTH-1, y+UPPER_OFFSET)); // 0->1
138                line(p0, point(x-1, y+LOWER_OFFSET)); // 0->2
139            }
140
141            int p3 = point(x, y+UPPER_OFFSET+1);
142
143            line(p3, point(x+CWIDTH-1, y+UPPER_OFFSET+1)); // 3->4
144            line(p3, point(x, y+LOWER_OFFSET)); // 3->5
145
146            break;
147
148#undef UPPER_OFFSET
149#undef LOWER_OFFSET
150#undef CWIDTH
151
152        }
153        case ED4_TRADITIONAL_CURSOR_CONNECTED:
154        case ED4_TRADITIONAL_CURSOR_BOTTOM:
155        case ED4_TRADITIONAL_CURSOR: {
156            int small_version = (term_height <= 10) ? 1 : 0;
157
158
159#define UPPER_OFFSET    0
160#define LOWER_OFFSET    (term_height-1)
161#define CWIDTH          3
162
163            //  -----2*CWIDTH----
164            //
165            //  0---------------1       UPPER_OFFSET (from top)
166            //     4---------5
167            //        8---9
168            //         C/C
169            //
170            //         D/D
171            //        A---B
172            //     6---------7
173            //  2---------------3       LOWER_OFFSET (from top)
174
175            bool draw_upper = typ != ED4_TRADITIONAL_CURSOR_BOTTOM;
176
177            if (draw_upper) horizontal_line(x, y+UPPER_OFFSET, CWIDTH-small_version); // 0/1
178            horizontal_line(x, y+LOWER_OFFSET, CWIDTH-small_version); // 2/3
179
180            if (draw_upper) horizontal_line(x, y+UPPER_OFFSET+1, (CWIDTH*2)/3-small_version); // 4/5
181            horizontal_line(x, y+LOWER_OFFSET-1, (CWIDTH*2)/3-small_version); // 6/7
182
183            if (!small_version) {
184                if (draw_upper) horizontal_line(x, y+UPPER_OFFSET+2, CWIDTH/3); // 8/9
185                horizontal_line(x, y+LOWER_OFFSET-2, CWIDTH/3); // A/B
186            }
187
188            int pu = point(x, y+UPPER_OFFSET+3-small_version);
189            int pl = point(x, y+LOWER_OFFSET-3+small_version);
190
191            if (draw_upper) line(pu, pu);   // C/C
192            line(pl, pl);   // D/D
193
194            if (typ == ED4_TRADITIONAL_CURSOR_CONNECTED) {
195                int pu2 = point(x, y+UPPER_OFFSET+5-small_version);
196                int pl2 = point(x, y+LOWER_OFFSET-5+small_version);
197                line(pu2, pl2);
198            }
199
200            break;
201
202#undef UPPER_OFFSET
203#undef LOWER_OFFSET
204#undef CWIDTH
205
206        }
207        case ED4_FUCKING_BIG_CURSOR: {
208
209#define OUTER_HEIGHT    (term_height/4)
210#define INNER_HEIGHT    (term_height-1)
211#define CWIDTH          12
212#define STEPS           6
213#define THICKNESS       2
214
215#if (2*STEPS+THICKNESS > MAXLINES)
216#error Bad definitions!
217#endif
218
219            //          2               3               |
220            //            \           /                 | OUTER_HEIGHT
221            //               \     /                    |
222            //                  0               |       |
223            //                  |               | INNER_HEIGHT
224            //                  |               |
225            //                  1               |
226            //                /    \                    --
227            //             /          \                 --
228            //          4               5
229            //
230            //          -----------------
231            //                2*WIDTH
232
233            int s;
234            for (s=0; s<STEPS; s++) {
235                int size = ((STEPS-s)*CWIDTH)/STEPS;
236
237                horizontal_line(x, y-OUTER_HEIGHT+s,                    size);
238                horizontal_line(x, y+INNER_HEIGHT+OUTER_HEIGHT-s,       size);
239            }
240
241            int y_upper = ypos[s-4];
242            int y_lower = ypos[s-2];
243
244            int t;
245            for (t=0; t<THICKNESS; t++) {
246                int xp = x-(THICKNESS/2)+t+1;
247                line(point(xp, y_upper), point(xp, y_lower));
248            }
249
250            break;
251
252#undef OUTER_HEIGHT
253#undef INNER_HEIGHT
254#undef CWIDTH
255#undef STEPS
256#undef THICKNESS
257
258        }
259        default: {
260            e4_assert(0);
261            break;
262        }
263    }
264}
265
266/* --------------------------------------------------------------------------------
267   ED4_cursor
268   -------------------------------------------------------------------------------- */
269
270static bool allow_update_global_cursorpos = true;
271
272ED4_returncode ED4_cursor::draw_cursor(AW_pos x, AW_pos y) { // @@@ remove return value
273    if (cursor_shape) {
274        delete cursor_shape;
275        cursor_shape = NULp;
276    }
277
278    cursor_shape = new ED4_CursorShape(ctype,
279                                       SEQ_TERM_TEXT_YOFFSET+2,
280                                       ED4_ROOT->font_group.get_width(ED4_G_SEQUENCES),
281                                       !awar_edit_rightward);
282
283    cursor_shape->draw(window()->get_device(), int(x), int(y));
284
285#if defined(TRACE_REFRESH)
286    printf("draw_cursor(%i, %i)\n", int(x), int(y));
287#endif // TRACE_REFRESH
288
289    return ED4_R_OK;
290}
291
292ED4_returncode ED4_cursor::delete_cursor(AW_pos del_mark, ED4_base *target_terminal) {
293    AW_pos x, y;
294    target_terminal->calc_world_coords(&x, &y);
295    ED4_base *temp_parent = target_terminal->get_parent(LEV_SPECIES);
296    if (!temp_parent || temp_parent->flag.hidden || !is_partly_visible()) {
297        return ED4_R_BREAK;
298    }
299
300    x = del_mark;
301    win->world_to_win_coords(&x, &y);
302
303    // refresh own terminal + terminal above + terminal below
304
305    const int     MAX_AFFECTED = 3;
306    int           affected     = 0;
307    ED4_terminal *affected_terminal[MAX_AFFECTED];
308
309    affected_terminal[affected++] = target_terminal->to_terminal();
310
311    {
312        ED4_terminal *term = target_terminal->to_terminal();
313        bool backward = true;
314
315        while (1) {
316            int done = 0;
317
318            term = backward ? term->get_prev_terminal() : term->get_next_terminal();
319            if (!term) done = 1;
320            else if ((term->is_sequence_terminal()) && !term->is_in_folded_group()) {
321                affected_terminal[affected++] = term;
322                done                          = 1;
323            }
324
325            if (done) {
326                if (!backward) break;
327                backward = false;
328                term = target_terminal->to_terminal();
329            }
330        }
331    }
332
333    bool refresh_was_requested[MAX_AFFECTED];
334    e4_assert(affected >= 1 && affected <= MAX_AFFECTED);
335    for (int a = 0; a<affected; ++a) {
336        ED4_terminal *term       = affected_terminal[a];
337        refresh_was_requested[a] = term->update_info.refresh;
338        term->request_refresh();
339    }
340
341    // clear rectangle where cursor is displayed
342
343    AW_device *dev = win->get_device();
344    dev->push_clip_scale();
345
346    int xmin, xmax, ymin, ymax;
347
348    e4_assert(cursor_shape);
349    cursor_shape->get_bounding_box(int(x), int(y), xmin, ymin, xmax, ymax);
350
351#if defined(TRACE_REFRESH)
352    printf("delete_cursor(%i, %i)\n", int(x), int(y));
353#endif // TRACE_REFRESH
354
355    dev->set_font_overlap(true);
356
357#define EXPAND_SIZE 0
358    if (dev->reduceClipBorders(ymin-EXPAND_SIZE, ymax+EXPAND_SIZE, xmin-EXPAND_SIZE, xmax+EXPAND_SIZE)) {
359        dev->clear_part(xmin, ymin, xmax-xmin+1, ymax-ymin+1, AW_ALL_DEVICES);
360        // refresh terminal to hide cursor
361        ED4_LocalWinContext uses(window());
362        LocallyModify<bool> flag(allowed_to_draw, false);
363        ED4_ROOT->special_window_refresh(false);
364    }
365    dev->pop_clip_scale();
366
367    // restore old refresh flags (to avoid refresh of 3 complete terminals when cursor changes)
368    for (int a = 0; a<affected; ++a) {
369        affected_terminal[a]->update_info.refresh = refresh_was_requested[a];
370    }
371
372    return ED4_R_OK;
373}
374
375
376ED4_cursor::ED4_cursor(ED4_window *win_) : win(win_) {
377    init();
378    allowed_to_draw = true;
379    cursor_shape    = NULp;
380
381    ctype = (ED4_CursorType)(ED4_ROOT->aw_root->awar(ED4_AWAR_CURSOR_TYPE)->read_int()%ED4_CURSOR_TYPES);
382}
383void ED4_cursor::init() {
384    // used by ED4_terminal-d-tor
385    owner_of_cursor   = NULp;
386    cursor_abs_x      = 0;
387    screen_position   = 0;
388}
389ED4_cursor::~ED4_cursor() {
390    delete cursor_shape;
391}
392
393int ED4_cursor::get_sequence_pos() const {
394    ED4_remap *remap = ED4_ROOT->root_group_man->remap();
395    size_t max_scrpos = remap->get_max_screen_pos();
396
397    return remap->screen_to_sequence(size_t(screen_position)<=max_scrpos ? screen_position : max_scrpos);
398}
399
400bool ED4_species_manager::setCursorTo(ED4_cursor *cursor, int seq_pos, bool unfold_groups, ED4_CursorJumpType jump_type) {
401    ED4_group_manager *group_manager_to_unfold = is_in_folded_group();
402
403    if (unfold_groups) {
404        bool did_unfold = false;
405
406        while (group_manager_to_unfold && unfold_groups) {
407            group_manager_to_unfold->unfold();
408            did_unfold              = true;
409            group_manager_to_unfold = is_in_folded_group();
410        }
411
412        if (did_unfold) ED4_ROOT->refresh_all_windows(1); // needed to recalculate world cache of target terminal
413    }
414
415    if (!group_manager_to_unfold) { // species manager is visible (now)
416        ED4_terminal *terminal = search_spec_child_rek(LEV_SEQUENCE_STRING)->to_terminal();
417        if (terminal) {
418            if (seq_pos == -1) seq_pos = cursor->get_sequence_pos();
419            cursor->set_to_terminal(terminal, seq_pos, jump_type);
420            return true;
421        }
422    }
423
424    return false;
425}
426
427static void jump_to_corresponding_seq_terminal(ED4_species_name_terminal *name_term, bool unfold_groups) {
428    ED4_species_manager *species_manager = name_term->get_parent(LEV_SPECIES)->to_species_manager();
429    ED4_cursor          *cursor          = &current_cursor();
430    bool                 jumped          = false;
431
432    if (species_manager) jumped = species_manager->setCursorTo(cursor, -1, unfold_groups, ED4_JUMP_KEEP_POSITION);
433    if (!jumped) cursor->HideCursor();
434}
435
436static bool ignore_selected_species_changes_cb = false;
437static bool ignore_selected_SAI_changes_cb     = false;
438
439static void select_named_sequence_terminal(const char *name) {
440    GB_transaction ta(ED4_ROOT->get_gb_main());
441    ED4_species_name_terminal *name_term = ED4_find_species_or_SAI_name_terminal(name);
442    if (name_term) {
443        ED4_MostRecentWinContext context; // use the last used window for selection
444
445        // lookup current name term
446        ED4_species_name_terminal *cursor_name_term = NULp;
447        {
448            ED4_cursor *cursor = &current_cursor();
449            if (cursor) {
450                ED4_sequence_terminal *cursor_seq_term = NULp;
451
452                if (cursor->owner_of_cursor) {
453                    ED4_terminal *cursor_term = cursor->owner_of_cursor->to_text_terminal();
454                    if (cursor_term->is_sequence_terminal()) {
455                        cursor_seq_term = cursor_term->to_sequence_terminal();
456                    }
457                    else { // cursor is in a non-sequence text terminal -> search for corresponding sequence terminal
458                        ED4_multi_sequence_manager *seq_man = cursor_term->get_parent(LEV_MULTI_SEQUENCE)->to_multi_sequence_manager();
459                        if (seq_man) {
460                            cursor_seq_term = seq_man->search_spec_child_rek(LEV_SEQUENCE_STRING)->to_sequence_terminal();
461                        }
462                    }
463                }
464                if (cursor_seq_term) {
465                    cursor_name_term = cursor_seq_term->corresponding_species_name_terminal();
466                }
467            }
468        }
469
470        if (name_term!=cursor_name_term) { // do not change if already there!
471#if defined(TRACE_JUMPS)
472            printf("Jumping to species/SAI '%s'\n", name);
473#endif
474            jump_to_corresponding_seq_terminal(name_term, false);
475        }
476        else {
477#if defined(TRACE_JUMPS)
478            printf("Change ignored because same name term!\n");
479#endif
480        }
481    }
482}
483
484void ED4_selected_SAI_changed_cb(AW_root * /* aw_root */) {
485    if (!ignore_selected_SAI_changes_cb) {
486        char *name = GBT_read_string(ED4_ROOT->get_gb_main(), AWAR_SAI_NAME);
487
488        if (name && name[0]) {
489#if defined(TRACE_JUMPS)
490            printf("Selected SAI is '%s'\n", name);
491#endif // DEBUG
492            LocallyModify<bool> flag(allow_update_global_cursorpos, false);
493            select_named_sequence_terminal(name);
494            free(name);
495        }
496    }
497}
498
499void ED4_selected_species_changed_cb(AW_root * /* aw_root */) {
500    if (!ignore_selected_species_changes_cb) {
501        char *name = GBT_read_string(ED4_ROOT->get_gb_main(), AWAR_SPECIES_NAME);
502        if (name && name[0]) {
503#if defined(TRACE_JUMPS)
504            printf("Selected species is '%s'\n", name);
505#endif
506            LocallyModify<bool> flag(allow_update_global_cursorpos, false);
507            select_named_sequence_terminal(name);
508        }
509        free(name);
510    }
511    else {
512#if defined(TRACE_JUMPS)
513        printf("Change ignored because ignore_selected_species_changes_cb!\n");
514#endif
515    }
516}
517
518void ED4_jump_to_current_species(AW_window *aww) {
519    ED4_LocalWinContext uses(aww);
520
521    GBDATA *gb_main = ED4_ROOT->get_gb_main();
522    char   *name    = GBT_read_string(gb_main, AWAR_SPECIES_NAME);
523    if (name && name[0]) {
524        GB_transaction ta(gb_main);
525#if defined(TRACE_JUMPS)
526        printf("Jump to selected species (%s)\n", name);
527#endif
528        ED4_species_name_terminal *name_term = ED4_find_species_name_terminal(name);
529
530        if (name_term) {
531            jump_to_corresponding_seq_terminal(name_term, true);
532        }
533        else {
534            aw_message(GBS_global_string("Species '%s' is not loaded - use GET to load it.", name));
535        }
536    }
537    else {
538        aw_message("Please select a species");
539    }
540}
541
542static bool multi_species_man_consensus_id_starts_with(ED4_base *base, const char *start) { // TRUE if consensus id starts with 'start'
543    ED4_multi_species_manager *ms_man    = base->to_multi_species_manager();
544    ED4_base                  *consensus = ms_man->search_spec_child_rek(LEV_SPECIES);
545
546    if (consensus) {
547        ED4_base *consensus_name = consensus->to_manager()->search_spec_child_rek(LEV_SPECIES_NAME);
548
549        if (consensus_name) {
550            if (strncmp(consensus_name->id, start, strlen(start))==0) {
551                ED4_multi_species_manager *cons_ms_man = consensus_name->get_parent(LEV_MULTI_SPECIES)->to_multi_species_manager();
552                return cons_ms_man==ms_man;
553            }
554        }
555    }
556
557    return false;
558}
559
560ED4_multi_species_manager *ED4_find_MoreSequences_manager() {
561    // returns manager into which new species should be inserted
562    ED4_base *manager = ED4_ROOT->root_group_man->find_first_that(LEV_MULTI_SPECIES, makeED4_basePredicate(multi_species_man_consensus_id_starts_with, "More Sequences"));
563    return manager ? manager->to_multi_species_manager() : NULp;
564}
565
566void ED4_init_notFoundMessage() {
567    not_found_counter = 0;
568    not_found_message = new GBS_strstruct(10000);
569}
570void ED4_finish_and_show_notFoundMessage() {
571    if (not_found_counter != 0) {
572        if (not_found_counter>MAX_SHOWN_MISSING_SPECIES) {
573            not_found_message->nprintf(70, "(skipped display of %zu more species)\n", not_found_counter-MAX_SHOWN_MISSING_SPECIES);
574        }
575        aw_message(not_found_message->get_data());
576        aw_message(GBS_global_string("Couldn't load %zu species:", not_found_counter));
577    }
578    delete not_found_message;
579    not_found_message = NULp;
580}
581
582static ED4_species_name_terminal *insert_new_species_terminal(GB_CSTR species_name, bool is_SAI) {
583    ED4_multi_species_manager *insert_into_manager = ED4_find_MoreSequences_manager();
584    ED4_group_manager         *group_man           = insert_into_manager->get_parent(LEV_GROUP)->to_group_manager();
585
586    ED4_init_notFoundMessage();
587    {
588        char *buffer = ARB_alloc<char>(strlen(species_name)+3);
589        sprintf(buffer, "-%c%s", is_SAI ? 'S' : 'L', species_name);
590
591        int index = 0;
592        EDB_root_bact::fill_species(insert_into_manager, ED4_ROOT->ref_terminals, buffer, &index, insert_into_manager->calc_group_depth(), NULp);
593        free(buffer);
594    }
595    ED4_finish_and_show_notFoundMessage();
596
597    {
598        GBDATA *gb_main = ED4_ROOT->get_gb_main();
599        GBDATA *gb_item = is_SAI ? GBT_find_SAI(gb_main, species_name) : GBT_find_species(gb_main, species_name);
600
601        if (gb_item) {
602            GBDATA *gbd = GBT_find_sequence(gb_item, ED4_ROOT->get_alignment_name());
603            if (gbd) {
604                char *data = GB_read_string(gbd); // @@@ NOT_ALL_SAI_HAVE_DATA
605                int   len  = GB_read_string_count(gbd);
606
607                group_man->update_bases(NULp, 0, data, len);
608            }
609        }
610    }
611
612    ED4_species_name_terminal *name_term = is_SAI
613        ? ED4_find_SAI_name_terminal(species_name)
614        : ED4_find_species_name_terminal(species_name);
615
616    if (name_term) {
617        // new AAseqTerminals should be created if it is in ProtView mode
618        if (ED4_ROOT->alignment_type == GB_AT_DNA && !is_SAI) {
619            PV_AddCorrespondingOrfTerminals(name_term);
620        }
621        ED4_ROOT->main_manager->request_resize(); // @@@ instead needs to be called whenever adding or deleting PV-terminals
622        // it should create new AA Sequence terminals if the protein viewer is enabled
623    }
624    insert_into_manager->invalidate_species_counters();
625
626    return name_term;
627}
628
629void ED4_get_and_jump_to_selected_SAI(AW_window *aww) {
630    const char *sai_name = aww->get_root()->awar(AWAR_SAI_NAME)->read_char_pntr();
631
632    if (sai_name && sai_name[0]) {
633        ED4_MostRecentWinContext   context;
634        GB_transaction             ta(ED4_ROOT->get_gb_main());
635        ED4_species_name_terminal *name_term = ED4_find_SAI_name_terminal(sai_name);
636        bool                       loaded    = false;
637
638        if (!name_term) {
639            name_term = insert_new_species_terminal(sai_name, true);
640            loaded    = true;
641        }
642        if (name_term) {
643            jump_to_corresponding_seq_terminal(name_term, true);
644            if (!loaded) aw_message(GBS_global_string("SAI '%s' is already loaded.", sai_name));
645        }
646        else {
647            aw_message(GBS_global_string("Failed to load SAI '%s'", sai_name));
648        }
649    }
650}
651
652void ED4_get_and_jump_to_species(GB_CSTR species_name) {
653    e4_assert(species_name && species_name[0]);
654
655    GB_transaction             ta(ED4_ROOT->get_gb_main());
656    ED4_species_name_terminal *name_term = ED4_find_species_name_terminal(species_name);
657    bool                       loaded    = false;
658
659    if (!name_term) { // insert new species
660        name_term = insert_new_species_terminal(species_name, false);
661        loaded    = true;
662    }
663    if (name_term) {
664        jump_to_corresponding_seq_terminal(name_term, true);
665        if (!loaded) aw_message(GBS_global_string("Species '%s' is already loaded.", species_name));
666    }
667    else {
668        aw_message(GBS_global_string("Failed to get species '%s'", species_name));
669    }
670}
671
672void ED4_get_and_jump_to_current(AW_window *aww) {
673    ED4_LocalWinContext  uses(aww);
674    char                *name = GBT_read_string(ED4_ROOT->get_gb_main(), AWAR_SPECIES_NAME);
675    if (name && name[0]) {
676        ED4_get_and_jump_to_species(name);
677    }
678    else {
679        aw_message("Please select a species");
680    }
681}
682
683void ED4_get_marked_from_menu(AW_window *) {
684#define BUFFERSIZE 1000
685    GBDATA         *gb_main = ED4_ROOT->get_gb_main();
686    GB_transaction  ta(gb_main);
687    long            marked  = GBT_count_marked_species(gb_main);
688
689    if (marked) {
690        GBDATA *gb_species = GBT_first_marked_species(gb_main);
691        char   *buffer     = new char[BUFFERSIZE+1];
692        char   *bp         = buffer;
693
694        ED4_multi_species_manager *insert_into_manager = ED4_find_MoreSequences_manager();
695        ED4_group_manager         *group_man           = insert_into_manager->get_parent(LEV_GROUP)->to_group_manager();
696
697        int group_depth = insert_into_manager->calc_group_depth();
698        int index       = 0;
699        int inserted    = 0;
700
701        const char *default_alignment = ED4_ROOT->get_alignment_name();
702
703        arb_progress progress("Loading species", marked);
704
705        ED4_init_notFoundMessage();
706
707        while (gb_species) {
708            const char *name = GBT_get_name_or_description(gb_species);
709            ED4_species_name_terminal *name_term = ED4_find_species_name_terminal(name);
710
711            if (!name_term) { // species not found -> insert
712                {
713                    int namelen = strlen(name);
714                    int buffree = BUFFERSIZE-int(bp-buffer);
715
716                    if ((namelen+2)>buffree) {
717                        *bp = 0;
718                        EDB_root_bact::fill_species(insert_into_manager, ED4_ROOT->ref_terminals, buffer, &index, group_depth, NULp);
719                        bp = buffer;
720                        index = 0;
721                    }
722
723                    *bp++ = 1;
724                    *bp++ = 'L';
725                    memcpy(bp, name, namelen);
726                    bp += namelen;
727                }
728
729                {
730                    GBDATA *gbd = GBT_find_sequence(gb_species, default_alignment);
731
732                    if (gbd) {
733                        char *data = GB_read_string(gbd);
734                        int len = GB_read_string_count(gbd);
735                        group_man->table().add(data, len);
736                    }
737                }
738
739                inserted++;
740            }
741            gb_species = GBT_next_marked_species(gb_species);
742            progress.inc();
743        }
744
745        if (bp>buffer) {
746            *bp++ = 0;
747            EDB_root_bact::fill_species(insert_into_manager, ED4_ROOT->ref_terminals, buffer, &index, group_depth, NULp);
748        }
749
750        aw_message(GBS_global_string("Loaded %i of %li marked species.", inserted, marked));
751
752        ED4_finish_and_show_notFoundMessage();
753
754        if (inserted) {
755            // new AAseqTerminals should be created if it is in ProtView mode
756            if (ED4_ROOT->alignment_type == GB_AT_DNA) {
757                PV_AddOrfTerminalsToLoadedSpecies();
758            }
759            ED4_ROOT->main_manager->request_resize(); // @@@ instead needs to be called whenever adding or deleting PV-terminals
760        }
761
762        delete [] buffer;
763    }
764    else {
765        aw_message("No species marked.");
766    }
767
768#undef BUFFERSIZE
769}
770
771ED4_returncode ED4_cursor::HideCursor() {
772    if (owner_of_cursor) {
773        if (is_partly_visible()) {
774            delete_cursor(cursor_abs_x, owner_of_cursor);
775        }
776        owner_of_cursor = NULp;
777    }
778
779    return ED4_R_OK;
780}
781
782void ED4_cursor::changeType(ED4_CursorType typ) {
783    if (owner_of_cursor) {
784        ED4_terminal *old_owner_of_cursor = owner_of_cursor;
785
786        HideCursor();
787        ctype = typ;
788        ED4_ROOT->aw_root->awar(ED4_AWAR_CURSOR_TYPE)->write_int(int(ctype));
789        owner_of_cursor = old_owner_of_cursor;
790        ShowCursor(0, ED4_C_NONE, 0);
791    }
792    else {
793        ctype = typ;
794    }
795}
796
797static void trace_termChange_in_global_awar(ED4_terminal *term, char*& last_value, bool& ignore_flag, const char *awar_name) {
798    char *species_name = term->get_name_of_species();
799
800    if (!last_value || strcmp(last_value, species_name) != 0) {
801        freeset(last_value, species_name);
802        LocallyModify<bool> raise(ignore_flag, true);
803#if defined(TRACE_JUMPS)
804        fprintf(stderr, "Writing '%s' to awar '%s'\n", species_name, awar_name);
805#endif
806        GBT_write_string(ED4_ROOT->get_gb_main(), awar_name, species_name);
807    }
808    else {
809        free(species_name);
810    }
811}
812
813void ED4_cursor::updateAwars(bool new_term_selected) {
814    AW_root *aw_root = ED4_ROOT->aw_root;
815    int      seq_pos = get_sequence_pos();
816
817    if (allow_update_global_cursorpos && new_term_selected) {
818        // @@@ last_set_XXX has to be window-specific (or better cursor specific)
819        if (in_SAI_terminal()) {
820            static char *last_set_SAI = NULp;
821            trace_termChange_in_global_awar(owner_of_cursor, last_set_SAI, ignore_selected_SAI_changes_cb, AWAR_SAI_NAME);
822        }
823        else if (in_species_seq_terminal()) {
824            static char *last_set_species = NULp;
825            trace_termChange_in_global_awar(owner_of_cursor, last_set_species, ignore_selected_species_changes_cb, AWAR_SPECIES_NAME);
826        }
827    }
828    if (new_term_selected) ED4_viewDifferences_announceTerminalChange();
829
830    // update awars for cursor position:
831    aw_root->awar(win->awar_path_for_cursor)->write_int(info2bio(seq_pos));
832    if (allow_update_global_cursorpos) {
833        aw_root->awar(AWAR_CURSOR_POSITION)->write_int(info2bio(seq_pos)); // update ARB-global cursor position
834    }
835
836    // look if we have a commented search result under the cursor:
837
838    if (owner_of_cursor && owner_of_cursor->is_sequence_terminal()) {
839        ED4_sequence_terminal *seq_term = owner_of_cursor->to_sequence_terminal();
840        ED4_SearchResults     &results  = seq_term->results();
841        ED4_SearchPosition    *pos      = results.get_shown_at(seq_pos);
842
843        if (pos) {
844            GB_CSTR comment = pos->get_comment();
845
846            if (comment) {
847                char *buffer = GB_give_buffer(strlen(comment)+30);
848
849                sprintf(buffer, "%s: %s", ED4_SearchPositionTypeId[pos->get_whatsFound()], comment);
850                aw_message(buffer);
851            }
852        }
853    }
854
855    // update awar for ecoli position:
856    BI_ecoli_ref *ecoli = ED4_ROOT->ecoli_ref;
857    if (ecoli->gotData()) {
858        int ecoli_pos = ecoli->abs_2_rel(seq_pos+1); // inclusive position behind cursor
859        aw_root->awar(win->awar_path_for_Ecoli)->write_int(ecoli_pos);
860    }
861
862    // update awar for base position:
863    int base_pos = base_position.get_base_position(owner_of_cursor, seq_pos+1); // inclusive position behind cursor
864    aw_root->awar(win->awar_path_for_basePos)->write_int(base_pos);
865
866    // update awar for IUPAC:
867
868#define MAXIUPAC 6
869
870    char iupac[MAXIUPAC+1];
871    strcpy(iupac, ED4_IUPAC_EMPTY);
872
873    {
874        char at[2] = "\0";
875
876        if (in_consensus_terminal()) {
877            ED4_group_manager *group_manager = owner_of_cursor->get_parent(LEV_GROUP)->to_group_manager();
878            BaseFrequencies&   groupTab      = group_manager->table();
879            if (seq_pos<groupTab.size()) {
880                groupTab.build_consensus_string_to(at, ExplicitRange(seq_pos, seq_pos), ED4_ROOT->get_consensus_params());
881            }
882        }
883        else if (in_species_seq_terminal() || in_SAI_terminal()) {
884            int         len;
885            const char *seq = owner_of_cursor->resolve_pointer_to_char_pntr(&len);
886
887            if (seq_pos<len) at[0] = seq[seq_pos];
888        }
889
890        if (at[0]) {
891            char        base = at[0];
892            const char *i    = iupac::decode(base, ED4_ROOT->alignment_type, aw_root->awar(ED4_AWAR_CONSENSUS_GROUP)->read_int());
893
894            e4_assert(strlen(i)<=MAXIUPAC);
895            strcpy(iupac, i);
896        }
897    }
898
899#undef MAXIUPAC
900
901    aw_root->awar(win->awar_path_for_IUPAC)->write_string(iupac);
902
903    // update awar for helix#:
904    const char *helixNr = ED4_ROOT->helix->helixNr(seq_pos);
905    aw_root->awar(win->awar_path_for_helixNr)->write_string(null2empty(helixNr));
906}
907
908int ED4_cursor::get_screen_relative_pos() const {
909    const ED4_coords& coords = window()->coords;
910    return cursor_abs_x - coords.window_left_clip_point;
911}
912void ED4_cursor::set_screen_relative_pos(int scroll_to_relpos) {
913    int curr_rel_pos  = get_screen_relative_pos();
914    int scroll_amount = curr_rel_pos-scroll_to_relpos;
915
916    int length_of_char = ED4_ROOT->font_group.get_width(ED4_G_SEQUENCES);
917    scroll_amount      = (scroll_amount/length_of_char)*length_of_char; // align to char-size
918
919    if (scroll_amount != 0) {
920        AW_window *aww = window()->aww;
921        aww->set_horizontal_scrollbar_position(aww->slider_pos_horizontal + scroll_amount);
922#if defined(TRACE_JUMPS)
923        printf("set_screen_relative_pos(%i) auto-scrolls %i\n", scroll_to_relpos, scroll_amount);
924#endif
925        ED4_horizontal_change_cb(aww);
926    }
927}
928
929
930void ED4_cursor::jump_screen_pos(int screen_pos, ED4_CursorJumpType jump_type) {
931    if (!owner_of_cursor) {
932        aw_message("First you have to place the cursor");
933        return;
934    }
935
936    if (owner_of_cursor->is_hidden()) return; // do not jump if cursor terminal is hidden
937
938    AW_pos terminal_x, terminal_y;
939    owner_of_cursor->calc_world_coords(&terminal_x, &terminal_y);
940
941#if defined(TRACE_JUMPS)
942    printf("jump_screen_pos(%i)\n", screen_pos);
943#endif
944
945    ED4_terminal *term = owner_of_cursor;
946    ED4_window   *ed4w = window();
947
948    term->scroll_into_view(ed4w); // correct y-position of terminal
949
950    int cursor_diff = screen_pos-screen_position;
951    if (cursor_diff == 0) { // cursor position did not change
952        if (jump_type == ED4_JUMP_KEEP_VISIBLE) return; // nothing special -> done
953    }
954
955    int terminal_pixel_length = ed4w->get_device()->get_string_size(ED4_G_SEQUENCES, owner_of_cursor->to_text_terminal()->get_length());
956    int length_of_char        = ED4_ROOT->font_group.get_width(ED4_G_SEQUENCES);
957    int abs_x_new             = cursor_abs_x+cursor_diff*length_of_char; // position in terminal
958
959    if (abs_x_new > terminal_x+terminal_pixel_length+CHARACTEROFFSET || abs_x_new < terminal_x+CHARACTEROFFSET) {
960        return; // don`t move out of terminal
961    }
962
963    ED4_coords *coords = &ed4w->coords;
964
965    int screen_width  = coords->window_right_clip_point-coords->window_left_clip_point;
966    int scroll_new_to = -1;     // if >0 -> scroll abs_x_new to this screen-relative position
967
968    if (jump_type != ED4_JUMP_KEEP_VISIBLE) {
969        int rel_x = cursor_abs_x-coords->window_left_clip_point;
970
971        if (jump_type == ED4_JUMP_KEEP_POSITION) {
972            bool was_in_screen = rel_x >= 0 && rel_x <= screen_width;
973            if (!was_in_screen) {
974                jump_type = ED4_JUMP_KEEP_VISIBLE; // // don't have useful relative position -> scroll
975            }
976        }
977
978        switch (jump_type) {
979            case ED4_JUMP_CENTERED:             scroll_new_to = screen_width/2;         break;
980            case ED4_JUMP_KEEP_POSITION:        scroll_new_to = rel_x;                  break;
981            case ED4_JUMP_KEEP_VISIBLE:         break; // handled below
982            default: e4_assert(0); break;
983        }
984    }
985
986    if (jump_type == ED4_JUMP_KEEP_VISIBLE) {
987        int margin = length_of_char * ED4_ROOT->aw_root->awar(ED4_AWAR_SCROLL_MARGIN)->read_int();
988
989        int right_margin = coords->window_right_clip_point - margin;
990        int left_margin  = coords->window_left_clip_point + margin;
991
992        if (left_margin >= right_margin)    scroll_new_to = screen_width/2; // margins too big -> center
993        else if (abs_x_new > right_margin)  scroll_new_to = screen_width-margin;
994        else if (abs_x_new < left_margin)   scroll_new_to = margin;
995    }
996
997    delete_cursor(cursor_abs_x, owner_of_cursor);
998
999    if (scroll_new_to >= 0) {   // scroll
1000        int rel_x_new     = abs_x_new-coords->window_left_clip_point;
1001        int scroll_amount = rel_x_new-scroll_new_to;
1002
1003        if      (scroll_amount>0) scroll_amount += length_of_char/2;
1004        else if (scroll_amount<0) scroll_amount -= length_of_char/2;
1005
1006        scroll_amount = (scroll_amount/length_of_char)*length_of_char; // align to char-size
1007        if (scroll_amount != 0) {
1008            AW_window *aww  = ed4w->aww;
1009            aww->set_horizontal_scrollbar_position(aww->slider_pos_horizontal + scroll_amount);
1010#if defined(TRACE_JUMPS)
1011            printf("jump_screen_pos auto-scrolls %i\n", scroll_amount);
1012#endif
1013            LocallyModify<bool> flag(allowed_to_draw, false);
1014            ED4_horizontal_change_cb(aww);
1015        }
1016    }
1017
1018    LocallyModify<bool> flag(allowed_to_draw, true);
1019    if (cursor_diff >= 0) {
1020        ShowCursor(cursor_diff*length_of_char, ED4_C_RIGHT, abs(cursor_diff));
1021    }
1022    else {
1023        ShowCursor(cursor_diff*length_of_char, ED4_C_LEFT, abs(cursor_diff));
1024    }
1025#if defined(ASSERTION_USED)
1026    {
1027        int sp = get_screen_pos();
1028        e4_assert(sp == screen_pos);
1029    }
1030#endif
1031}
1032
1033void ED4_cursor::jump_sequence_pos(int seq_pos, ED4_CursorJumpType jump_type) {
1034    ED4_remap *remap = ED4_ROOT->root_group_man->remap();
1035
1036    e4_assert(!remap->compile_needed());
1037
1038    if (remap->is_shown(seq_pos)) {
1039        int screen_pos = remap->sequence_to_screen(seq_pos);
1040        jump_screen_pos(screen_pos, jump_type);
1041#if defined(ASSERTION_USED)
1042        if (owner_of_cursor) {
1043            int res_seq_pos = get_sequence_pos();
1044            e4_assert(res_seq_pos == seq_pos);
1045        }
1046#endif
1047    }
1048    else {
1049        int scr_left, scr_right;
1050        remap->adjacent_screen_positions(seq_pos, scr_left, scr_right);
1051        jump_screen_pos(scr_right>=0 ? scr_right : scr_left, jump_type);
1052    }
1053}
1054
1055void ED4_cursor::jump_base_pos(int base_pos, ED4_CursorJumpType jump_type) {
1056    int seq_pos = base2sequence_position(base_pos);
1057    jump_sequence_pos(seq_pos, jump_type);
1058
1059#if defined(ASSERTION_USED)
1060    if (owner_of_cursor) {
1061        int res_base_pos = get_base_position();
1062        e4_assert(res_base_pos == base_pos);
1063    }
1064#endif
1065}
1066
1067class has_base_at : public ED4_TerminalPredicate {
1068    int  seq_pos;
1069    bool want_base;
1070public:
1071    has_base_at(int seq_pos_, bool want_base_) : seq_pos(seq_pos_), want_base(want_base_) {}
1072    bool fulfilled_by(const ED4_terminal *terminal) const OVERRIDE {
1073        bool test_succeeded = false;
1074
1075        if (terminal->is_sequence_terminal()) {
1076            const ED4_sequence_terminal *seqTerm = terminal->to_sequence_terminal();
1077            int len;
1078            char *seq = seqTerm->resolve_pointer_to_string_copy(&len);
1079            if (seq) {
1080                test_succeeded = len>seq_pos && bool(ED4_is_gap_character(seq[seq_pos]))!=want_base;
1081            }
1082            free(seq);
1083        }
1084
1085        return test_succeeded;
1086    }
1087};
1088
1089struct acceptAnyTerminal : public ED4_TerminalPredicate {
1090    bool fulfilled_by(const ED4_terminal *) const OVERRIDE { return true; }
1091};
1092
1093static ED4_terminal *get_upper_lower_cursor_pos(ED4_manager *starting_point, ED4_cursor_move cursor_move, AW_pos current_y, bool isScreen, const ED4_TerminalPredicate& predicate) {
1094    // current_y is y-position of terminal at which search starts.
1095    // It may be in world or screen coordinates (isScreen marks which is used)
1096    // This is needed to move the cursor from top- to middle-area w/o scrolling middle-area to top-position.
1097
1098    ED4_terminal *result = NULp;
1099
1100    int m      = 0;
1101    int last_m = starting_point->members()-1;
1102    int incr   = 1;
1103
1104    if (cursor_move == ED4_C_UP) {
1105        std::swap(m, last_m); incr = -1; // revert search direction
1106        e4_assert(!isScreen);            // use screen coordinates for ED4_C_DOWN only!
1107    }
1108
1109    while (!result) {
1110        ED4_base *member = starting_point->member(m);
1111
1112        if (member->is_manager()) {
1113            if (!member->flag.hidden) { // step over hidden managers (e.g. folded groups)
1114                result = get_upper_lower_cursor_pos(member->to_manager(), cursor_move, current_y, isScreen, predicate);
1115            }
1116        }
1117        else {
1118            if (member->has_property(PROP_CURSOR_ALLOWED)) {
1119                AW_pos x, y;
1120                member->calc_world_coords(&x, &y);
1121                if (isScreen) current_ed4w()->world_to_win_coords(&x, &y); // if current_y is screen, convert x/y to screen-coordinates as well
1122
1123                bool pos_beyond = (cursor_move == ED4_C_UP) ? y<current_y : y>current_y;
1124                if (pos_beyond) {
1125                    bool skip_top_scrolled = false;
1126                    if (isScreen) {
1127                        ED4_multi_species_manager *marea_man = NULp;
1128                        if (member->get_area_level(&marea_man) == ED4_A_MIDDLE_AREA) {
1129                            // previous position was in top-area -> avoid selecting scrolled-out terminals
1130                            AW_pos y_area     = marea_man->parent->extension.position[Y_POS];
1131                            skip_top_scrolled = y<y_area;
1132                        }
1133                    }
1134
1135                    if (!skip_top_scrolled) {
1136                        ED4_terminal *term = member->to_terminal();
1137                        if (predicate.fulfilled_by(term)) result = term;
1138                    }
1139                }
1140            }
1141        }
1142
1143        if (m == last_m) break;
1144        m += incr;
1145    }
1146
1147    return result;
1148}
1149
1150struct acceptConsensusTerminal : public ED4_TerminalPredicate {
1151    bool fulfilled_by(const ED4_terminal *term) const OVERRIDE { return term->is_consensus_terminal(); }
1152};
1153
1154ED4_returncode ED4_cursor::move_cursor(AW_event *event) {
1155    // move cursor up down
1156    ED4_cursor_move dir     = ED4_C_NONE;
1157    ED4_returncode  result  = ED4_R_OK;
1158    bool            endHome = false;
1159
1160    switch (event->keycode) {
1161        case AW_KEY_UP:   dir = ED4_C_UP;   break;
1162        case AW_KEY_DOWN: dir = ED4_C_DOWN; break;
1163        case AW_KEY_HOME: dir = ED4_C_UP;   endHome = true; break;
1164        case AW_KEY_END:  dir = ED4_C_DOWN; endHome = true; break;
1165        default: e4_assert(0); break; // illegal call of move_cursor()
1166    }
1167
1168    if (dir != ED4_C_NONE) {
1169        if (owner_of_cursor->is_hidden()) result = ED4_R_IMPOSSIBLE; // don't move cursor if terminal is hidden
1170
1171        if (result == ED4_R_OK) {
1172            AW_pos x_dummy, y_world;
1173
1174            owner_of_cursor->calc_world_coords(&x_dummy, &y_world);
1175
1176            int           seq_pos         = get_sequence_pos();
1177            ED4_terminal *target_terminal = NULp;
1178
1179            // stay in current area
1180            ED4_multi_species_manager *start_at_manager = NULp;
1181            ED4_AREA_LEVEL             area_level       = owner_of_cursor->get_area_level(&start_at_manager);
1182
1183            if (event->keymodifier & AW_KEYMODE_CONTROL) {
1184                bool has_base = has_base_at(seq_pos, true).fulfilled_by(owner_of_cursor);
1185
1186                if (!endHome) { // not End or Home
1187                    target_terminal = get_upper_lower_cursor_pos(start_at_manager, dir, y_world, false, has_base_at(seq_pos, !has_base));
1188                    if (target_terminal && !has_base && ED4_ROOT->aw_root->awar(ED4_AWAR_FAST_CURSOR_JUMP)->read_int()) {  // if jump_over group
1189                        target_terminal->calc_world_coords(&x_dummy, &y_world);
1190                        target_terminal = get_upper_lower_cursor_pos(start_at_manager, dir, y_world, false, has_base_at(seq_pos, false));
1191                    }
1192                }
1193
1194                if (!target_terminal) {
1195                    // either already in last group (or no space behind last group) -> jump to end (or start)
1196                    target_terminal = get_upper_lower_cursor_pos(start_at_manager,
1197                                                                 dir == ED4_C_UP ? ED4_C_DOWN : ED4_C_UP, // use opposite movement direction
1198                                                                 dir == ED4_C_UP ? 0 : INT_MAX, false, // search for top-/bottom-most terminal
1199                                                                 acceptAnyTerminal());
1200                }
1201            }
1202            else {
1203                e4_assert(!endHome); // END and HOME w/o Ctrl should not call move_cursor()
1204                if (event->keymodifier & AW_KEYMODE_ALT) {
1205                    target_terminal = get_upper_lower_cursor_pos(start_at_manager, dir, y_world, false, acceptConsensusTerminal());
1206                }
1207                else {
1208                    bool isScreen = false;
1209                    if (dir == ED4_C_DOWN) {
1210                        if (area_level == ED4_A_TOP_AREA) {
1211                            window()->world_to_win_coords(&x_dummy, &y_world); // special handling to move cursor from top to bottom area
1212                            isScreen = true;
1213                        }
1214                    }
1215                    target_terminal = get_upper_lower_cursor_pos(ED4_ROOT->main_manager, dir, y_world, isScreen, acceptAnyTerminal());
1216                }
1217            }
1218
1219            if (target_terminal) {
1220                set_to_terminal(target_terminal, seq_pos, ED4_JUMP_KEEP_VISIBLE);
1221            }
1222        }
1223    }
1224
1225    return result;
1226}
1227
1228void ED4_cursor::set_abs_x() {
1229    AW_pos x, y;
1230    owner_of_cursor->calc_world_coords(&x, &y);
1231    cursor_abs_x = int(get_sequence_pos()*ED4_ROOT->font_group.get_width(ED4_G_SEQUENCES) + CHARACTEROFFSET + x);
1232}
1233
1234
1235ED4_returncode ED4_cursor::ShowCursor(ED4_index offset_x, ED4_cursor_move move, int move_pos) {
1236    AW_pos x=0, y=0, x_help = 0, y_help;
1237
1238    owner_of_cursor->calc_world_coords(&x, &y);
1239
1240    switch (move) {
1241        case ED4_C_RIGHT: screen_position += move_pos; break;
1242        case ED4_C_LEFT:  screen_position -= move_pos; break;
1243        case ED4_C_NONE: break; // no move - only redisplay
1244        default: e4_assert(0); break;
1245    }
1246
1247    {
1248        LocallyModify<bool> flag(allow_update_global_cursorpos, allow_update_global_cursorpos && move != ED4_C_NONE);
1249        updateAwars(false);
1250    }
1251
1252    x_help = cursor_abs_x + offset_x;
1253    y_help = y;
1254
1255    window()->world_to_win_coords(&x_help, &y_help);
1256
1257    if (allowed_to_draw) draw_cursor(x_help, y_help);
1258#if defined(DEBUG) && 0
1259    else printf("Skip draw_cursor (allowed_to_draw=false)\n");
1260#endif // DEBUG
1261
1262    cursor_abs_x += offset_x;
1263
1264    return ED4_R_OK;
1265}
1266
1267bool ED4_cursor::is_hidden_inside_group() const {
1268    if (!owner_of_cursor) return false;
1269    if (!owner_of_cursor->is_in_folded_group()) return false;
1270    if (in_consensus_terminal()) {
1271        ED4_base *group_man = owner_of_cursor->get_parent(LEV_GROUP);
1272        e4_assert(group_man);
1273        return group_man->is_in_folded_group();
1274    }
1275    return true;
1276}
1277
1278bool ED4_cursor::is_partly_visible() const {
1279    e4_assert(owner_of_cursor);
1280    e4_assert(cursor_shape); // cursor is not drawn, cannot test visibility
1281
1282    if (is_hidden_inside_group()) {
1283        printf("is_hidden_inside_group=true\n");
1284        return false;
1285    }
1286
1287    AW_pos x, y;
1288    owner_of_cursor->calc_world_coords(&x, &y);
1289
1290    int x1, y1, x2, y2;
1291    cursor_shape->get_bounding_box(cursor_abs_x, int(y), x1, y1, x2, y2);
1292
1293    bool visible = false;
1294
1295    switch (owner_of_cursor->get_area_level(NULp)) {
1296        case ED4_A_TOP_AREA:    visible = win->shows_xpos(x1) || win->shows_xpos(x2); break;
1297        case ED4_A_MIDDLE_AREA: visible = win->partly_shows(x1, y1, x2, y2); break;
1298        default: break;
1299    }
1300
1301    return visible;
1302}
1303
1304bool ED4_cursor::is_completely_visible() const {
1305    e4_assert(owner_of_cursor);
1306    e4_assert(cursor_shape); // cursor is not drawn, cannot test visibility
1307
1308    if (is_hidden_inside_group()) return false;
1309
1310    AW_pos x, y;
1311    owner_of_cursor->calc_world_coords(&x, &y);
1312
1313    int x1, y1, x2, y2;
1314    cursor_shape->get_bounding_box(cursor_abs_x, int(y), x1, y1, x2, y2);
1315
1316    bool visible = false;
1317
1318    switch (owner_of_cursor->get_area_level(NULp)) {
1319        case ED4_A_TOP_AREA:    visible = win->shows_xpos(x1) && win->shows_xpos(x2); break;
1320        case ED4_A_MIDDLE_AREA: visible = win->completely_shows(x1, y1, x2, y2); break;
1321        default: break;
1322    }
1323
1324    return visible;
1325}
1326
1327#if defined(DEBUG) && 0
1328#define DUMP_SCROLL_INTO_VIEW
1329#endif
1330
1331void ED4_terminal::scroll_into_view(ED4_window *ed4w) { // scroll y-position only
1332    ED4_LocalWinContext uses(ed4w);
1333
1334    AW_pos termw_x, termw_y;
1335    calc_world_coords(&termw_x, &termw_y);
1336
1337    ED4_coords *coords  = &current_ed4w()->coords;
1338
1339    int term_height = int(extension.size[1]);
1340    int win_ysize   = coords->window_lower_clip_point - coords->window_upper_clip_point + 1;
1341
1342    bool scroll = false;
1343    int  slider_pos_y;
1344
1345    ED4_cursor_move direction = ED4_C_NONE;
1346
1347    AW_pos termw_y_upper = termw_y; // upper border of terminal
1348    AW_pos termw_y_lower = termw_y + term_height; // lower border of terminal
1349
1350    if (termw_y_upper > coords->top_area_height) { // don't scroll if terminal is in top area (always visible)
1351        if (termw_y_upper < coords->window_upper_clip_point) { // scroll up
1352#ifdef DUMP_SCROLL_INTO_VIEW
1353            printf("termw_y_upper(%i) < window_upper_clip_point(%i)\n",
1354                   int(termw_y_upper), int(coords->window_upper_clip_point));
1355#endif // DEBUG
1356            slider_pos_y = int(termw_y_upper - coords->top_area_height - term_height);
1357            scroll       = true;
1358            direction    = ED4_C_UP;
1359        }
1360        else if (termw_y_lower > coords->window_lower_clip_point) { // scroll down
1361#ifdef DUMP_SCROLL_INTO_VIEW
1362            printf("termw_y_lower(%i) > window_lower_clip_point(%i)\n",
1363                   int(termw_y_lower), int(coords->window_lower_clip_point));
1364#endif // DEBUG
1365            slider_pos_y = int(termw_y_upper - coords->top_area_height - win_ysize);
1366            scroll       = true;
1367            direction    = ED4_C_DOWN;
1368        }
1369    }
1370
1371#ifdef DUMP_SCROLL_INTO_VIEW
1372    if (!scroll) {
1373        printf("No scroll needed (termw_y_upper=%i termw_y_lower=%i term_height=%i window_upper_clip_point=%i window_lower_clip_point=%i)\n",
1374               int(termw_y_upper), int(termw_y_lower), term_height,
1375               int(coords->window_upper_clip_point), int(coords->window_lower_clip_point));
1376    }
1377#endif // DEBUG
1378
1379    if (scroll) {
1380        AW_window *aww = ed4w->aww;
1381
1382        int pic_ysize         = int(aww->get_scrolled_picture_height());
1383        int slider_pos_yrange = pic_ysize - win_ysize;
1384
1385        if (slider_pos_yrange<0) { // win_ysize > pic_ysize
1386            slider_pos_y = 0;
1387        }
1388        else {
1389            ED4_multi_species_manager *start_at_manager = NULp;
1390            get_area_level(&start_at_manager);
1391
1392            ED4_terminal *nextTerm = get_upper_lower_cursor_pos(start_at_manager, direction, termw_y, false, acceptAnyTerminal());
1393            if (!nextTerm) { // no next term in this area
1394                slider_pos_y = direction == ED4_C_UP ? 0 : slider_pos_yrange; // scroll to limit
1395            }
1396        }
1397
1398        if (slider_pos_y>slider_pos_yrange) slider_pos_y = slider_pos_yrange;
1399        if (slider_pos_y<0) slider_pos_y                 = 0;
1400
1401        aww->set_vertical_scrollbar_position(slider_pos_y);
1402        ED4_scrollbar_change_cb(aww);
1403    }
1404}
1405
1406void ED4_cursor::set_to_terminal(ED4_terminal *terminal, int seq_pos, ED4_CursorJumpType jump_type) {
1407    if (seq_pos == -1) seq_pos = get_sequence_pos();
1408
1409    bool new_term_selected = owner_of_cursor != terminal;
1410    if (new_term_selected) {
1411        if (owner_of_cursor) {
1412            if (get_sequence_pos() != seq_pos) {
1413                jump_sequence_pos(seq_pos, jump_type); // position to wanted column -- scrolls horizontally
1414            }
1415        }
1416
1417        int scr_pos = ED4_ROOT->root_group_man->remap()->sequence_to_screen(seq_pos);
1418        show_cursor_at(terminal, scr_pos);
1419
1420        if (!is_completely_visible()) {
1421            jump_sequence_pos(seq_pos, jump_type);
1422        }
1423    }
1424    else {
1425        jump_sequence_pos(seq_pos, jump_type);
1426    }
1427
1428    GB_transaction ta(ED4_ROOT->get_gb_main());
1429    updateAwars(new_term_selected);
1430}
1431
1432ED4_returncode ED4_cursor::show_cursor_at(ED4_terminal *target_terminal, ED4_index scr_pos) {
1433    bool new_term_selected = owner_of_cursor != target_terminal;
1434
1435    if (owner_of_cursor) {
1436        if (is_partly_visible()) {
1437            delete_cursor(cursor_abs_x, owner_of_cursor);
1438        }
1439        owner_of_cursor = NULp;
1440        DRAW = 1;
1441    }
1442
1443    target_terminal->scroll_into_view(window());
1444
1445    AW_pos termw_x, termw_y;
1446    target_terminal->calc_world_coords(&termw_x, &termw_y);
1447
1448    screen_position = scr_pos;
1449
1450    int length_of_char = ED4_ROOT->font_group.get_width(ED4_G_SEQUENCES);
1451
1452    AW_pos world_x = termw_x + length_of_char*screen_position + CHARACTEROFFSET;
1453    AW_pos world_y = termw_y;
1454
1455    AW_pos win_x = world_x;
1456    AW_pos win_y = world_y;
1457    window()->world_to_win_coords(&win_x, &win_y);
1458
1459    cursor_abs_x = (long int)world_x;
1460    owner_of_cursor = target_terminal;
1461
1462    draw_cursor(win_x, win_y);
1463
1464    GB_transaction ta(ED4_ROOT->get_gb_main());
1465    updateAwars(new_term_selected);
1466
1467    return ED4_R_OK;
1468}
1469
1470ED4_returncode ED4_cursor::show_clicked_cursor(AW_pos click_xpos, ED4_terminal *target_terminal) {
1471    AW_pos termw_x, termw_y;
1472    target_terminal->calc_world_coords(&termw_x, &termw_y);
1473
1474    ED4_index scr_pos = ED4_ROOT->pixel2pos(click_xpos - termw_x);
1475    return show_cursor_at(target_terminal, scr_pos);
1476}
1477
1478
1479/* --------------------------------------------------------------------------------
1480   ED4_base_position
1481   -------------------------------------------------------------------------------- */
1482
1483static void ed4_bp_sequence_changed_cb(ED4_species_manager*, ED4_base_position *base_pos) {
1484    base_pos->invalidate();
1485}
1486
1487void ED4_base_position::remove_changed_cb() {
1488    if (calced4term) {
1489        ED4_species_manager *species_manager = calced4term->get_parent(LEV_SPECIES)->to_species_manager();
1490        species_manager->remove_sequence_changed_cb(makeED4_species_managerCallback(ed4_bp_sequence_changed_cb, this));
1491
1492        calced4term = NULp;
1493    }
1494}
1495
1496static bool is_consensus_gap(char c) { return ED4_is_gap_character(c) || c == '='; }
1497
1498void ED4_base_position::calc4term(const ED4_terminal *base) {
1499    e4_assert(base);
1500
1501    ED4_species_manager *species_manager = base->get_parent(LEV_SPECIES)->to_species_manager();
1502
1503    int   len;
1504    char *seq;
1505
1506    if (base != calced4term) { // terminal changes => rebind callback to new manager
1507        remove_changed_cb();
1508        species_manager->add_sequence_changed_cb(makeED4_species_managerCallback(ed4_bp_sequence_changed_cb, this));
1509    }
1510
1511    bool (*isGap_fun)(char);
1512    if (species_manager->is_consensus_manager()) {
1513        ED4_group_manager *group_manager = base->get_parent(LEV_GROUP)->to_group_manager();
1514
1515        seq       = group_manager->build_consensus_string();
1516        len       = strlen(seq);
1517        isGap_fun = is_consensus_gap;
1518    }
1519    else {
1520        seq = base->resolve_pointer_to_string_copy(&len);
1521        e4_assert((int)strlen(seq) == len);
1522        isGap_fun = ED4_is_gap_character;
1523    }
1524
1525    e4_assert(seq);
1526
1527    CharPredicate pred_is_gap(isGap_fun);
1528    initialize(seq, len, pred_is_gap);
1529    calced4term = base;
1530
1531    free(seq);
1532}
1533int ED4_base_position::get_base_position(const ED4_terminal *term, int sequence_position) {
1534    if (!term) return 0;
1535    set_term(term);
1536    return abs_2_rel(sequence_position);
1537}
1538int ED4_base_position::get_sequence_position(const ED4_terminal *term, int base_pos) {
1539    if (!term) return 0;
1540    set_term(term);
1541    return rel_2_abs(base_pos);
1542}
1543
1544/* --------------------------------------------------------------------------------
1545   Store/Restore Cursorpositions
1546   -------------------------------------------------------------------------------- */
1547
1548class CursorPos : virtual Noncopyable {
1549    ED4_terminal *terminal;
1550    int seq_pos;
1551
1552    CursorPos *next;
1553
1554    static CursorPos *head;
1555
1556public:
1557
1558    static void clear() {
1559        while (head) {
1560            CursorPos *p = head->next;
1561
1562            delete head;
1563            head = p;
1564        }
1565    }
1566    static CursorPos *get_head() { return head; }
1567
1568    CursorPos(ED4_terminal *t, int p) {
1569        terminal = t;
1570        seq_pos = p;
1571        next = head;
1572        head = this;
1573    }
1574    ~CursorPos() {}
1575
1576    ED4_terminal *get_terminal() const { return terminal; }
1577    int get_seq_pos() const { return seq_pos; }
1578
1579    void moveToEnd() {
1580        e4_assert(this==head);
1581
1582        if (next) {
1583            CursorPos *p = head = next;
1584
1585            while (p->next) {
1586                p = p->next;
1587            }
1588
1589            p->next = this;
1590            this->next = NULp;
1591        }
1592    }
1593};
1594
1595CursorPos *CursorPos::head = NULp;
1596
1597void ED4_store_curpos(AW_window *aww) {
1598    GB_transaction       ta(ED4_ROOT->get_gb_main());
1599    ED4_LocalWinContext  uses(aww);
1600    ED4_cursor          *cursor = &current_cursor();
1601
1602    if (!cursor->owner_of_cursor) {
1603        aw_message("First you have to place the cursor.");
1604    }
1605    else {
1606        new CursorPos(cursor->owner_of_cursor, cursor->get_sequence_pos());
1607    }
1608}
1609
1610void ED4_restore_curpos(AW_window *aww) {
1611    GB_transaction       ta(ED4_ROOT->get_gb_main());
1612    ED4_LocalWinContext  uses(aww);
1613    ED4_cursor          *cursor = &current_cursor();
1614
1615    CursorPos *pos = CursorPos::get_head();
1616    if (!pos) {
1617        aw_message("No cursor position stored.");
1618        return;
1619    }
1620
1621    pos->get_terminal()->setCursorTo(cursor, pos->get_seq_pos(), true, ED4_JUMP_KEEP_VISIBLE);
1622    pos->moveToEnd();
1623}
1624
1625void ED4_clear_stored_curpos() {
1626    CursorPos::clear();
1627}
1628
1629/* --------------------------------------------------------------------------------
1630   Other stuff
1631   -------------------------------------------------------------------------------- */
1632
1633void ED4_helix_jump_opposite(AW_window *aww) {
1634    GB_transaction       ta(ED4_ROOT->get_gb_main());
1635    ED4_LocalWinContext  uses(aww);
1636    ED4_cursor          *cursor = &current_cursor();
1637
1638    if (!cursor->owner_of_cursor) {
1639        aw_message("First you have to place the cursor.");
1640        return;
1641    }
1642
1643    int       seq_pos = cursor->get_sequence_pos();
1644    AW_helix *helix   = ED4_ROOT->helix;
1645
1646    if (helix->is_pairpos(seq_pos)) {
1647        int pairing_pos = helix->opposite_position(seq_pos);
1648        cursor->jump_sequence_pos(pairing_pos, ED4_JUMP_KEEP_POSITION);
1649    }
1650    else {
1651        aw_message("Not at helix position");
1652    }
1653}
1654
1655void ED4_change_cursor(AW_window *aww) {
1656    ED4_LocalWinContext uses(aww);
1657    ED4_cursor     *cursor = &current_cursor();
1658    ED4_CursorType  typ    = cursor->getType();
1659
1660    cursor->changeType((ED4_CursorType)((typ+1)%ED4_CURSOR_TYPES));
1661}
1662
1663// --------------------------------------------------------------------------------
1664
1665#ifdef UNIT_TESTS
1666#include <test_unit.h>
1667#include <test_helpers.h>
1668
1669struct test_absrel {
1670    bool torel;
1671    test_absrel(bool r) : torel(r) {}
1672    virtual ~test_absrel() {}
1673
1674    virtual int a2r(int a) const = 0;
1675    virtual int r2a(int r) const = 0;
1676
1677    virtual int abs_size() const = 0;
1678    virtual int rel_size() const = 0;
1679
1680    int gen(int i) const { return torel ? a2r(i) : r2a(i); }
1681    int get_size() const { return torel ? abs_size()+1 : rel_size(); }
1682
1683    char *genResult() const;
1684};
1685
1686struct membind {
1687    const test_absrel& me;
1688    membind(const test_absrel& ta) : me(ta) {}
1689    int operator()(int i) const { return me.gen(i); }
1690};
1691
1692char *test_absrel::genResult() const {
1693    return collectIntFunResults(membind(*this), 0, get_size()-1, 3, 1, 1);
1694}
1695
1696struct test_ecoli : public test_absrel {
1697    BI_ecoli_ref& eref;
1698    test_ecoli(BI_ecoli_ref& b, bool to_rel) : test_absrel(to_rel), eref(b) {}
1699    int a2r(int a) const OVERRIDE { return eref.abs_2_rel(a); }
1700    int r2a(int r) const OVERRIDE { return eref.rel_2_abs(r); }
1701    int abs_size() const OVERRIDE { return eref.abs_count(); }
1702    int rel_size() const OVERRIDE { return eref.base_count(); }
1703};
1704
1705struct test_basepos : public test_absrel {
1706    BasePosition& bpos;
1707    test_basepos(BasePosition& bpos_, bool to_rel)
1708        : test_absrel(to_rel), bpos(bpos_) {}
1709    int a2r(int a) const OVERRIDE { return bpos.abs_2_rel(a); }
1710    int r2a(int r) const OVERRIDE { return bpos.rel_2_abs(r); }
1711    int abs_size() const OVERRIDE { return bpos.abs_count(); }
1712    int rel_size() const OVERRIDE { return bpos.base_count(); }
1713};
1714
1715#define TEST_ABSREL_EQUALS(tester,expected) do {        \
1716        char *res = tester.genResult();                 \
1717        TEST_EXPECT_EQUAL(res,expected);                \
1718        free(res);                                      \
1719    } while(0)
1720
1721#define TEST_ECOLIREF_EQUALS(data,alen,a2r,r2a) do {            \
1722        BI_ecoli_ref eref;                                      \
1723        eref.init(data,alen);                                   \
1724        TEST_ABSREL_EQUALS(test_ecoli(eref, true), a2r);        \
1725        TEST_ABSREL_EQUALS(test_ecoli(eref, false), r2a);       \
1726    } while(0)
1727
1728
1729#define TEST_BASE_POS_EQUALS(data,a2r,r2a) do {                                               \
1730        {                                                                                     \
1731            BasePosition bpos(data, strlen(data), CharPredicate(ED4_is_gap_character));       \
1732            TEST_ABSREL_EQUALS(test_basepos(bpos, true), a2r);                                \
1733            TEST_ABSREL_EQUALS(test_basepos(bpos, false), r2a);                               \
1734        }                                                                                     \
1735    } while(0)
1736
1737void TEST_BI_ecoli_ref() {
1738    TEST_ECOLIREF_EQUALS("-.AC-G-T-.", 10,
1739                         "  [0]  0  0  0  1  2  2  3  3  4  4  4  [4]", // abs -> rel
1740                         "  [0]  2  3  5  7  [7]");                     // rel -> abs
1741
1742    TEST_ECOLIREF_EQUALS("-",   1, "  [0]  0  0  [0]",       "  [0]  [0]");
1743    TEST_ECOLIREF_EQUALS("--A", 1, "  [0]  0  0  [0]",       "  [0]  [0]"); // part of sequence
1744    TEST_ECOLIREF_EQUALS("--",  2, "  [0]  0  0  0  [0]",    "  [0]  [0]");
1745    TEST_ECOLIREF_EQUALS("---", 3, "  [0]  0  0  0  0  [0]", "  [0]  [0]");
1746
1747    TEST_ECOLIREF_EQUALS("A",   1, "  [0]  0  1  [1]",       "  [0]  0  [0]");
1748    TEST_ECOLIREF_EQUALS("A",   2, "  [0]  0  1  1  [1]",    "  [0]  0  [0]");
1749
1750    TEST_ECOLIREF_EQUALS("A-",  2, "  [0]  0  1  1  [1]",    "  [0]  0  [0]");
1751    TEST_ECOLIREF_EQUALS("-A",  2, "  [0]  0  0  1  [1]",    "  [0]  1  [1]");
1752
1753    TEST_ECOLIREF_EQUALS("A",   3, "  [0]  0  1  1  1  [1]", "  [0]  0  [0]"); // more than sequence
1754    TEST_ECOLIREF_EQUALS("A--", 3, "  [0]  0  1  1  1  [1]", "  [0]  0  [0]");
1755    TEST_ECOLIREF_EQUALS("-A-", 3, "  [0]  0  0  1  1  [1]", "  [0]  1  [1]");
1756    TEST_ECOLIREF_EQUALS("--A", 3, "  [0]  0  0  0  1  [1]", "  [0]  2  [2]");
1757}
1758
1759void TEST_base_position() {
1760    ED4_setup_gaps_and_alitype("-", GB_AT_RNA); // count '.' as base
1761
1762    TEST_BASE_POS_EQUALS("-.AC-G-T-.",
1763                         "  [0]  0  0  1  2  3  3  4  4  5  5  6  [6]", // abs -> rel
1764                         "  [0]  1  2  3  5  7  9  [9]");               // rel -> abs
1765
1766    // ------------------------------
1767    ED4_setup_gaps_and_alitype(".-", GB_AT_RNA); // count '.' as gap
1768
1769    TEST_BASE_POS_EQUALS("-.AC-G-T-.",
1770                         "  [0]  0  0  0  1  2  2  3  3  4  4  4  [4]", // abs -> rel
1771                         "  [0]  2  3  5  7  [7]");                     // rel -> abs
1772
1773    TEST_BASE_POS_EQUALS("-",   "  [0]  0  0  [0]",       "  [0]  [0]");
1774    TEST_BASE_POS_EQUALS("--",  "  [0]  0  0  0  [0]",    "  [0]  [0]");
1775    TEST_BASE_POS_EQUALS("---", "  [0]  0  0  0  0  [0]", "  [0]  [0]");
1776
1777    TEST_BASE_POS_EQUALS("A",   "  [0]  0  1  [1]",       "  [0]  0  [0]");
1778
1779    TEST_BASE_POS_EQUALS("A-",  "  [0]  0  1  1  [1]",    "  [0]  0  [0]");
1780    TEST_BASE_POS_EQUALS("-A",  "  [0]  0  0  1  [1]",    "  [0]  1  [1]");
1781
1782    TEST_BASE_POS_EQUALS("A--", "  [0]  0  1  1  1  [1]", "  [0]  0  [0]");
1783    TEST_BASE_POS_EQUALS("-A-", "  [0]  0  0  1  1  [1]", "  [0]  1  [1]");
1784    TEST_BASE_POS_EQUALS("--A", "  [0]  0  0  0  1  [1]", "  [0]  2  [2]");
1785}
1786
1787#endif // UNIT_TESTS
1788
1789
Note: See TracBrowser for help on using the repository browser.