source: tags/ms_r18q1/EDIT4/ED4_cursor.cxx

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