source: tags/arb-6.0/EDIT4/ED4_root.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: 78.7 KB
Line 
1// =============================================================== //
2//                                                                 //
3//   File      : ED4_root.cxx                                      //
4//   Purpose   :                                                   //
5//                                                                 //
6//   Institute of Microbiology (Technical University Munich)       //
7//   http://www.arb-home.de/                                       //
8//                                                                 //
9// =============================================================== //
10
11#include "ed4_class.hxx"
12#include "ed4_awars.hxx"
13#include "ed4_tools.hxx"
14#include "ed4_block.hxx"
15#include "ed4_dots.hxx"
16#include "ed4_nds.hxx"
17#include "ed4_list.hxx"
18#include "ed4_plugins.hxx"
19#include "ed4_visualizeSAI.hxx"
20#include "ed4_naligner.hxx"
21#include "ed4_ProteinViewer.hxx"
22#include "ed4_protein_2nd_structure.hxx"
23#include "graph_aligner_gui.hxx"
24#include "ed4_colStat.hxx"
25
26#include <ed4_extern.hxx>
27#include <fast_aligner.hxx>
28#include <AW_helix.hxx>
29#include <gde.hxx>
30#include <awt.hxx>
31#include <awt_seq_colors.hxx>
32#include <awt_map_key.hxx>
33#include <aw_awars.hxx>
34#include <aw_preset.hxx>
35#include <aw_msg.hxx>
36#include <arb_progress.h>
37#include <aw_root.hxx>
38#include <aw_question.hxx>
39#include <aw_advice.hxx>
40#include "../WINDOW/aw_status.hxx" // @@@ hack - obsolete when EDIT4 status works like elsewhere
41#include <arb_version.h>
42#include <arb_file.h>
43#include <arbdbt.h>
44#include <ad_cb.h>
45#include <macros.hxx>
46
47#include <cctype>
48#include <map>
49
50AW_window *AWTC_create_island_hopping_window(AW_root *root, AW_CL);
51
52ED4_WinContext ED4_WinContext::current_context;
53
54void ED4_folding_line::warn_illegal_dimension() {
55#if defined(DEBUG)
56    if (dimension<0.0) {
57        // e4_assert(0); // crashes gdb when called from scrollbar callback - so instead only dump backtrace
58        const char *msg = GBS_global_string("illegal dimension %f\n", dimension);
59        GBK_dump_backtrace(stderr, msg);
60    }
61#endif
62}
63
64void ED4_WinContext::warn_missing_context() const {
65    e4_assert(0);
66    GBK_dump_backtrace(stderr, "Missing context");
67    aw_message("Missing context - please send information from console to devel@arb-home.de");
68}
69
70static ARB_ERROR request_terminal_refresh(ED4_base *base, AW_CL cl_level) {
71    ED4_level lev = ED4_level(cl_level);
72    if (lev == ED4_L_NO_LEVEL || (base->spec.level&lev) != 0) {
73        if (base->is_terminal()) base->request_refresh();
74    }
75    return NULL;
76}
77
78void ED4_root::request_refresh_for_all_terminals() {
79    main_manager->route_down_hierarchy(request_terminal_refresh, ED4_L_NO_LEVEL).expect_no_error();
80}
81
82void ED4_root::request_refresh_for_specific_terminals(ED4_level lev) {
83    main_manager->route_down_hierarchy(request_terminal_refresh, lev).expect_no_error();
84}
85
86
87static ARB_ERROR request_sequence_refresh(ED4_base *base, AW_CL cl_consensi) {
88    ARB_ERROR error;
89    if (base->spec.level & ED4_L_SPECIES) {
90        bool consensi = bool(cl_consensi);
91        if (base->is_consensus_manager() == consensi) {
92            error = base->to_manager()->route_down_hierarchy(request_terminal_refresh, ED4_L_SEQUENCE_STRING);
93        }
94    }
95    return error;
96}
97
98// if you want to refresh consensi AND sequences you may use request_refresh_for_specific_terminals(ED4_L_SEQUENCE_STRING)
99void ED4_root::request_refresh_for_consensus_terminals() {
100    main_manager->route_down_hierarchy(request_sequence_refresh, true).expect_no_error();
101}
102void ED4_root::request_refresh_for_sequence_terminals() {
103    if (main_manager) {
104        main_manager->route_down_hierarchy(request_sequence_refresh, false).expect_no_error();
105    }
106}
107
108void ED4_root::refresh_window_simple(bool redraw) {
109    // if 'redraw' -> update everything (ignoring refresh flag)
110    int refresh_all = 0;
111    if (redraw) {
112#if defined(TRACE_REFRESH)
113        fprintf(stderr, "- clear display (refresh_window_simple(redraw=true) called)\n"); fflush(stderr);
114#endif
115        main_manager->update_info.set_clear_at_refresh(1);
116        refresh_all = 1;
117    }
118
119    main_manager->Show(refresh_all, 0);
120    if (redraw) main_manager->update_info.set_clear_at_refresh(0);
121}
122
123void ED4_root::handle_update_requests(bool& redraw) {
124    if (main_manager->update_info.delete_requested) {
125#if defined(TRACE_REFRESH)
126        fprintf(stderr, "- handling requested deletes\n"); fflush(stderr);
127#endif
128        main_manager->delete_requested_children();
129        redraw = true;
130    }
131
132    if (main_manager->update_info.update_requested) {
133#if defined(TRACE_REFRESH)
134        fprintf(stderr, "- handling requested updates\n"); fflush(stderr);
135#endif
136        main_manager->update_requested_children();
137        redraw = true; // @@@ needed ?
138    }
139
140    while (main_manager->update_info.resize) {
141#if defined(TRACE_REFRESH)
142        fprintf(stderr, "- handling requested resizes\n"); fflush(stderr);
143#endif
144        main_manager->resize_requested_children();
145        redraw = true;
146    }
147
148    // make sure all update request have been handled:
149    e4_assert(!main_manager->update_info.delete_requested);
150    e4_assert(!main_manager->update_info.update_requested);
151    e4_assert(!main_manager->update_info.resize);
152}
153
154void ED4_root::special_window_refresh(bool handle_updates) {
155    // this function should only be used for window specific updates (e.g. cursor placement/deletion)
156    e4_assert(ED4_WinContext::have_context());
157
158    bool redraw = true;
159    if (handle_updates) handle_update_requests(redraw);
160    refresh_window_simple(redraw);
161    // do NOT clear_refresh_requests here!! this is no full refresh!
162}
163
164ED4_returncode ED4_root::refresh_all_windows(bool redraw) {
165    // if 'redraw' -> update everything (ignoring refresh flag)
166    GB_transaction ta(GLOBAL_gb_main);
167
168    handle_update_requests(redraw);
169   
170    ED4_window *window = first_window;
171    while (window) {
172        ED4_LocalWinContext uses(window);
173        refresh_window_simple(redraw);
174        window = window->next;
175    }
176
177    if (main_manager->update_info.refresh) main_manager->clear_refresh();
178
179    return (ED4_R_OK);
180}
181
182// --------------------------------------------------------------------------------
183
184#ifdef UNIT_TESTS
185#ifndef TEST_UNIT_H
186#include <test_unit.h>
187#endif
188
189static arb_test::match_expectation correct_win2world_calculation(ED4_foldable& foldable, int xwin_org, int ywin_org, int xwrld_expd, int ywrld_expd) {
190    using namespace arb_test;
191    match_expectation precondition(all().of(that(xwrld_expd).is_more_or_equal(xwin_org),
192                                            that(ywrld_expd).is_more_or_equal(ywin_org)));
193
194    AW_pos xwrld_calc = xwin_org;
195    AW_pos ywrld_calc = ywin_org;
196    foldable.win_to_world_coords(&xwrld_calc, &ywrld_calc);
197
198    match_expectation win_2_world_conversion(all().of(that(xwrld_calc).is_equal_to(xwrld_expd),
199                                                      that(ywrld_calc).is_equal_to(ywrld_expd)));
200
201    AW_pos xwin_back = xwrld_calc;
202    AW_pos ywin_back = ywrld_calc;
203    foldable.world_to_win_coords(&xwin_back, &ywin_back);
204
205    match_expectation world_back2_win_conversion(all().of(that(xwin_back).is_equal_to(xwin_org),
206                                                          that(ywin_back).is_equal_to(ywin_org)));
207
208    return all().of(precondition, win_2_world_conversion, world_back2_win_conversion);
209}
210
211static arb_test::match_expectation correct_world2win_calculation(ED4_foldable& foldable, int xwrld_org, int ywrld_org, int xwin_expd, int ywin_expd) {
212    using namespace arb_test;
213    match_expectation precondition(all().of(that(xwrld_org).is_more_or_equal(xwin_expd),
214                                            that(ywrld_org).is_more_or_equal(ywin_expd)));
215
216
217    AW_pos xwin_calc = xwrld_org;
218    AW_pos ywin_calc = ywrld_org;
219    foldable.world_to_win_coords(&xwin_calc, &ywin_calc);
220
221    match_expectation world_2_win_conversion(all().of(that(xwin_calc).is_equal_to(xwin_expd),
222                                                      that(ywin_calc).is_equal_to(ywin_expd)));
223
224    return all().of(precondition, world_2_win_conversion);
225}
226
227#define TEST_EXPECT_WIN_UNFOLDED(xwi,ywi)              TEST_EXPECTATION(correct_win2world_calculation(foldable, xwi, ywi, xwi, ywi))
228#define TEST_EXPECT_WIN_WORLD_FOLDING(xwi,ywi,fx,fy)   TEST_EXPECTATION(correct_win2world_calculation(foldable, xwi, ywi, (xwi)+(fx), (ywi)+(fy)))
229#define TEST_EXPECT_WORLD_WIN_FOLDING(xwo,ywo,xwi,ywi) TEST_EXPECTATION(correct_world2win_calculation(foldable, xwo, ywo, xwi, ywi))
230
231#define TEST_EXPECT_WIN_WORLD_FOLDING__BROKEN(xwi,ywi,fx,fy)        TEST_EXPECTATION__BROKEN(correct_win2world_calculation(foldable, xwi, ywi, (xwi)+(fx), (ywi)+(fy)))
232#define TEST_EXPECT_WIN_WORLD_FOLDING__BROKENIF(when,xwi,ywi,fx,fy) TEST_EXPECTATION__BROKENIF(when, correct_win2world_calculation(foldable, xwi, ywi, (xwi)+(fx), (ywi)+(fy)))
233
234void TEST_win_2_world() {
235    ED4_foldable foldable;
236
237    const int X1 = 200;
238    const int X2 = 300;
239    const int Y1 = 100;
240    const int Y2 = 200;
241
242    ED4_folding_line *hor100 = foldable.insert_folding_line(Y1, 0, ED4_P_HORIZONTAL);
243    ED4_folding_line *ver200 = foldable.insert_folding_line(X1, 0, ED4_P_VERTICAL);
244    ED4_folding_line *hor200 = foldable.insert_folding_line(Y2, 0, ED4_P_HORIZONTAL);
245    ED4_folding_line *ver300 = foldable.insert_folding_line(X2, 0, ED4_P_VERTICAL);
246
247    // nothing folded yet
248
249    const int x01 = X1/2;
250    const int x12 = (X1+X2)/2;
251    const int x23 = X2+x01;
252
253    const int y01 = Y1/2;
254    const int y12 = (Y1+Y2)/2;
255    const int y23 = Y2+y01;
256
257    TEST_EXPECT_WIN_UNFOLDED(x01, y01);
258    TEST_EXPECT_WIN_UNFOLDED(x12, y01);
259    TEST_EXPECT_WIN_UNFOLDED(x23, y01);
260
261    TEST_EXPECT_WIN_UNFOLDED(x01, y12);
262    TEST_EXPECT_WIN_UNFOLDED(x12, y12);
263    TEST_EXPECT_WIN_UNFOLDED(x23, y12);
264
265    TEST_EXPECT_WIN_UNFOLDED(x01, y23);
266    TEST_EXPECT_WIN_UNFOLDED(x12, y23);
267    TEST_EXPECT_WIN_UNFOLDED(x23, y23);
268
269    for (int FACTOR = 1; FACTOR <= 100; FACTOR += 7) {
270        TEST_ANNOTATE(GBS_global_string("FACTOR=%i", FACTOR));
271        int H1 = FACTOR* 10;
272        int H2 = FACTOR* 40;
273        int V1 = FACTOR* 20;
274        int V2 = FACTOR* 80;
275
276        hor100->set_dimension(H1);
277        hor200->set_dimension(H2);
278        ver200->set_dimension(V1);
279        ver300->set_dimension(V2);
280
281        TEST_EXPECT_WIN_UNFOLDED     (x01, y01); // always in unfolded range
282        TEST_EXPECT_WIN_WORLD_FOLDING(x12, y01, V1,    0);
283        TEST_EXPECT_WIN_WORLD_FOLDING(x23, y01, V1+V2, 0);
284
285        TEST_EXPECT_WIN_WORLD_FOLDING(x01, y12, 0,     H1);
286        TEST_EXPECT_WIN_WORLD_FOLDING(x12, y12, V1,    H1);
287        TEST_EXPECT_WIN_WORLD_FOLDING(x23, y12, V1+V2, H1);
288
289        TEST_EXPECT_WIN_WORLD_FOLDING(x01, y23, 0,     H1+H2);
290        TEST_EXPECT_WIN_WORLD_FOLDING(x12, y23, V1,    H1+H2);
291        TEST_EXPECT_WIN_WORLD_FOLDING(x23, y23, V1+V2, H1+H2);
292
293        // test "folded" world positions.
294        // they result in win positions lower than folding line!
295        TEST_EXPECT_WORLD_WIN_FOLDING(X1-1,    Y1-1,    X1-1,    Y1-1);    // left of/above folded range
296        TEST_EXPECT_WORLD_WIN_FOLDING(X1,      Y1,      X1-V1,   Y1-H1);   // left/upper end of folded range
297        TEST_EXPECT_WORLD_WIN_FOLDING(X1+5,    Y1+5,    X1+5-V1, Y1+5-H1); // in folded range
298        TEST_EXPECT_WORLD_WIN_FOLDING(X1+V1,   Y1+H1,   X1,      Y1);      // right/lower end of folded range
299        TEST_EXPECT_WORLD_WIN_FOLDING(X1+V1+1, Y1+H1+1, X1+1,    Y1+1);    // right of/below folded range
300    }
301}
302
303#endif // UNIT_TESTS
304
305// --------------------------------------------------------------------------------
306
307ED4_returncode ED4_root::deselect_all()
308{
309    ED4_multi_species_manager *main_multi_man = middle_area_man->get_multi_species_manager();
310    main_multi_man->deselect_all_species_and_SAI();
311
312    main_multi_man = top_area_man->get_multi_species_manager();
313    main_multi_man->deselect_all_species_and_SAI();
314
315    return ED4_R_OK;
316}
317
318void ED4_root::remove_from_selected(ED4_species_name_terminal *name_term) { // @@@ change param to ED4_species_manager ?
319    if (name_term) {
320        if ((selected_objects->has_elem(name_term->selection_info))) {
321            selected_objects->remove_elem(name_term->selection_info);
322
323            delete name_term->selection_info;
324            name_term->selection_info    = NULL;
325            name_term->containing_species_manager()->set_selected(false);
326            name_term->dragged = false; // @@@ caller shall do this
327
328#ifdef DEBUG
329            GBDATA *gbd = name_term->get_species_pointer();
330
331            if (gbd) {
332                printf("removed term '%s'\n", GB_read_char_pntr(gbd));
333            }
334            else {
335                ED4_species_manager *spec_man = name_term->get_parent(ED4_L_SPECIES)->to_species_manager();
336
337                if (spec_man->is_consensus_manager()) {
338                    printf("removed consensus '%s'\n", name_term->id);
339                }
340                else {
341                    printf("removed unknown term '%s'\n", name_term->id ? name_term->id : "NULL");
342                }
343            }
344#endif
345
346            name_term->request_refresh();
347            ED4_sequence_terminal *seq_term = name_term->corresponding_sequence_terminal();
348            if (seq_term) seq_term->request_refresh();
349
350            // ProtView: Refresh corresponding orf terminals
351            if (alignment_type == GB_AT_DNA) {
352                PV_CallBackFunction(this->aw_root);
353            }
354
355            ED4_multi_species_manager *multi_man = name_term->get_parent(ED4_L_MULTI_SPECIES)->to_multi_species_manager();
356            multi_man->invalidate_species_counters();
357        }
358    }
359}
360
361void ED4_root::announce_useraction_in(AW_window *aww) {
362    for (ED4_window *win = first_window; win; win = win->next) {
363        if (win->aww == aww) {
364            most_recently_used_window = win;
365        }
366    }
367}
368
369ED4_returncode ED4_root::add_to_selected(ED4_species_name_terminal *name_term) { // @@@ change param to ED4_species_manager ?
370    if (!name_term || !(name_term->dynamic_prop & ED4_P_SELECTABLE)) {   // check if object exists and may be selected
371        return (ED4_R_IMPOSSIBLE);
372    }
373
374    if (!(selected_objects->has_elem(name_term->selection_info))) {     // object is really new to our list => calculate current extension and append it
375        ED4_selection_entry *sel_info = new ED4_selection_entry;
376        name_term->selection_info     = sel_info;
377
378        if (name_term->dynamic_prop & ED4_P_IS_HANDLE) { // object is a handle for an object up in the hierarchy => search it
379            ED4_level  mlevel     = name_term->spec.handled_level;
380            ED4_base  *tmp_object = name_term;
381
382            while ((tmp_object != NULL) && !(tmp_object->spec.level & mlevel)) {
383                tmp_object = tmp_object->parent;
384            }
385
386            if (!tmp_object) return (ED4_R_WARNING); // no target level found
387
388            sel_info->actual_width  = tmp_object->extension.size[WIDTH];
389            sel_info->actual_height = tmp_object->extension.size[HEIGHT];
390        }
391        else // selected object is no handle => take it directly
392        {
393            sel_info->actual_width  = name_term->extension.size[WIDTH];
394            sel_info->actual_height = name_term->extension.size[HEIGHT];
395        }
396
397        sel_info->drag_old_x  = 0;
398        sel_info->drag_old_y  = 0;
399        sel_info->drag_off_x  = 0;
400        sel_info->drag_off_y  = 0;
401        sel_info->old_event_y = 0;
402
403        sel_info->object = name_term;
404
405        selected_objects->prepend_elem(sel_info);
406
407        name_term->containing_species_manager()->set_selected(true);
408
409#ifdef DEBUG
410        GBDATA *gbd = name_term->get_species_pointer();
411
412        if (gbd) {
413            printf("added term '%s'\n", GB_read_char_pntr(gbd));
414        }
415        else {
416            ED4_species_manager *spec_man = name_term->get_parent(ED4_L_SPECIES)->to_species_manager();
417            if (spec_man->is_consensus_manager()) {
418                printf("added consensus '%s'\n", name_term->id);
419            }
420            else {
421                printf("added unknown term '%s'\n", name_term->id ? name_term->id : "NULL");
422            }
423        }
424#endif
425
426        name_term->request_refresh();
427        ED4_sequence_terminal *seq_term = name_term->corresponding_sequence_terminal();
428        if (seq_term) seq_term->request_refresh();
429
430        // ProtView: Refresh corresponding orf terminals
431        if (alignment_type == GB_AT_DNA) {
432            PV_CallBackFunction(this->aw_root);
433        }
434
435        ED4_multi_species_manager *multi_man = name_term->get_parent(ED4_L_MULTI_SPECIES)->to_multi_species_manager();
436        multi_man->invalidate_species_counters();
437
438        return (ED4_R_OK);
439    }
440
441    return (ED4_R_IMPOSSIBLE);
442}
443
444void ED4_root::resize_all() {
445    while (main_manager->update_info.resize) {
446        main_manager->resize_requested_children();
447    }
448}
449
450static ARB_ERROR change_char_table_length(ED4_base *base, AW_CL new_length) {
451    if (base->is_abstract_group_manager()) {
452        ED4_abstract_group_manager *group_man = base->to_abstract_group_manager();
453        group_man->table().change_table_length(new_length);
454    }
455    return NULL;
456}
457
458void ED4_alignment_length_changed(GBDATA *gb_alignment_len, GB_CB_TYPE IF_ASSERTION_USED(gbtype)) // callback from database
459{
460    e4_assert(gbtype==GB_CB_CHANGED);
461    int new_length = GB_read_int(gb_alignment_len);
462
463#if defined(DEBUG) && 1
464    printf("alignment_length_changed from %i to %i\n", MAXSEQUENCECHARACTERLENGTH, new_length);
465#endif
466
467    if (MAXSEQUENCECHARACTERLENGTH!=new_length) { // otherwise we already did this (i.e. we were called by changed_by_database)
468        bool was_increased = new_length>MAXSEQUENCECHARACTERLENGTH;
469
470        MAXSEQUENCECHARACTERLENGTH = new_length;
471
472        {
473            const char *err = ED4_ROOT->helix->init(GLOBAL_gb_main); // reload helix
474            aw_message_if(err);
475        }
476        {
477            const char *err = ED4_ROOT->ecoli_ref->init(GLOBAL_gb_main); // reload ecoli
478            aw_message_if(err);
479        }
480
481        if (ED4_ROOT->alignment_type == GB_AT_AA) {
482            // TODO: is this needed here?
483            const char *err = ED4_pfold_set_SAI(&ED4_ROOT->protstruct, GLOBAL_gb_main, ED4_ROOT->alignment_name, &ED4_ROOT->protstruct_len); // reload protstruct
484            aw_message_if(err);
485        }
486
487        if (was_increased) {
488            ED4_ROOT->main_manager->route_down_hierarchy(change_char_table_length, new_length).expect_no_error();
489            ED4_ROOT->root_group_man->remap()->mark_compile_needed_force();
490        }
491    }
492}
493
494ED4_returncode ED4_root::init_alignment() {
495    GB_transaction ta(GLOBAL_gb_main);
496
497    alignment_name = GBT_get_default_alignment(GLOBAL_gb_main);
498    alignment_type = GBT_get_alignment_type(GLOBAL_gb_main, alignment_name);
499    if (alignment_type==GB_AT_UNKNOWN) {
500        aw_popup_exit("You have to select a valid alignment before you can start ARB_EDIT4");
501    }
502
503    GBDATA *gb_alignment = GBT_get_alignment(GLOBAL_gb_main, alignment_name);
504    if (!gb_alignment) aw_popup_exit("You can't edit without an existing alignment");
505
506    GBDATA *gb_alignment_len = GB_search(gb_alignment, "alignment_len", GB_FIND);
507    int alignment_length = GB_read_int(gb_alignment_len);
508    MAXSEQUENCECHARACTERLENGTH = alignment_length;
509
510    GB_add_callback(gb_alignment_len, GB_CB_CHANGED, makeDatabaseCallback(ED4_alignment_length_changed));
511
512    aw_root->awar_string(AWAR_EDITOR_ALIGNMENT, alignment_name);
513
514    return ED4_R_OK;
515}
516
517void ED4_root::recalc_font_group() {
518    font_group.unregisterAll();
519    for (int f=ED4_G_FIRST_FONT; f<=ED4_G_LAST_FONT; f++) {
520        ED4_MostRecentWinContext context;
521        font_group.registerFont(current_device(), f);
522    }
523}
524
525static ARB_ERROR force_group_update(ED4_base *base) {
526    if (base->is_multi_species_manager()) {
527        base->to_multi_species_manager()->update_requested_by_child();
528    }
529    return NULL;
530}
531
532ED4_returncode ED4_root::create_hierarchy(char *area_string_middle, char *area_string_top) {
533    // creates internal hierarchy of editor
534
535    long total_no_of_groups  = 0;
536    long total_no_of_species = 0;
537    {
538        // count species and related info (e.g. helix) displayed in the top region (a == 0)
539        // count no of species and sais including groups in middle region (a == 1)
540
541        const char *area_string[2] = { area_string_top, area_string_middle };
542        for (int a = 0; a<2; ++a) {
543            long group_count;
544            long species_count;
545            database->calc_no_of_all(area_string[a], &group_count, &species_count);
546
547            total_no_of_groups  += group_count;
548            total_no_of_species += species_count;
549        }
550    }
551
552    SmartPtr<arb_progress> startup_progress = new arb_progress("EDIT4 startup");
553
554    GB_push_transaction(GLOBAL_gb_main);
555
556    ecoli_ref = new BI_ecoli_ref;
557    ecoli_ref->init(GLOBAL_gb_main);
558
559    // [former position of ali-init-code]
560
561    main_manager   = new ED4_main_manager("Main_Manager", 0, 0, 0, 0, NULL); // build a test hierarchy
562    root_group_man = new ED4_root_group_manager("Root_Group_Manager", 0, 0, 0, 0, main_manager);
563   
564    main_manager->children->append_member(root_group_man);
565
566    ED4_device_manager *device_manager = new ED4_device_manager("Device_Manager", 0, 0, 0, 0, root_group_man);
567    root_group_man->children->append_member(device_manager);
568
569    ED4_calc_terminal_extentions();
570
571    {
572        int col_stat_term_height = 50; // @@@ Hoehe des ColumnStatistics Terminals ausrechnen
573
574        ref_terminals.init(new ED4_sequence_info_terminal("Reference_Sequence_Info_Terminal", /* NULL, */ 250, 0, MAXINFOWIDTH, TERMINALHEIGHT, NULL),
575                           new ED4_sequence_terminal("Reference_Sequence_Terminal", 300, 0, 300, TERMINALHEIGHT, NULL, false),
576                           new ED4_sequence_info_terminal("Reference_ColumnStatistics_Info_Terminal", /* NULL, */ 250, 0, MAXINFOWIDTH, col_stat_term_height, NULL),
577                           new ED4_columnStat_terminal("Reference_ColumnStatistics_Terminal", 300, 0, 300, col_stat_term_height, NULL));
578    }
579
580
581    recalc_font_group();
582
583    ED4_index y = 0;
584
585    {
586        arb_progress species_progress("Loading species", total_no_of_species);
587       
588        const int XPOS_MULTIMAN = 100;
589
590        // ********** Top Area beginning **********
591
592        ED4_multi_species_manager *top_multi_species_manager;
593        ED4_spacer_terminal       *top_spacer_terminal;
594        ED4_spacer_terminal       *top_mid_spacer_terminal;
595        ED4_spacer_terminal       *top_multi_spacer_terminal_beg;
596        ED4_line_terminal         *top_mid_line_terminal;
597        {
598            ED4_area_manager *top_area_manager = new ED4_area_manager("Top_Area_Manager", 0, y, 0, 0, device_manager);
599            device_manager->children->append_member(top_area_manager);
600            top_area_man = top_area_manager;
601
602            top_spacer_terminal = new ED4_spacer_terminal("Top_Spacer", true, 0, 0, 100, 10, top_area_manager);
603            top_area_manager->children->append_member(top_spacer_terminal);
604
605            top_multi_species_manager = new ED4_multi_species_manager("Top_MultiSpecies_Manager", XPOS_MULTIMAN, 0, 0, 0, top_area_manager);
606            top_area_manager->children->append_member(top_multi_species_manager);
607
608            top_multi_spacer_terminal_beg = new ED4_spacer_terminal("Top_Multi_Spacer_Terminal_Beg", true, 0, 0, 0, 3, top_multi_species_manager);
609            top_multi_species_manager->children->append_member(top_multi_spacer_terminal_beg);
610
611            y += 3;
612
613            reference = new AWT_reference(GLOBAL_gb_main);
614
615            int index = 0;
616            database->scan_string(top_multi_species_manager, ref_terminals.get_ref_sequence_info(), ref_terminals.get_ref_sequence(),
617                                  area_string_top, &index, &y, species_progress);
618            GB_pop_transaction(GLOBAL_gb_main);
619
620            const int TOP_MID_LINE_HEIGHT   = 3;
621            int       TOP_MID_SPACER_HEIGHT = font_group.get_max_height()-TOP_MID_LINE_HEIGHT;
622
623            top_mid_line_terminal = new ED4_line_terminal("Top_Mid_Line_Terminal", 0, y, 0, TOP_MID_LINE_HEIGHT, device_manager);    // width will be set below
624            device_manager->children->append_member(top_mid_line_terminal);
625
626            y += TOP_MID_LINE_HEIGHT;
627
628
629            top_mid_spacer_terminal = new ED4_spacer_terminal("Top_Middle_Spacer", true, 0, y, 880, TOP_MID_SPACER_HEIGHT,   device_manager);
630            device_manager->children->append_member(top_mid_spacer_terminal);
631
632            // needed to avoid text-clipping problems:
633            main_manager->set_top_middle_spacer_terminal(top_mid_spacer_terminal);
634            main_manager->set_top_middle_line_terminal(top_mid_line_terminal);
635
636            y += TOP_MID_SPACER_HEIGHT; // add top-mid_spacer_terminal height
637        }
638
639        // ********** Middle Area beginning **********
640
641        ED4_area_manager          *middle_area_manager;
642        ED4_tree_terminal         *tree_terminal;
643        ED4_multi_species_manager *mid_multi_species_manager;
644        ED4_spacer_terminal       *mid_multi_spacer_terminal_beg;
645        ED4_line_terminal         *mid_bot_line_terminal;
646        ED4_spacer_terminal       *total_bottom_spacer;
647        {
648            middle_area_manager = new ED4_area_manager("Middle_Area_Manager", 0, y, 0, 0, device_manager);
649            device_manager->children->append_member(middle_area_manager);
650            middle_area_man = middle_area_manager;
651
652            tree_terminal = new ED4_tree_terminal("Tree", 0, 0, 2, 0, middle_area_manager);
653            middle_area_manager->children->append_member(tree_terminal);
654
655            mid_multi_species_manager = new ED4_multi_species_manager("Middle_MultiSpecies_Manager", XPOS_MULTIMAN, 0, 0, 0, middle_area_manager);
656            middle_area_manager->children->append_member(mid_multi_species_manager);
657
658            mid_multi_spacer_terminal_beg = new ED4_spacer_terminal("Mid_Multi_Spacer_Terminal_Beg", true, 0, 0, 0, 3, mid_multi_species_manager);
659            mid_multi_species_manager->children->append_member(mid_multi_spacer_terminal_beg);
660
661            y+=3;               // dummy height, to create a dummy layout ( to preserve order of objects )
662
663            scroll_links.link_for_ver_slider = middle_area_manager;
664
665            ED4_index help = y;
666            {
667                GB_transaction ta(GLOBAL_gb_main);
668                int index  = 0;
669                database->scan_string(mid_multi_species_manager, ref_terminals.get_ref_sequence_info(), ref_terminals.get_ref_sequence(),
670                                      area_string_middle, &index, &y, species_progress);
671            }
672
673            {
674                ED4_spacer_terminal *mid_bot_spacer_terminal = new ED4_spacer_terminal("Middle_Bot_Spacer_Terminal", true, 0, y, 880, 10, device_manager);
675                device_manager->children->append_member(mid_bot_spacer_terminal);
676            }
677
678            tree_terminal->extension.size[HEIGHT] = y - help;
679
680            y += 10; // add top-mid_spacer_terminal height
681
682            mid_bot_line_terminal = new ED4_line_terminal("Mid_Bot_Line_Terminal", 0, y, 0, 3, device_manager);    // width will be set below
683            device_manager->children->append_member(mid_bot_line_terminal);
684            y += 3;
685
686            total_bottom_spacer = new ED4_spacer_terminal("Total_Bottom_Spacer_terminal", true, 0, y, 0, 10000, device_manager);
687            device_manager->children->append_member(total_bottom_spacer);
688            y += 10000;
689        }
690
691        if (scroll_links.link_for_hor_slider) {
692            long ext_width = long(scroll_links.link_for_hor_slider->extension.size[WIDTH]);
693
694            top_multi_spacer_terminal_beg->extension.size[WIDTH] = ext_width + MAXSPECIESWIDTH + SEQUENCEINFOSIZE;
695            mid_multi_spacer_terminal_beg->extension.size[WIDTH] = ext_width + MAXSPECIESWIDTH + SEQUENCEINFOSIZE;
696            total_bottom_spacer->extension.size[WIDTH] = ext_width + MAXSPECIESWIDTH + SEQUENCEINFOSIZE;
697
698            top_mid_line_terminal->extension.size[WIDTH] = ext_width + TREETERMINALSIZE + MAXSPECIESWIDTH + SEQUENCEINFOSIZE;
699            mid_bot_line_terminal->extension.size[WIDTH] = ext_width + TREETERMINALSIZE + MAXSPECIESWIDTH + SEQUENCEINFOSIZE;
700
701        }
702
703        tree_terminal->set_links(NULL, mid_multi_species_manager);                          // set links
704        top_spacer_terminal->set_links(tree_terminal, top_multi_species_manager);
705        top_mid_spacer_terminal->set_links(middle_area_manager, NULL);
706        total_bottom_spacer->set_links(mid_bot_line_terminal, 0);
707
708        species_progress.done();
709    }
710
711    first_window->update_window_coords();
712    resize_all();
713
714    main_manager->route_down_hierarchy(force_group_update).expect_no_error();
715
716    if (!scroll_links.link_for_hor_slider) { // happens when no species AND no SAI has data
717        startup_progress->done();
718        startup_progress.SetNull(); // make progress disappear (otherwise prompter below is often behind progress window)
719        GB_pop_transaction(GLOBAL_gb_main);
720       
721        aw_popup_ok(GBS_global_string("No species/SAI contains data in '%s'\nARB_EDIT4 will terminate", alignment_name));
722        ED4_exit();
723    }
724
725    // build consensi
726    {
727        arb_progress consensi_progress("Initializing consensi", total_no_of_species+total_no_of_groups+1); // 1 is root_group_man
728
729        root_group_man->create_consensus(root_group_man, &consensi_progress);
730        e4_assert(root_group_man->table().ok());
731        consensi_progress.done(); // if there is a "top"-group, progress increment is one to low
732    }
733
734    root_group_man->remap()->mark_compile_needed_force();
735    root_group_man->update_remap();
736
737    // calc size and display:
738
739    resize_all();
740
741    e4_assert(main_manager);
742
743    {
744        ED4_base *x_link      = scroll_links.link_for_hor_slider;
745        ED4_base *y_link      = scroll_links.link_for_ver_slider;
746        ED4_base *width_link  = x_link;
747        ED4_base *height_link = y_link;
748
749        ED4_window *win = first_window;
750        while (win) {
751            win->set_scrolled_rectangle(x_link, y_link, width_link, height_link);
752            win->aww->show();
753            win->update_scrolled_rectangle();
754            win = win->next;
755        }
756    }
757
758    ED4_trigger_instant_refresh();
759    ED4_finish_and_show_notFoundMessage();
760
761    return ED4_R_OK;
762}
763
764ED4_returncode ED4_root::get_area_rectangle(AW_screen_area *rect, AW_pos x, AW_pos y) {
765    // returns win-coordinates of area (defined by folding lines) which contains position x/y
766    int                    x1, x2, y1, y2;
767    const AW_screen_area&  area_rect = current_device()->get_area_size();
768
769    x1 = area_rect.l;
770    for (const ED4_folding_line *flv=current_ed4w()->get_vertical_folding(); ; flv = flv->get_next()) {
771        if (flv) {
772            x2 = int(flv->get_pos()); // @@@ use AW_INT ?
773        }
774        else {
775            x2 = area_rect.r;
776            if (x1==x2) {
777                break;
778            }
779        }
780
781        y1 = area_rect.t;
782        for (const ED4_folding_line *flh=current_ed4w()->get_horizontal_folding(); ; flh = flh->get_next()) {
783            if (flh) {
784                y2 = int(flh->get_pos()); // @@@ use AW_INT ?
785            }
786            else {
787                y2 = area_rect.b;
788                if (y1==y2) {
789                    break;
790                }
791            }
792
793            if (x1<=x && x<=x2 && y1<=y && y<=y2) {
794                rect->t = y1;
795                rect->b = y2;
796                rect->l = x1;
797                rect->r = x2;
798                return ED4_R_OK;
799            }
800            y1 = y2;
801            if (!flh) break;
802        }
803        x1 = x2;
804        if (!flv) break;
805    }
806    return ED4_R_IMPOSSIBLE; // no area contains x/y :-(
807}
808
809void ED4_root::copy_window_struct(ED4_window *source,   ED4_window *destination)
810{
811    destination->slider_pos_horizontal  = source->slider_pos_horizontal;
812    destination->slider_pos_vertical    = source->slider_pos_vertical;
813    destination->coords         = source->coords;
814}
815
816
817static void reload_helix_cb() { 
818    const char *err = ED4_ROOT->helix->init(GLOBAL_gb_main);
819    if (err) aw_message(err);
820    ED4_request_full_refresh();
821}
822
823
824static void reload_ecoli_cb() {
825    const char *err = ED4_ROOT->ecoli_ref->init(GLOBAL_gb_main);
826    if (err) aw_message(err);
827    ED4_request_full_refresh();
828}
829
830// ---------------------------------------
831//      recursion through all species
832
833typedef ARB_ERROR (*ED4_Species_Callback)(GBDATA*, AW_CL);
834
835static ARB_ERROR do_sth_with_species(ED4_base *base, AW_CL cl_spec_cb, AW_CL cd) {
836    ARB_ERROR error = NULL;
837
838    if (base->is_species_manager()) {
839        ED4_Species_Callback       cb                    = (ED4_Species_Callback)cl_spec_cb;
840        ED4_species_manager       *species_manager       = base->to_species_manager();
841        ED4_species_name_terminal *species_name_terminal = species_manager->search_spec_child_rek(ED4_L_SPECIES_NAME)->to_species_name_terminal();
842
843        if (species_name_terminal->get_species_pointer()) {
844            char *species_name = GB_read_as_string(species_name_terminal->get_species_pointer());
845
846            e4_assert(species_name);
847            GBDATA *species = GBT_find_species(GLOBAL_gb_main, species_name);
848
849            error = species
850                ? cb(species, cd)
851                : GB_append_exportedError(GBS_global_string("can't find species '%s'", species_name));
852
853            free(species_name);
854        }
855    }
856
857    return error;
858}
859
860
861static ARB_ERROR ED4_with_all_loaded_species(ED4_Species_Callback cb, AW_CL cd) {
862    return ED4_ROOT->root_group_man->route_down_hierarchy(do_sth_with_species, (AW_CL)cb, cd);
863}
864
865static bool has_species_name(ED4_base *base, AW_CL cl_species_name) {
866    ED4_species_name_terminal *name_term = base->to_species_name_terminal();
867    GBDATA *gbd = name_term->get_species_pointer();
868
869    if (gbd) {
870        const char *name = GB_read_char_pntr(gbd);
871        e4_assert(name);
872        return strcmp(name, (const char*)cl_species_name)==0;
873    }
874
875    return false;
876}
877
878ED4_species_name_terminal *ED4_find_species_name_terminal(const char *species_name)
879{
880    ED4_base *base = ED4_ROOT->root_group_man->find_first_that(ED4_L_SPECIES_NAME, has_species_name, (AW_CL)species_name);
881
882    return base ? base->to_species_name_terminal() : 0;
883}
884
885static char *get_group_consensus(const char *species_name, PosRange range) {
886    ED4_species_name_terminal *name_term = ED4_find_species_name_terminal(species_name);
887    char *consensus = 0;
888
889    if (name_term) {
890        ED4_abstract_group_manager *group_man = name_term->get_parent(ED4_level(ED4_L_GROUP|ED4_L_ROOTGROUP))->to_abstract_group_manager();
891        if (group_man) {
892            consensus = group_man->table().build_consensus_string(range);
893        }
894    }
895
896    return consensus;
897}
898
899static bool get_selected_range(PosRange& range) {
900    ED4_selected_elem *listElem = ED4_ROOT->selected_objects->head();
901    if (listElem) {
902        ED4_sequence_terminal *seqTerm = listElem->elem()->object->corresponding_sequence_terminal();
903        return ED4_get_selected_range(seqTerm, range);
904    }
905    return false;
906}
907
908static ED4_selected_elem *curr_aligner_elem = 0;
909
910static GBDATA *get_next_selected_species() {
911    if (!curr_aligner_elem) return 0;
912
913    ED4_species_manager *specMan = curr_aligner_elem->elem()->object->containing_species_manager();
914    curr_aligner_elem = curr_aligner_elem->next();
915    return specMan->get_species_pointer();
916}
917
918static GBDATA *get_first_selected_species(int *total_no_of_selected_species)
919{
920    int selected = ED4_ROOT->selected_objects->size();
921
922    if (total_no_of_selected_species) {
923        *total_no_of_selected_species = selected;
924    }
925
926    if (selected) {
927        curr_aligner_elem = ED4_ROOT->selected_objects->head();
928    }
929    else {
930        curr_aligner_elem = 0;
931    }
932
933    return get_next_selected_species();
934}
935
936struct AlignDataAccess dataAccess_4_aligner = {
937    1,                                              // default is to do a refresh
938    ED4_trigger_instant_refresh,                    // with this function
939    get_group_consensus,                            // aligner fetches consensus of group of species via this function
940    get_selected_range,                             // aligner fetches column range of selection via this function
941    get_first_selected_species,                     // aligner fetches first and..
942    get_next_selected_species,                      // .. following selected species via this functions
943    0,                                              // AW_helix (needed for island_hopping)
944    NULL,                                           // gb_main
945};
946static ARB_ERROR ED4_delete_temp_entries(GBDATA *species, AW_CL cl_alignment_name) {
947    return FastAligner_delete_temp_entries(species, (GB_CSTR)cl_alignment_name);
948}
949
950static void ED4_remove_faligner_entries(AW_window *, AW_CL, AW_CL) {
951    ARB_ERROR error = GB_begin_transaction(GLOBAL_gb_main);
952    if (!error) error = ED4_with_all_loaded_species(ED4_delete_temp_entries, (AW_CL)ED4_ROOT->alignment_name);
953    GB_end_transaction_show_error(GLOBAL_gb_main, error, aw_message);
954}
955
956#if defined(DEBUG) && 0
957
958void ED4_testSplitNMerge(AW_window *aw, AW_CL, AW_CL)
959{
960    AW_root *root = aw->get_root();
961    char *name;
962    GBDATA *species;
963    GBDATA *gbd;
964    char *data;
965    long length;
966
967    GB_ERROR error = GB_begin_transaction(gb_main);
968    char *ali = ED4_ROOT->alignment_name;
969
970    if (!error)
971    {
972        name = root->awar(AWAR_SPECIES_NAME)->read_string();
973        species = GBT_find_species(gb_main, name);
974        gbd = species ? GBT_read_sequence(species, ali) : NULL;
975        data = gbd ? GB_read_string(gbd) : NULL;
976        length = gbd ? GB_read_string_count(gbd) : NULL;
977
978        if (data)
979        {
980            char *newData = AWTC_testConstructSequence(data);
981
982            if (newData)
983            {
984                error = GB_write_string(gbd, newData);
985                delete [] newData;
986            }
987        }
988        else
989        {
990            error = GB_get_error();
991            if (!error) error = GB_export_error("Can't read data of '%s'", name);
992        }
993
994        delete name;
995        delete data;
996    }
997
998    GB_end_transaction_show_error(gb_main, error, aw_message);
999}
1000
1001#endif
1002
1003static void toggle_helix_for_SAI(AW_window *aww, AW_CL, AW_CL) {
1004    ED4_LocalWinContext  uses(aww);
1005    ED4_cursor          *cursor = &current_cursor();
1006
1007    if (cursor->in_SAI_terminal()) {
1008        ED4_sequence_terminal      *sai_term      = cursor->owner_of_cursor->to_sequence_terminal();
1009        ED4_sequence_info_terminal *sai_info_term = sai_term->parent->search_spec_child_rek(ED4_L_SEQUENCE_INFO)->to_sequence_info_terminal();
1010
1011        GBDATA         *gb_sai_data = sai_info_term->data();
1012        GB_transaction  ta(gb_sai_data);
1013
1014        GBDATA *gb_sai      = GB_get_grandfather(gb_sai_data);
1015        GBDATA *gb_disp_sec = GB_searchOrCreate_int(gb_sai, "showsec", 0);
1016
1017        bool show_sec = 1-bool(GB_read_int(gb_disp_sec));
1018        GB_ERROR error = GB_write_int(gb_disp_sec, show_sec);
1019        if (!error) {
1020            sai_term->set_secstruct_display(show_sec);
1021            sai_term->request_refresh();
1022        }
1023        if (error) aw_message(error);
1024    }
1025    else {
1026        aw_message("Please select an SAI");
1027    }
1028}
1029
1030static void title_mode_changed(AW_root *aw_root, AW_window *aww)
1031{
1032    int title_mode = aw_root->awar(AWAR_EDIT_TITLE_MODE)->read_int();
1033
1034    if (title_mode==0) {
1035        aww->set_info_area_height(57);
1036    }
1037    else {
1038        aww->set_info_area_height(170);
1039    }
1040}
1041
1042static void ED4_undo_redo(AW_window *aww, AW_CL undo_type) {
1043    ED4_LocalWinContext uses(aww);
1044    GB_ERROR error = GB_undo(GLOBAL_gb_main, (GB_UNDO_TYPE)undo_type);
1045
1046    if (error) {
1047        aw_message(error);
1048    }
1049    else {
1050        GB_begin_transaction(GLOBAL_gb_main);
1051        GB_commit_transaction(GLOBAL_gb_main);
1052        ED4_cursor *cursor = &current_cursor();
1053        if (cursor->owner_of_cursor) cursor->owner_of_cursor->request_refresh();
1054    }
1055}
1056
1057static void ED4_clear_errors(AW_window *aww, AW_CL) {
1058    aw_clear_message_cb(aww);
1059}
1060
1061static AW_window *ED4_zoom_message_window(AW_root *root, AW_CL)
1062{
1063    AW_window_simple *aws = new AW_window_simple;
1064
1065    aws->init(root, "ZOOM_ERR_MSG", "Errors and warnings");
1066    aws->load_xfig("edit4/message.fig");
1067
1068    aws->callback((AW_CB0)AW_POPDOWN);
1069    aws->at("hide");
1070    aws->create_button("HIDE", "HIDE");
1071
1072    aws->callback(ED4_clear_errors, (AW_CL)0);
1073    aws->at("clear");
1074    aws->create_button("CLEAR", "CLEAR");
1075
1076    aws->at("errortext");
1077    aws->create_text_field(AWAR_ERROR_MESSAGES);
1078
1079    return (AW_window *)aws;
1080}
1081
1082
1083static char *cat(char *toBuf, const char *s1, const char *s2)
1084{
1085    char *buf = toBuf;
1086
1087    while ((*buf++=*s1++)!=0) ;
1088    buf--;
1089    while ((*buf++=*s2++)!=0) ;
1090
1091    return toBuf;
1092}
1093
1094static void insert_search_fields(AW_window_menu_modes *awmm,
1095                                 const char *label_prefix, const char *macro_prefix,
1096                                 const char *pattern_awar_name, const char *show_awar_name,
1097                                 int short_form, ED4_SearchPositionType type, ED4_window *ed4w)
1098{
1099    char buf[200];
1100
1101    if (!short_form) {
1102        awmm->at(cat(buf, label_prefix, "search"));
1103        awmm->create_input_field(pattern_awar_name, 30);
1104    }
1105
1106    awmm->at(cat(buf, label_prefix, "n"));
1107    awmm->callback(ED4_search_cb, ED4_encodeSearchDescriptor(+1, type), (AW_CL)ed4w);
1108    awmm->create_button(cat(buf, macro_prefix, "_SEARCH_NEXT"), "#edit/next.xpm");
1109
1110    awmm->at(cat(buf, label_prefix, "l"));
1111    awmm->callback(ED4_search_cb, ED4_encodeSearchDescriptor(-1, type), (AW_CL)ed4w);
1112    awmm->create_button(cat(buf, macro_prefix, "_SEARCH_LAST"), "#edit/last.xpm");
1113
1114    awmm->at(cat(buf, label_prefix, "d"));
1115    awmm->callback(ED4_popup_search_window, (AW_CL)type);
1116    awmm->create_button(cat(buf, macro_prefix, "_SEARCH_DETAIL"), "#edit/detail.xpm");
1117
1118    awmm->at(cat(buf, label_prefix, "s"));
1119    awmm->create_toggle(show_awar_name);
1120}
1121
1122static void ED4_set_protection(AW_window *aww, AW_CL cd1, AW_CL /* cd2 */) {
1123    ED4_LocalWinContext uses(aww);
1124    ED4_cursor *cursor = &current_cursor();
1125    GB_ERROR    error  = 0;
1126
1127    if (cursor->owner_of_cursor) {
1128        int                         wanted_protection = int(cd1);
1129        ED4_sequence_terminal      *seq_term          = cursor->owner_of_cursor->to_sequence_terminal();
1130        ED4_sequence_info_terminal *seq_info_term     = seq_term->parent->search_spec_child_rek(ED4_L_SEQUENCE_INFO)->to_sequence_info_terminal();
1131        GBDATA                     *gbd               = seq_info_term->data();
1132
1133        GB_push_transaction(gbd);
1134
1135        GB_push_my_security(gbd);
1136        error = GB_write_security_write(gbd, wanted_protection);
1137        GB_pop_my_security(gbd);
1138
1139        error = GB_end_transaction(gbd, error);
1140    }
1141    else {
1142        error = "No species selected";
1143    }
1144
1145    if (error) aw_message(error);
1146}
1147
1148enum MenuSelectType {
1149    ED4_MS_NONE,
1150    ED4_MS_ALL,
1151    ED4_MS_INVERT,
1152    ED4_MS_INVERT_GROUP,
1153    ED4_MS_UNMARK_ALL,
1154    ED4_MS_MARK_SELECTED,
1155    ED4_MS_UNMARK_SELECTED,
1156    ED4_MS_SELECT_MARKED,
1157    ED4_MS_DESELECT_MARKED,
1158    ED4_MS_TOGGLE_BLOCKTYPE
1159};
1160
1161static void ED4_menu_select(AW_window *aww, AW_CL type, AW_CL) {
1162    GB_transaction ta(GLOBAL_gb_main);
1163    MenuSelectType select = MenuSelectType(type);
1164    ED4_multi_species_manager *middle_multi_man = ED4_ROOT->middle_area_man->get_multi_species_manager();
1165
1166    e4_assert(middle_multi_man);
1167
1168    switch (select) {
1169        case ED4_MS_NONE: {
1170            if (ED4_getBlocktype()!=ED4_BT_NOBLOCK) {
1171                ED4_ROOT->deselect_all();
1172                ED4_setBlocktype(ED4_BT_NOBLOCK);
1173            }
1174            break;
1175        }
1176        case ED4_MS_ALL: {
1177            middle_multi_man->select_all(true); // only species
1178            ED4_correctBlocktypeAfterSelection();
1179            break;
1180        }
1181        case ED4_MS_INVERT: {
1182            middle_multi_man->invert_selection_of_all_species();
1183            ED4_correctBlocktypeAfterSelection();
1184            break;
1185        }
1186        case ED4_MS_SELECT_MARKED: {
1187            middle_multi_man->marked_species_select(true);
1188            ED4_correctBlocktypeAfterSelection();
1189            break;
1190        }
1191        case ED4_MS_DESELECT_MARKED: {
1192            middle_multi_man->marked_species_select(false);
1193            ED4_correctBlocktypeAfterSelection();
1194            break;
1195        }
1196        case ED4_MS_UNMARK_ALL: {
1197            GBT_mark_all(GLOBAL_gb_main, 0);
1198            break;
1199        }
1200        case ED4_MS_MARK_SELECTED: {
1201            middle_multi_man->selected_species_mark(true);
1202            ED4_correctBlocktypeAfterSelection();
1203            break;
1204        }
1205        case ED4_MS_UNMARK_SELECTED: {
1206            middle_multi_man->selected_species_mark(false);
1207            ED4_correctBlocktypeAfterSelection();
1208            break;
1209        }
1210        case ED4_MS_INVERT_GROUP: {
1211            ED4_cursor *cursor = &ED4_ROOT->first_window->get_matching_ed4w(aww)->cursor;
1212            int done = 0;
1213
1214            if (cursor->owner_of_cursor) {
1215                ED4_multi_species_manager *multi_man = cursor->owner_of_cursor->get_parent(ED4_L_MULTI_SPECIES)->to_multi_species_manager();
1216
1217                multi_man->invert_selection_of_all_species();
1218                ED4_correctBlocktypeAfterSelection();
1219                done = 1;
1220            }
1221
1222            if (!done) {
1223                aw_message("Place cursor into group");
1224            }
1225            break;
1226        }
1227        case ED4_MS_TOGGLE_BLOCKTYPE: {
1228            ED4_toggle_block_type();
1229            break;
1230        }
1231        default: {
1232            e4_assert(0);
1233            break;
1234        }
1235    }
1236
1237    ED4_request_full_refresh();
1238}
1239
1240static void ED4_menu_perform_block_operation(AW_window */*aww*/, AW_CL type, AW_CL) {
1241    ED4_perform_block_operation(ED4_blockoperation_type(type));
1242}
1243
1244static void modes_cb(AW_window*, ED4_species_mode smode) {
1245    ED4_ROOT->species_mode = smode;
1246    for (ED4_window *win = ED4_ROOT->first_window; win; win = win->next) {
1247        win->aww->select_mode(smode);
1248    }
1249}
1250
1251void ED4_no_dangerous_modes() {
1252    if (ED4_ROOT->species_mode == ED4_SM_KILL) {
1253        modes_cb(NULL, ED4_SM_MOVE);
1254    }
1255}
1256
1257void ED4_init_aligner_data_access(AlignDataAccess *data_access) {
1258    GB_ERROR  error          = GB_push_transaction(GLOBAL_gb_main);
1259    char     *alignment_name = GBT_get_default_alignment(GLOBAL_gb_main);
1260    long      alilen         = GBT_get_alignment_len(GLOBAL_gb_main, alignment_name);
1261
1262    data_access->gb_main = GLOBAL_gb_main;
1263
1264    if (alilen<=0) error = GB_await_error();
1265    else {
1266        char   *helix_string = 0;
1267        char   *helix_name   = GBT_get_default_helix(GLOBAL_gb_main);
1268        GBDATA *gb_helix_con = GBT_find_SAI(GLOBAL_gb_main, helix_name);
1269        if (gb_helix_con) {
1270            GBDATA *gb_helix = GBT_read_sequence(gb_helix_con, alignment_name);
1271            if (gb_helix) helix_string = GB_read_string(gb_helix);
1272        }
1273        free(helix_name);
1274        freeset(data_access->helix_string, helix_string);
1275    }
1276
1277    free(alignment_name);
1278    error = GB_end_transaction(GLOBAL_gb_main, error);
1279    if (error) aw_message(error);
1280}
1281
1282static AW_window *ED4_create_faligner_window(AW_root *awr, AW_CL cl_AlignDataAccess) {
1283    AlignDataAccess *data_access = (AlignDataAccess*)cl_AlignDataAccess;
1284
1285#if defined(DEBUG)
1286    static AlignDataAccess *last_data_access = NULL;
1287
1288    e4_assert(!last_data_access || (last_data_access == data_access)); // there shall be only one AlignDataAccess
1289    last_data_access = data_access;
1290#endif
1291
1292    static AW_window *aws = NULL;
1293    if (!aws) {
1294        ED4_init_aligner_data_access(data_access);
1295        aws = FastAligner_create_window(awr, data_access);
1296    }
1297    return aws;
1298}
1299
1300static void ED4_save_properties(AW_window *aw, AW_CL cl_mode, AW_CL) {
1301    int mode = (int)cl_mode;
1302
1303    AW_save_specific_properties(aw, ED4_propertyName(mode));
1304}
1305
1306void ED4_popup_gc_window(AW_window *awp, AW_gc_manager gcman) {
1307    typedef std::map<AW_gc_manager, AW_window*> gcwin;
1308    static gcwin win;
1309
1310    gcwin::iterator found = win.find(gcman);
1311
1312    AW_window *aww = NULL;
1313    if (found == win.end()) {
1314        aww        = AW_create_gc_window(awp->get_root(), gcman);
1315        win[gcman] = aww;
1316    }
1317    else {
1318        aww = win[gcman];
1319    }
1320    aww->activate();
1321}
1322
1323static void refresh_on_gc_change_cb() {
1324    ED4_expose_recalculations();
1325    ED4_request_full_instant_refresh();
1326}
1327
1328ED4_returncode ED4_root::generate_window(AW_device **device, ED4_window **new_window) {
1329    {
1330        ED4_window *ed4w = first_window;
1331
1332        while (ed4w) { // before creating a window look for a hidden window
1333            if (ed4w->is_hidden) {
1334                ed4w->aww->show();
1335                ed4w->is_hidden = false;
1336                return ED4_R_BREAK;
1337            }
1338            ed4w = ed4w->next;
1339        }
1340    }
1341
1342    if (ED4_window::no_of_windows == MAXWINDOWS)                            // no more than 5 windows allowed
1343    {
1344        aw_message(GBS_global_string("Restricted to %i windows", MAXWINDOWS));
1345        return ED4_R_BREAK;
1346    }
1347
1348    AW_window_menu_modes *awmm = new AW_window_menu_modes;
1349    {
1350        int   winNum   = ED4_window::no_of_windows+1;
1351        char *winName  = winNum>1 ? GBS_global_string_copy("ARB_EDIT4_%i", winNum) : strdup("ARB_EDIT4");
1352        char *winTitle = GBS_global_string_copy("ARB_EDIT4 *%d* [%s]", winNum, alignment_name);
1353
1354        awmm->init(aw_root, winName, winTitle, 800, 450);
1355
1356        free(winTitle);
1357        free(winName);
1358    }
1359
1360    *device     = awmm->get_device(AW_MIDDLE_AREA); // points to Middle Area device
1361    *new_window = ED4_window::insert_window(awmm);   // append to window list
1362
1363    e4_assert(ED4_window::no_of_windows >= 1);
1364    bool clone = ED4_window::no_of_windows>1;
1365    if (!clone) {                                   // this is the first window
1366        AW_init_color_group_defaults("arb_edit4");
1367    }
1368    else { // additional edit windows
1369        copy_window_struct(first_window, *new_window);
1370    }
1371
1372    ED4_LocalWinContext uses(*new_window);
1373
1374    // each window has its own gc-manager
1375    gc_manager = AW_manage_GC(awmm,
1376                              "ARB_EDIT4",                   // but all gc-managers use the same colors
1377                              *device,
1378                              ED4_G_STANDARD,                // GC_Standard configuration
1379                              ED4_G_DRAG,
1380                              AW_GCM_DATA_AREA,
1381                              makeWindowCallback(refresh_on_gc_change_cb), // callback triggering refresh on gc-change
1382                              true,                          // use color groups
1383
1384                              "#f8f8f8",
1385                              "STANDARD$black",              // Standard Color showing sequences
1386                              "#SEQUENCES (0)$#505050",      // default color for sequences (color 0)
1387                              "+-HELIX (1)$#8E0000",  "+-COLOR 2$#0000dd",    "-COLOR 3$#00AA55",
1388                              "+-COLOR 4$#80f",       "+-COLOR 5$#c0a020",    "-COLOR 6$grey",
1389                              "+-COLOR 7$#ff0000",    "+-COLOR 8$#44aaff",    "-COLOR 9$#ffaa00",
1390
1391                              "+-RANGE 0$#FFFFFF",    "+-RANGE 1$#F0F0F0",    "-RANGE 2$#E0E0E0",
1392                              "+-RANGE 3$#D8D8D8",    "+-RANGE 4$#D0D0D0",    "-RANGE 5$#C8C8C8",
1393                              "+-RANGE 6$#C0C0C0",    "+-RANGE 7$#B8B8B8",    "-RANGE 8$#B0B0B0",
1394                              "-RANGE 9$#A0A0A0",
1395
1396                              // colors used to Paint search patterns
1397                              // (do not change the names of these gcs)
1398                              "+-User1$#B8E2F8",      "+-User2$#B8E2F8",      "-Probe$#B8E2F8", // see also SEC_graphic::init_devices
1399                              "+-Primer(l)$#A9FE54",  "+-Primer(r)$#A9FE54",  "-Primer(g)$#A9FE54",
1400                              "+-Sig(l)$#DBB0FF",     "+-Sig(r)$#DBB0FF",     "-Sig(g)$#DBB0FF",
1401
1402                              "+-MISMATCHES$#FF9AFF", "-CURSOR$#FF0080",
1403                              "+-MARKED$#f4f8e0",     "-SELECTED$#FFFF80",
1404
1405                              NULL);
1406
1407    // since the gc-managers of all EDIT4-windows point to the same window properties,
1408    // changing fonts and colors is always done on first gc-manager
1409    static AW_gc_manager first_gc_manager = 0;
1410    if (!first_gc_manager) first_gc_manager = gc_manager;
1411
1412    // --------------
1413    //      File
1414
1415#if defined(DEBUG)
1416    AWT_create_debug_menu(awmm);
1417#endif // DEBUG
1418
1419    awmm->create_menu("File", "F", AWM_ALL);
1420
1421    awmm->insert_menu_topic("new_win",        "New Editor Window",     "W", 0, AWM_ALL, ED4_new_editor_window);
1422    awmm->insert_menu_topic("save_config",    "Save Configuration",    "S", 0, AWM_ALL, makeWindowCallback(ED4_save_configuration, false));
1423    awmm->insert_menu_topic("save_config_as", "Save Configuration As", "A", 0, AWM_ALL, AW_POPUP,                      (AW_CL) ED4_save_configuration_as_open_window, (int)0);
1424    awmm->sep______________();
1425    awmm->insert_menu_topic("load_config",   "Load Configuration",   "L", 0, AWM_ALL, AW_POPUP,           (AW_CL)ED4_start_editor_on_old_configuration, 0);
1426    awmm->insert_menu_topic("reload_config", "Reload Configuration", "R", 0, AWM_ALL, ED4_restart_editor, 0,                                            0);
1427    insert_macro_menu_entry(awmm, true);
1428    awmm->sep______________();
1429    GDE_load_menu(awmm, AWM_ALL, "Print");
1430    awmm->sep______________();
1431
1432    if (clone) awmm->insert_menu_topic("close", "CLOSE", "C", 0, AWM_ALL, ED4_quit_editor);
1433    else       awmm->insert_menu_topic("quit",   "QUIT",  "Q", 0, AWM_ALL, ED4_quit_editor);
1434
1435    // ----------------
1436    //      Create
1437
1438    awmm->create_menu("Create", "C", AWM_ALL);
1439    awmm->insert_menu_topic("create_species",                "Create new species",                "n", 0, AWM_ALL, makeCreateWindowCallback(ED4_create_new_seq_window, CREATE_NEW_SPECIES));
1440    awmm->insert_menu_topic("create_species_from_consensus", "Create new species from consensus", "u", 0, AWM_ALL, makeCreateWindowCallback(ED4_create_new_seq_window, CREATE_FROM_CONSENSUS));
1441    awmm->insert_menu_topic("copy_species",                  "Copy current species",              "C", 0, AWM_ALL, makeCreateWindowCallback(ED4_create_new_seq_window, COPY_SPECIES));
1442    awmm->sep______________();
1443    awmm->insert_menu_topic("create_group",           "Create new Group",              "G", 0, AWM_ALL, group_species_cb, 0, 0);
1444    awmm->insert_menu_topic("create_groups_by_field", "Create new groups using Field", "F", 0, AWM_ALL, group_species_cb, 1, 0);
1445
1446    // --------------
1447    //      Edit
1448
1449    awmm->create_menu("Edit", "E", AWM_ALL);
1450    awmm->insert_menu_topic("refresh",      "Refresh [Ctrl-L]",           "f", 0, AWM_ALL, (AW_CB)ED4_request_full_refresh,       0, 0);
1451    awmm->insert_menu_topic("load_current", "Load current species [GET]", "G", 0, AWM_ALL, ED4_get_and_jump_to_current_from_menu, 0, 0);
1452    awmm->insert_menu_topic("load_marked",  "Load marked species",        "m", 0, AWM_ALL, ED4_get_marked_from_menu,              0, 0);
1453    awmm->sep______________();
1454    awmm->insert_menu_topic("refresh_ecoli",       "Reload Ecoli sequence",        "E", "ecoliref.hlp", AWM_ALL, (AW_CB)reload_ecoli_cb, 0, 0);
1455    awmm->insert_menu_topic("refresh_helix",       "Reload Helix",                 "H", "helix.hlp",    AWM_ALL, (AW_CB)reload_helix_cb, 0, 0);
1456    awmm->insert_menu_topic("helix_jump_opposite", "Jump helix opposite [Ctrl-J]", "J", 0,              AWM_ALL, ED4_helix_jump_opposite);
1457    awmm->sep______________();
1458
1459    awmm->insert_sub_menu("Set protection of current ", "p");
1460    {
1461        char macro[] = "to_0",
1462            topic[] = ".. to 0",
1463            hotkey[] = "0";
1464
1465        for (char i='0'; i<='6'; i++) {
1466            macro[3] = topic[6] = hotkey[0] = i;
1467            awmm->insert_menu_topic(macro, topic, hotkey, "security.hlp", AWM_ALL, ED4_set_protection, AW_CL(i-'0'), 0);
1468        }
1469    }
1470    awmm->close_sub_menu();
1471
1472#if !defined(NDEBUG) && 0
1473    awmm->insert_menu_topic(0,               "Test (test split & merge)", "T", 0, AWM_ALL, ED4_testSplitNMerge, 1, 0);
1474#endif
1475   
1476    awmm->sep______________();
1477    awmm->insert_menu_topic("fast_aligner",       INTEGRATED_ALIGNERS_TITLE,             "I", "faligner.hlp",     AWM_ALL,            AW_POPUP,                               (AW_CL)ED4_create_faligner_window, (AW_CL)&dataAccess_4_aligner);
1478    awmm->insert_menu_topic("fast_align_set_ref", "Set aligner reference [Ctrl-R]",      "R", "faligner.hlp",     AWM_ALL,            (AW_CB)FastAligner_set_reference_species, (AW_CL)aw_root,                    0);
1479    awmm->insert_menu_topic("align_sequence",     "Old aligner from ARB_EDIT [broken]",  "O", "ne_align_seq.hlp", AWM_DISABLED,       AW_POPUP,                               (AW_CL)create_naligner_window,     0);
1480    awmm->insert_menu_topic("sina",               "SINA (SILVA Incremental Aligner)",    "S", "sina_main.hlp",    sina_mask(aw_root), show_sina_window,                       (AW_CL)&dataAccess_4_aligner,      0);
1481    awmm->insert_menu_topic("del_ali_tmp",        "Remove all aligner Entries",          "v", 0,                  AWM_ALL,            ED4_remove_faligner_entries,            1,                                 0);
1482    awmm->sep______________();
1483    awmm->insert_menu_topic("missing_bases", "Dot potentially missing bases", "D", "missbase.hlp", AWM_EXP, ED4_popup_dot_missing_bases_window, 0, 0);
1484
1485    if (alignment_type == GB_AT_RNA) { // if the database contains valid alignment of rRNA sequences
1486        awmm->sep______________();
1487        awmm->insert_menu_topic("sec_edit", "Edit secondary structure", "c", "arb_secedit.hlp", AWM_ALL, ED4_start_plugin, (AW_CL)GLOBAL_gb_main, (AW_CL)"SECEDIT");
1488#if defined(ARB_OPENGL)
1489        awmm->insert_menu_topic("rna3d", "View 3D molecule", "3", "rna3d_general.hlp", AWM_ALL, ED4_start_plugin, (AW_CL)GLOBAL_gb_main, (AW_CL)"RNA3D");
1490#endif // ARB_OPENGL
1491#if defined(DEBUG)
1492        awmm->insert_menu_topic("noplugin", "DEBUG: call unknown plugin", "u", 0, AWM_ALL, ED4_start_plugin, (AW_CL)GLOBAL_gb_main, (AW_CL)"testplugin");
1493#endif // DEBUG
1494    }
1495
1496    // --------------
1497    //      View
1498
1499    awmm->create_menu("View", "V", AWM_ALL);
1500    awmm->insert_sub_menu("Search", "S");
1501    {
1502        int         s;
1503        const char *hotkeys  = "12Poiclrg";
1504        char        hotkey[] = "_";
1505
1506        e4_assert(strlen(hotkeys) == SEARCH_PATTERNS);
1507
1508        for (s=0; s<SEARCH_PATTERNS; s++) {
1509            ED4_SearchPositionType type = ED4_SearchPositionType(s);
1510            const char *id = ED4_SearchPositionTypeId[type];
1511            int len = strlen(id);
1512            char *macro_name = GB_give_buffer(2*(len+8));
1513            char *menu_entry_name = macro_name+(len+8);
1514
1515#ifndef NDEBUG
1516            memset(macro_name, 0, 2*(len+8)); // to avoid memchk-warning
1517#endif
1518            sprintf(macro_name, "%s_SEARCH", id);
1519            char *p = macro_name;
1520            while (1) {
1521                char c = *p++;
1522                if (!c) break;
1523                p[-1] = toupper(c);
1524            }
1525            sprintf(menu_entry_name, "%s Search", id);
1526
1527            hotkey[0] = hotkeys[s];
1528            awmm->insert_menu_topic(awmm->local_id(macro_name), menu_entry_name, hotkey, "e4_search.hlp", AWM_ALL, ED4_popup_search_window, AW_CL(type));
1529        }
1530    }
1531    awmm->close_sub_menu();
1532    awmm->sep______________();
1533    awmm->insert_sub_menu("Cursor position ", "p");
1534    awmm->insert_menu_topic("store_curpos",   "Store cursor position",    "S", 0, AWM_ALL, ED4_store_curpos);
1535    awmm->insert_menu_topic("restore_curpos", "Restore cursor position ", "R", 0, AWM_ALL, ED4_restore_curpos);
1536    awmm->insert_menu_topic("clear_curpos",   "Clear stored positions",   "C", 0, AWM_ALL, makeWindowCallback(ED4_clear_stored_curpos));
1537    awmm->close_sub_menu();
1538
1539    awmm->sep______________();
1540    awmm->insert_menu_topic("change_cursor", "Change cursor type",                "t", 0,                   AWM_ALL, ED4_change_cursor);
1541    awmm->insert_menu_topic("show_all",      "Show all bases ",                   "a", "set_reference.hlp", AWM_ALL, ED4_set_reference_species, 1, 0);
1542    awmm->insert_menu_topic("show_diff",     "Show only differences to selected", "d", "set_reference.hlp", AWM_ALL, ED4_set_reference_species, 0, 0);
1543    awmm->sep______________();
1544    awmm->insert_menu_topic("enable_col_stat",  "Activate column statistics", "v", "st_ml.hlp", AWM_EXP, ED4_activate_col_stat,            0, 0);
1545    awmm->insert_menu_topic("disable_col_stat", "Disable column statistics",  "i", "st_ml.hlp", AWM_EXP, ED4_disable_col_stat,             0, 0);
1546    awmm->insert_menu_topic("detail_col_stat",  "Toggle detailed Col.-Stat.", "C", "st_ml.hlp", AWM_EXP, ED4_toggle_detailed_column_stats, 0, 0);
1547    awmm->insert_menu_topic("dcs_threshold",    "Set threshold for D.c.s.",   "f", "st_ml.hlp", AWM_EXP, ED4_set_col_stat_threshold,       0, 0);
1548    awmm->sep______________();
1549    awmm->insert_menu_topic("visualize_SAI", "Visualize SAIs",                "z", "visualizeSAI.hlp",   AWM_ALL, AW_POPUP,             (AW_CL)ED4_createVisualizeSAI_window, 0);
1550    awmm->insert_menu_topic("toggle_saisec", "Toggle secondary info for SAI", "o", "toggle_secinfo.hlp", AWM_ALL, toggle_helix_for_SAI, 0,                                    0);
1551
1552    // Enable ProteinViewer only for DNA sequence type
1553    if (alignment_type == GB_AT_DNA) {
1554        awmm->insert_menu_topic("Protein_Viewer", "Protein Viewer", "w", "proteinViewer.hlp", AWM_ALL, AW_POPUP, (AW_CL)ED4_CreateProteinViewer_window, 0);
1555    }
1556
1557    // ---------------
1558    //      Block
1559
1560    awmm->create_menu("Block", "B", AWM_ALL);
1561
1562    awmm->insert_menu_topic("select_marked",   "Select marked species",   "e", "e4_block.hlp", AWM_ALL, ED4_menu_select, AW_CL(ED4_MS_SELECT_MARKED),   0);
1563    awmm->insert_menu_topic("deselect_marked", "Deselect marked species", "k", "e4_block.hlp", AWM_ALL, ED4_menu_select, AW_CL(ED4_MS_DESELECT_MARKED), 0);
1564    awmm->insert_menu_topic("select_all",      "Select all species",      "S", "e4_block.hlp", AWM_ALL, ED4_menu_select, AW_CL(ED4_MS_ALL),             0);
1565    awmm->insert_menu_topic("deselect_all",    "Deselect all",            "D", "e4_block.hlp", AWM_ALL, ED4_menu_select, AW_CL(ED4_MS_NONE),            0);
1566    awmm->sep______________();
1567    awmm->insert_menu_topic("mark_selected",   "Mark selected species",   "M", "e4_block.hlp", AWM_ALL, ED4_menu_select, AW_CL(ED4_MS_MARK_SELECTED),   0);
1568    awmm->insert_menu_topic("unmark_selected", "Unmark selected species", "n", "e4_block.hlp", AWM_ALL, ED4_menu_select, AW_CL(ED4_MS_UNMARK_SELECTED), 0);
1569    awmm->insert_menu_topic("unmark_all",      "Unmark all species",      "U", "e4_block.hlp", AWM_ALL, ED4_menu_select, AW_CL(ED4_MS_UNMARK_ALL),      0);
1570    awmm->sep______________();
1571    awmm->insert_menu_topic("invert_all",   "Invert selected species", "I", "e4_block.hlp", AWM_ALL, ED4_menu_select, AW_CL(ED4_MS_INVERT),       0);
1572    awmm->insert_menu_topic("invert_group", "Invert group",            "g", "e4_block.hlp", AWM_ALL, ED4_menu_select, AW_CL(ED4_MS_INVERT_GROUP), 0);
1573    awmm->sep______________();
1574    awmm->insert_menu_topic("lowcase", "Change to lower case ", "w", "e4_block.hlp", AWM_ALL, ED4_menu_perform_block_operation, AW_CL(ED4_BO_LOWER_CASE), 0);
1575    awmm->insert_menu_topic("upcase",  "Change to upper case",  "p", "e4_block.hlp", AWM_ALL, ED4_menu_perform_block_operation, AW_CL(ED4_BO_UPPER_CASE), 0);
1576    awmm->sep______________();
1577    awmm->insert_menu_topic("reverse",            "Reverse selection ",    "v", "e4_block.hlp", AWM_ALL, ED4_menu_perform_block_operation, AW_CL(ED4_BO_REVERSE),            0);
1578    awmm->insert_menu_topic("complement",         "Complement selection ", "o", "e4_block.hlp", AWM_ALL, ED4_menu_perform_block_operation, AW_CL(ED4_BO_COMPLEMENT),         0);
1579    awmm->insert_menu_topic("reverse_complement", "Reverse complement",    "t", "e4_block.hlp", AWM_ALL, ED4_menu_perform_block_operation, AW_CL(ED4_BO_REVERSE_COMPLEMENT), 0);
1580    awmm->sep______________();
1581    awmm->insert_menu_topic("unalignBlockLeft",   "Unalign block left",   "a", "e4_block.hlp", AWM_ALL, ED4_menu_perform_block_operation, AW_CL(ED4_BO_UNALIGN_LEFT),   0);
1582    awmm->insert_menu_topic("unalignBlockCenter", "Unalign block center", "c", "e4_block.hlp", AWM_ALL, ED4_menu_perform_block_operation, AW_CL(ED4_BO_UNALIGN_CENTER), 0);
1583    awmm->insert_menu_topic("unalignBlockRight",  "Unalign block right",  "b", "e4_block.hlp", AWM_ALL, ED4_menu_perform_block_operation, AW_CL(ED4_BO_UNALIGN_RIGHT),  0);
1584    awmm->sep______________();
1585    awmm->insert_menu_topic("replace", "Search & Replace ", "h", "e4_replace.hlp", AWM_ALL, AW_POPUP, AW_CL(ED4_create_replace_window), 0);
1586    awmm->insert_menu_topic("setsai",  "Modify SAI ",       "y", "e4_modsai.hlp",  AWM_ALL, AW_POPUP, AW_CL(ED4_create_modsai_window),  0);
1587    awmm->sep______________();
1588    awmm->insert_menu_topic("toggle_block_type", "Exchange: Line<->Column", "x", "e4_block.hlp", AWM_ALL, ED4_menu_select,                  AW_CL(ED4_MS_TOGGLE_BLOCKTYPE), 0);
1589    awmm->insert_menu_topic("shift_left",        "Shift block left ",       "l", "e4_block.hlp", AWM_ALL, ED4_menu_perform_block_operation, AW_CL(ED4_BO_SHIFT_LEFT),       0);
1590    awmm->insert_menu_topic("shift_right",       "Shift block right",       "r", "e4_block.hlp", AWM_ALL, ED4_menu_perform_block_operation, AW_CL(ED4_BO_SHIFT_RIGHT),      0);
1591
1592    // --------------------
1593    //      Properties
1594
1595    awmm->create_menu("Properties", "P", AWM_ALL);
1596
1597    awmm->insert_menu_topic("props_frame",     "Frame Settings ",       "F", 0,                  AWM_ALL, AW_preset_window);
1598    awmm->insert_menu_topic("props_options",   "Editor Options ",       "O", "e4_options.hlp",   AWM_ALL, ED4_create_level_1_options_window);
1599    awmm->insert_menu_topic("props_consensus", "Consensus Definition ", "u", "e4_consensus.hlp", AWM_ALL, ED4_create_consensus_definition_window);
1600    awmm->sep______________();
1601
1602    awmm->insert_menu_topic("props_data",       "Change Colors & Fonts ", "C", 0,                     AWM_ALL, makeWindowCallback(ED4_popup_gc_window, first_gc_manager));
1603    awmm->insert_menu_topic("props_seq_colors", "Sequence color mapping", "S", "sequence_colors.hlp", AWM_ALL, AW_POPUP, (AW_CL)create_seq_colors_window, (AW_CL)sequence_colors);
1604
1605    awmm->sep______________();
1606
1607    if (alignment_type == GB_AT_AA) awmm->insert_menu_topic("props_pfold",     "Protein Match Settings ", "P", "pfold_props.hlp", AWM_ALL, AW_POPUP, (AW_CL)ED4_pfold_create_props_window, (AW_CL)ED4_request_relayout);
1608    else                            awmm->insert_menu_topic("props_helix_sym", "Helix Settings ",         "H", "helixsym.hlp",    AWM_ALL, AW_POPUP, (AW_CL)create_helix_props_window,     (AW_CL)ED4_request_relayout);
1609
1610    awmm->insert_menu_topic("props_key_map", "Key Mappings ",              "K", "nekey_map.hlp", AWM_ALL, AW_POPUP, (AW_CL)create_key_map_window, 0);
1611    awmm->insert_menu_topic("props_nds",     "Select visible info (NDS) ", "D", "ed4_nds.hlp",   AWM_ALL, AW_POPUP, (AW_CL)ED4_create_nds_window, 0);
1612    awmm->sep______________();
1613    AW_insert_common_property_menu_entries(awmm);
1614    awmm->sep______________();
1615    awmm->insert_sub_menu("Save properties ...", "a");
1616    {
1617        static const char * const tag[] = { "save_alispecific_props", "save_alitype_props", "save_props" };
1618        static const char * const entry_type[] = { "alignment specific ", "ali-type specific ", "" };
1619
1620        // check what is the default mode
1621        int default_mode = -1;
1622        for (int mode = 0; mode <= 2; ++mode) {
1623            if (strcmp(GB_path_in_arbprop(ED4_propertyName(mode)), db_name) == 0) {
1624                default_mode = mode;
1625                break;
1626            }
1627        }
1628        if (default_mode == -1) default_mode = 2; // no properties yet -> use 'edit4.arb'
1629
1630        const char *entry = GBS_global_string("Save loaded Properties (%s)", ED4_propertyName(default_mode));
1631        awmm->insert_menu_topic("save_loaded_props", entry, "l", "e4_defaults.hlp", AWM_ALL, ED4_save_properties, (AW_CL)default_mode, 0);
1632        awmm->sep______________();
1633
1634        for (int mode = 2; mode >= 0; --mode) {
1635            char hotkey[] = "x";
1636            hotkey[0]     = "Pta"[mode];
1637            entry         = GBS_global_string("Save %sProperties (%s)", entry_type[mode], ED4_propertyName(mode));
1638            awmm->insert_menu_topic(tag[mode], entry, hotkey, "e4_defaults.hlp", AWM_ALL, ED4_save_properties, (AW_CL)mode, 0);
1639        }
1640    }
1641    awmm->close_sub_menu();
1642
1643    awmm->insert_help_topic("ARB_EDIT4 help",     "E", "e4.hlp", AWM_ALL, makeHelpCallback("e4.hlp"));
1644
1645    // ----------------------------------------------------------------------------------------------------
1646
1647    aw_root->awar_int(AWAR_EDIT_TITLE_MODE)->add_callback((AW_RCB1)title_mode_changed, (AW_CL)awmm);
1648    awmm->set_bottom_area_height(0);   // No bottom area
1649
1650    awmm->auto_space(5, -2);
1651    awmm->shadow_width(3);
1652
1653    int db_pathx, db_pathy;
1654    awmm->get_at_position(&db_pathx, &db_pathy);
1655
1656    awmm->shadow_width(1);
1657    awmm->load_xfig("edit4/editmenu.fig", false);
1658
1659    // --------------------------
1660    //      help /quit /fold
1661
1662    awmm->button_length(0);
1663
1664    awmm->at("quit");
1665    awmm->callback(ED4_quit_editor);
1666    awmm->help_text("quit.hlp");
1667
1668    if (clone) awmm->create_button("CLOSE", "#close.xpm");
1669    else       awmm->create_button("QUIT", "#quit.xpm");
1670
1671    awmm->at("help");
1672    awmm->callback(AW_help_entry_pressed);
1673    awmm->help_text("e4.hlp");
1674    awmm->create_button("HELP", "#help.xpm");
1675
1676    awmm->at("fold");
1677    awmm->help_text("e4.hlp");
1678    awmm->create_toggle(AWAR_EDIT_TITLE_MODE, "#more.xpm", "#less.xpm");
1679
1680    // -------------------
1681    //      positions
1682
1683    awmm->button_length(0);
1684
1685    awmm->at("posTxt");     awmm->create_button(0, "Position");
1686
1687    awmm->button_length(6+1);
1688
1689    awmm->at("ecoliTxt");   awmm->create_button(0, ED4_AWAR_NDS_ECOLI_NAME, 0, "+");
1690
1691    awmm->button_length(0);
1692
1693    awmm->at("baseTxt");    awmm->create_button(0, "Base");
1694    awmm->at("iupacTxt");   awmm->create_button(0, "IUPAC");
1695    awmm->at("helixnrTxt"); awmm->create_button(0, "Helix#");
1696
1697    awmm->at("pos");
1698    awmm->callback((AW_CB)ED4_jump_to_cursor_position, (AW_CL) current_ed4w()->awar_path_for_cursor, AW_CL(ED4_POS_SEQUENCE));
1699    awmm->create_input_field(current_ed4w()->awar_path_for_cursor, 7);
1700
1701    awmm->at("ecoli");
1702    awmm->callback((AW_CB)ED4_jump_to_cursor_position, (AW_CL) current_ed4w()->awar_path_for_Ecoli, AW_CL(ED4_POS_ECOLI));
1703    awmm->create_input_field(current_ed4w()->awar_path_for_Ecoli, 6);
1704
1705    awmm->at("base");
1706    awmm->callback((AW_CB)ED4_jump_to_cursor_position, (AW_CL) current_ed4w()->awar_path_for_basePos, AW_CL(ED4_POS_BASE));
1707    awmm->create_input_field(current_ed4w()->awar_path_for_basePos, 6);
1708
1709    awmm->at("iupac");
1710    awmm->callback((AW_CB)ED4_set_iupac, (AW_CL) current_ed4w()->awar_path_for_IUPAC, AW_CL(0));
1711    awmm->create_input_field(current_ed4w()->awar_path_for_IUPAC, 4);
1712
1713    awmm->at("helixnr");
1714    awmm->callback((AW_CB)ED4_set_helixnr, (AW_CL) current_ed4w()->awar_path_for_helixNr, AW_CL(0));
1715    awmm->create_input_field(current_ed4w()->awar_path_for_helixNr, 5);
1716
1717    // ----------------------------
1718    //      jump/get/undo/redo
1719
1720    awmm->button_length(4);
1721
1722    awmm->at("jump");
1723    awmm->callback(ED4_jump_to_current_species, 0);
1724    awmm->help_text("e4.hlp");
1725    awmm->create_button("JUMP", "Jump");
1726
1727    awmm->at("get");
1728    awmm->callback(ED4_get_and_jump_to_current, 0);
1729    awmm->help_text("e4.hlp");
1730    awmm->create_button("GET", "Get");
1731
1732    awmm->button_length(0);
1733
1734    awmm->at("undo");
1735    awmm->callback(ED4_undo_redo, GB_UNDO_UNDO);
1736    awmm->help_text("undo.hlp");
1737    awmm->create_button("UNDO", "#undo.xpm");
1738
1739    awmm->at("redo");
1740    awmm->callback(ED4_undo_redo, GB_UNDO_REDO);
1741    awmm->help_text("undo.hlp");
1742    awmm->create_button("REDO", "#redo.xpm");
1743
1744    // --------------------------
1745    //      aligner / SAIviz
1746
1747    awmm->button_length(7);
1748
1749    awmm->at("aligner");
1750    awmm->callback(AW_POPUP, (AW_CL)ED4_create_faligner_window, (AW_CL)&dataAccess_4_aligner);
1751    awmm->help_text("faligner.hlp");
1752    awmm->create_button("ALIGNER", "Aligner");
1753
1754    awmm->at("saiviz");
1755    awmm->callback(AW_POPUP, (AW_CL)ED4_createVisualizeSAI_window, 0);
1756    awmm->help_text("visualizeSAI.hlp");
1757    awmm->create_button("SAIVIZ", "SAIviz");
1758
1759    // -------------------------------------------
1760    //      align/insert/protection/direction
1761
1762    awmm->button_length(0);
1763
1764    awmm->at("protect");
1765    awmm->create_option_menu(AWAR_EDIT_SECURITY_LEVEL, true);
1766    awmm->insert_option("0", 0, 0);
1767    awmm->insert_option("1", 0, 1);
1768    awmm->insert_option("2", 0, 2);
1769    awmm->insert_option("3", 0, 3);
1770    awmm->insert_option("4", 0, 4);
1771    awmm->insert_option("5", 0, 5);
1772    awmm->insert_default_option("6", 0, 6);
1773    awmm->update_option_menu();
1774
1775    // draw protection icon AFTER protection!!
1776    awmm->at("pico");
1777    awmm->create_button(NULL, "#protect.xpm");
1778
1779    // draw align/edit-button AFTER protection!!
1780    awmm->at("edit");
1781    awmm->create_toggle(AWAR_EDIT_MODE, "#edit/align.xpm", "#edit/editseq.xpm", 7);
1782
1783    awmm->at("insert");
1784    awmm->create_text_toggle(AWAR_INSERT_MODE, "Replace", "Insert", 7);
1785
1786    awmm->at("direct");
1787    awmm->create_toggle(AWAR_EDIT_RIGHTWARD, "#edit/3to5.xpm", "#edit/5to3.xpm", 7);
1788
1789    // -------------------------
1790    //      secedit / rna3d
1791
1792    int xoffset = 0;
1793
1794    if (alignment_type == GB_AT_RNA) { // if the database contains valid alignment of rRNA sequences
1795        // add buttons for RNA3D and SECEDIT plugins
1796
1797        awmm->button_length(0);
1798
1799        awmm->at("secedit");
1800        awmm->callback(ED4_start_plugin, (AW_CL)GLOBAL_gb_main, (AW_CL)"SECEDIT");
1801        awmm->help_text("arb_secedit.hlp");
1802        awmm->create_button("SECEDIT", "#edit/secedit.xpm");
1803
1804#if defined(ARB_OPENGL)
1805        awmm->at("rna3d");
1806        awmm->callback(ED4_start_plugin, (AW_CL)GLOBAL_gb_main, (AW_CL)"RNA3D");
1807        awmm->help_text("rna3d_general.hlp");
1808        awmm->create_button("RNA3D", "#edit/rna3d.xpm");
1809#endif // ARB_OPENGL
1810    }
1811    else {
1812        awmm->at("secedit");
1813        int xsecedit = awmm->get_at_xposition();
1814        awmm->at("zoom");
1815        int xzoom    = awmm->get_at_xposition();
1816        xoffset      = xsecedit-xzoom; // shift message stuff to the left by xoffset
1817    }
1818
1819    {
1820        int x, y;
1821
1822        awmm->at("zoom");
1823        if (xoffset) { awmm->get_at_position(&x, &y); awmm->at(x+xoffset, y); }
1824        awmm->callback(AW_POPUP, (AW_CL)ED4_zoom_message_window, (AW_CL)0);
1825        awmm->create_button("ZOOM", "#edit/zoom.xpm");
1826
1827        awmm->at("clear");
1828        if (xoffset) { awmm->get_at_position(&x, &y); awmm->at(x+xoffset, y); }
1829        awmm->callback(ED4_clear_errors, (AW_CL)0);
1830        awmm->create_button("CLEAR", "#edit/clear.xpm");
1831
1832        awmm->at("errortext");
1833        if (xoffset) { awmm->get_at_position(&x, &y); awmm->at(x+xoffset, y); }
1834        aw_root->awar_string(AWAR_ERROR_MESSAGES, "This is ARB Edit4 [Build " ARB_VERSION "]");
1835        awmm->create_text_field(AWAR_ERROR_MESSAGES);
1836        aw_set_local_message();
1837    }
1838
1839    // ---------------------
1840    //      'more' area
1841
1842    awmm->at("cons");
1843    awmm->create_toggle(ED4_AWAR_CONSENSUS_SHOW, "#edit/nocons.xpm", "#edit/cons.xpm");
1844
1845    awmm->at("num");
1846    awmm->create_toggle(ED4_AWAR_DIGITS_AS_REPEAT, "#edit/norepeat.xpm", "#edit/repeat.xpm");
1847
1848    awmm->at("key");
1849    awmm->create_toggle("key_mapping/enable", "#edit/nokeymap.xpm", "#edit/keymap.xpm");
1850
1851    // search
1852
1853    awmm->button_length(0);
1854#define INSERT_SEARCH_FIELDS(Short, label_prefix, prefix)       \
1855    insert_search_fields(awmm,                                  \
1856                         #label_prefix,                         \
1857                         #prefix,                               \
1858                         ED4_AWAR_##prefix##_SEARCH_PATTERN,    \
1859                         ED4_AWAR_##prefix##_SEARCH_SHOW,       \
1860                         Short,                                 \
1861                         ED4_##prefix##_PATTERN,                \
1862                         current_ed4w()                         \
1863        )
1864
1865    INSERT_SEARCH_FIELDS(0, u1, USER1);
1866    INSERT_SEARCH_FIELDS(0, u2, USER2);
1867    INSERT_SEARCH_FIELDS(0, pro, PROBE);
1868    INSERT_SEARCH_FIELDS(1, pri1, PRIMER1);
1869    INSERT_SEARCH_FIELDS(1, pri2, PRIMER2);
1870    INSERT_SEARCH_FIELDS(1, pri3, PRIMER3);
1871    INSERT_SEARCH_FIELDS(1, sig1, SIG1);
1872    INSERT_SEARCH_FIELDS(1, sig2, SIG2);
1873    INSERT_SEARCH_FIELDS(1, sig3, SIG3);
1874
1875#undef INSERT_SEARCH_FIELDS
1876
1877    awmm->at("alast");
1878    awmm->callback(ED4_search_cb, ED4_encodeSearchDescriptor(-1, ED4_ANY_PATTERN), (AW_CL)current_ed4w());
1879    awmm->create_button("ALL_SEARCH_LAST", "#edit/last.xpm");
1880
1881    awmm->at("anext");
1882    awmm->callback(ED4_search_cb, ED4_encodeSearchDescriptor(+1, ED4_ANY_PATTERN), (AW_CL)current_ed4w());
1883    awmm->create_button("ALL_SEARCH_NEXT", "#edit/next.xpm");
1884
1885    title_mode_changed(aw_root, awmm);
1886
1887    // Buttons at left window border
1888
1889    awmm->create_mode("edit/arrow.xpm", "normal.hlp", AWM_ALL, makeWindowCallback(modes_cb, ED4_SM_MOVE));
1890    awmm->create_mode("edit/kill.xpm",  "kill.hlp",   AWM_ALL, makeWindowCallback(modes_cb, ED4_SM_KILL));
1891    awmm->create_mode("edit/mark.xpm",  "mark.hlp",   AWM_ALL, makeWindowCallback(modes_cb, ED4_SM_MARK));
1892
1893    FastAligner_create_variables(awmm->get_root(), props_db);
1894
1895#if defined(DEBUG)
1896    AWT_check_action_ids(awmm->get_root(), "");
1897#endif
1898
1899    return (ED4_R_OK);
1900}
1901
1902AW_window *ED4_root::create_new_window() {
1903    // only the first window, other windows are generated by generate_window
1904    AW_device  *device     = NULL;
1905    ED4_window *new_window = NULL;
1906
1907    generate_window(&device, &new_window);
1908
1909    ED4_LocalWinContext uses(new_window);
1910   
1911    ED4_calc_terminal_extentions();
1912
1913    DRAW                    = 1;
1914    move_cursor             = 0;
1915    max_seq_terminal_length = 0;
1916
1917    ED4_init_notFoundMessage();
1918
1919    return new_window->aww;
1920}
1921
1922ED4_index ED4_root::pixel2pos(AW_pos click_x) {
1923    // 'click_x' is the x-offset into the terminal in pixels
1924    // returns the x-offset into the terminal in base positions (clipped to max. allowed position)
1925
1926    int       length_of_char = font_group.get_width(ED4_G_SEQUENCES);
1927    ED4_index scr_pos        = int((click_x-CHARACTEROFFSET) / length_of_char);
1928    int       max_scrpos     = root_group_man->remap()->get_max_screen_pos();
1929
1930    if (scr_pos>max_scrpos) scr_pos = max_scrpos;
1931
1932    return scr_pos;
1933}
1934
1935static char *detectProperties() {
1936    char *propname = NULL;
1937
1938    // check if edit4_?na.arb / edit4_ali_???.arb exist in $ARB_PROP
1939    for (int mode = 0; !propname && mode <= 1; ++mode) { 
1940        const char *fullprop = GB_path_in_arbprop(ED4_propertyName(mode));
1941        if (GB_is_regularfile(fullprop)) {
1942            freedup(propname, fullprop);
1943        }
1944    }
1945
1946    // if not, use 'mode 2', i.e. "edit4.arb"
1947    // (no full path, we want to load default from arb_defaults)
1948    if (!propname) propname = strdup(ED4_propertyName(2));
1949
1950    return propname;
1951}
1952
1953ED4_root::ED4_root(int* argc, char*** argv)
1954    : most_recently_used_window(0),
1955      db_name(detectProperties()),
1956      aw_root(AWT_create_root(db_name, "ARB_EDIT4", need_macro_ability(), argc, argv)),
1957      props_db(AW_ROOT_DEFAULT),
1958      first_window(0),
1959      main_manager(0),
1960      middle_area_man(0),
1961      top_area_man(0),
1962      root_group_man(0),
1963      database(0),
1964      selected_objects(new ED4_selected_list), 
1965      folding_action(0),
1966      species_mode(ED4_SM_MOVE),
1967      ecoli_ref(0),
1968      alignment_name(0),
1969      alignment_type(GB_AT_UNKNOWN),
1970      reference(0),
1971      sequence_colors(0),
1972      gc_manager(0),
1973      st_ml(0),
1974      helix(0),
1975      helix_spacing(0),
1976      helix_add_spacing(0),
1977      terminal_add_spacing(0),
1978      protstruct(0),
1979      protstruct_len(0),
1980      edk(0),
1981      edit_string(0),
1982      column_stat_activated(false),
1983      column_stat_initialized(false),
1984      visualizeSAI(false),
1985      visualizeSAI_allSpecies(false),
1986      temp_gc(0)
1987{}
1988
1989
1990ED4_root::~ED4_root() {
1991    delete aw_root;
1992    delete first_window;
1993    delete main_manager;
1994    delete middle_area_man;
1995    delete top_area_man;
1996    delete database;
1997    delete ecoli_ref;
1998    delete selected_objects;
1999
2000    free(protstruct);
2001    free(db_name);
2002}
Note: See TracBrowser for help on using the repository browser.