source: tags/arb-6.0/EDIT4/ED4_cursor.cxx

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