source: trunk/SL/APP/db_browser.cxx

Last change on this file was 19599, checked in by westram, 2 weeks ago
  • eliminate awt.hxx
    • remove remaining includes.
    • fix use of awt_assert.
  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 49.4 KB
Line 
1//  ==================================================================== //
2//                                                                       //
3//    File      : db_browser.cxx                                         //
4//    Purpose   : Simple database viewer                                 //
5//                                                                       //
6//                                                                       //
7//  Coded by Ralf Westram (coder@reallysoft.de) in May 2004              //
8//  Copyright Department of Microbiology (Technical University Munich)   //
9//                                                                       //
10//  Visit our web site at: http://www.arb-home.de/                       //
11//                                                                       //
12//  ==================================================================== //
13
14#include "hexdump.hxx"
15
16#include <aw_window.hxx>
17#include <aw_msg.hxx>
18#include <aw_awar.hxx>
19#include <aw_select.hxx>
20#include <aw_system.hxx>
21#include <aw_advice.hxx>
22
23#include <arbdbt.h>
24
25#include <arb_str.h>
26#include <arb_strarray.h>
27
28#include <arb_misc.h>
29#include <arb_diff.h>
30#include <arb_file.h>
31#include <arb_sleep.h>
32#include <ad_cb.h>
33
34#include <string>
35#include <vector>
36#include <map>
37#include <algorithm>
38
39// do includes above (otherwise depends depend on DEBUG)
40#if defined(DEBUG)
41
42using namespace std;
43
44// used AWARs :
45
46#define AWAR_DBB_BASE     "/dbbrowser"
47#define AWAR_DBB_TMP_BASE "/tmp" AWAR_DBB_BASE
48
49#define AWAR_DBB_DB      AWAR_DBB_BASE "/db"
50#define AWAR_DBB_ORDER   AWAR_DBB_BASE "/order"
51#define AWAR_DBB_PATH    AWAR_DBB_BASE "/path"
52#define AWAR_DBB_HISTORY AWAR_DBB_BASE "/history"
53
54#define AWAR_DBB_BROWSE AWAR_DBB_TMP_BASE "/browse"
55#define AWAR_DBB_INFO   AWAR_DBB_TMP_BASE "/info"
56
57#define AWAR_DBB_RECSIZE AWAR_DBB_BASE "/recsize"
58
59#define AWAR_DUMP_HEX   AWAR_DBB_BASE "/hex"
60#define AWAR_DUMP_ASCII AWAR_DBB_BASE "/ascii"
61#define AWAR_DUMP_SPACE AWAR_DBB_BASE "/space"
62#define AWAR_DUMP_WIDTH AWAR_DBB_BASE "/width"
63#define AWAR_DUMP_BLOCK AWAR_DBB_BASE "/block"
64
65#define HISTORY_PSEUDO_PATH "*history*"
66#define ENTRY_MAX_LENGTH    1000
67#define HISTORY_MAX_LENGTH  20000
68
69inline bool is_dbbrowser_pseudo_path(const char *path) {
70    return
71        path           &&
72        path[0] == '*' &&
73        strcmp(path, HISTORY_PSEUDO_PATH) == 0;
74}
75
76enum SortOrder {
77    SORT_NONE,
78    SORT_NAME,
79    SORT_CONTAINER,
80    SORT_OCCUR,
81    SORT_TYPE,
82    SORT_CONTENT,
83
84    SORT_COUNT
85};
86
87static const char *sort_order_name[SORT_COUNT] = {
88    "Unsorted",
89    "Name",
90    "Name (Container)",
91    "Name (Occur)",
92    "Type",
93    "Content",
94};
95
96// used to sort entries in list
97struct list_entry {
98    const char *key_name;
99    GB_TYPES    type;
100    int         childCount;     // -1 if only one child with key_name exists
101    GBDATA     *gbd;
102    string      content;
103
104    static SortOrder sort_order;
105
106    inline bool less_than_by_name(const list_entry& other) const {
107        int cmp = ARB_stricmp(key_name, other.key_name);
108        if (cmp != 0) return cmp<0; // name differs!
109        return childCount<other.childCount; // equal names -> compare child count
110    }
111
112    inline int cmp_by_container(const list_entry& other) const { return int(type != GB_DB) - int(other.type != GB_DB); }
113    inline int cmp_by_childcount(const list_entry& other) const { return childCount - other.childCount; }
114
115    inline bool less_than_by_container_name(const list_entry& other) const {
116        int cmp = cmp_by_container(other);
117        if (cmp == 0) return less_than_by_name(other);
118        return cmp<0;
119    }
120    inline bool less_than_by_childcount_name(const list_entry& other) const {
121        int cmp = cmp_by_childcount(other);
122        if (cmp == 0) return less_than_by_name(other);
123        return cmp<0;
124    }
125
126    bool operator<(const list_entry& other) const {
127        bool is_less = false;
128        switch (sort_order) {
129            case SORT_COUNT: break;
130            case SORT_NONE:
131                arb_assert(0);  // not possible
132                break;
133
134            case SORT_NAME:
135                is_less = less_than_by_name(other);
136                break;
137
138            case SORT_CONTAINER:
139                is_less = less_than_by_container_name(other);
140                break;
141
142            case SORT_OCCUR:
143                is_less = less_than_by_childcount_name(other);
144                break;
145
146            case SORT_CONTENT: {
147                int cmp = ARB_stricmp(content.c_str(), other.content.c_str());
148
149                if (cmp != 0) is_less = cmp<0;
150                else is_less          = less_than_by_container_name(other);
151
152                break;
153            }
154            case SORT_TYPE: {
155                int cmp = type-other.type;
156
157                if (cmp == 0) is_less = less_than_by_name(other);
158                else is_less          = cmp<0;
159
160                break;
161            }
162        }
163        return is_less;
164    }
165};
166
167SortOrder list_entry::sort_order = SORT_NONE;
168
169// ---------------------
170//      create AWARs
171
172static MemDump make_userdefined_MemDump(AW_root *awr) {
173    bool   hex      = awr->awar(AWAR_DUMP_HEX)->read_int();
174    bool   ascii    = awr->awar(AWAR_DUMP_ASCII)->read_int();
175    bool   space    = awr->awar(AWAR_DUMP_SPACE)->read_int();
176    size_t width    = awr->awar(AWAR_DUMP_WIDTH)->read_int();
177    size_t separate = awr->awar(AWAR_DUMP_BLOCK)->read_int();
178
179    bool offset = (hex||ascii) && width;
180
181    return MemDump(offset, hex, ascii, width, separate, space);
182}
183
184static void nodedisplay_changed_cb(AW_root *aw_root) {
185    aw_root->awar(AWAR_DBB_BROWSE)->touch();
186}
187
188void AWT_create_db_browser_awars(AW_root *aw_root, AW_default aw_def) {
189    aw_root->awar_int   (AWAR_DBB_DB,      0,                     aw_def); // index to internal order of announced databases
190    aw_root->awar_int   (AWAR_DBB_ORDER,   SORT_CONTAINER,        aw_def); // sort order for "browse"-box
191    aw_root->awar_string(AWAR_DBB_PATH,    "/",                   aw_def); // path in database
192    aw_root->awar_string(AWAR_DBB_BROWSE,  "",                    aw_def); // selection in browser (= child name)
193    aw_root->awar_string(AWAR_DBB_INFO,    "<select an element>", aw_def); // information about selected item
194    aw_root->awar_string(AWAR_DBB_HISTORY, "",                    aw_def); // '\n'-separated string containing visited nodes
195
196    aw_root->awar_int(AWAR_DBB_RECSIZE, 0,  aw_def)->add_callback(nodedisplay_changed_cb); // collect size recursive?
197
198    // hex-dump-options
199    aw_root->awar_int(AWAR_DUMP_HEX,   1,  aw_def)->add_callback(nodedisplay_changed_cb); // show hex ?
200    aw_root->awar_int(AWAR_DUMP_ASCII, 1,  aw_def)->add_callback(nodedisplay_changed_cb); // show ascii ?
201    aw_root->awar_int(AWAR_DUMP_SPACE, 1,  aw_def)->add_callback(nodedisplay_changed_cb); // space bytes
202    aw_root->awar_int(AWAR_DUMP_WIDTH, 16, aw_def)->add_callback(nodedisplay_changed_cb); // bytes/line
203    aw_root->awar_int(AWAR_DUMP_BLOCK, 8,  aw_def)->add_callback(nodedisplay_changed_cb); // separate each bytes
204}
205
206static GBDATA *GB_search_numbered(GBDATA *gbd, const char *str, GB_TYPES create) { // @@@  this may be moved to ARBDB-sources
207    arb_assert(!GB_have_error());
208    if (str) {
209        if (str[0] == '/' && str[1] == 0) { // root
210            return GB_get_root(gbd);
211        }
212
213        const char *first_bracket = strchr(str, '[');
214        if (first_bracket) {
215            const char *second_bracket = strchr(first_bracket+1, ']');
216            if (second_bracket && (second_bracket[1] == 0 || second_bracket[1] == '/')) {
217                int count = atoi(first_bracket+1);
218                if (count >= 0 && isdigit(first_bracket[1])) {
219                    // we are sure we have sth with number in brackets (e.g. "/species_data/species[42]/name")
220                    const char *previous_slash = first_bracket-1;
221                    while (previous_slash >= str && previous_slash[0] != '/') previous_slash--; //
222                    if (previous_slash<str) previous_slash = NULp;
223
224                    GBDATA *gb_parent = NULp;
225                    {
226                        if (previous_slash) { // found a slash
227                            char *parent_path = ARB_strpartdup(str, previous_slash-1);
228
229                            // we are sure parent path does not contain brackets -> search normal
230                            if (parent_path[0] == 0) { // that means : root-item is numbered (e.g. '/species_data[7]/...')
231                                gb_parent = GB_get_root(gbd);
232                            }
233                            else {
234                                gb_parent = GB_search(gbd, parent_path, GB_FIND);
235                            }
236
237                            if (!gb_parent) fprintf(stderr, "Warning: parent '%s' not found\n", parent_path);
238                            free(parent_path);
239                        }
240                        else {
241                            gb_parent = gbd;
242                        }
243                    }
244
245                    if (gb_parent) {
246                        GBDATA *gb_son = NULp;
247                        {
248                            const char *name_start = previous_slash ? previous_slash+1 : str;
249                            char       *key_name   = ARB_strpartdup(name_start, first_bracket-1);
250                            int         c          = 0;
251
252                            gb_son = GB_entry(gb_parent, key_name);
253                            while (c<count && gb_son) {
254                                gb_son = GB_nextEntry(gb_son);
255                                if (gb_son) ++c;
256                            }
257
258                            if (!gb_son) fprintf(stderr, "Warning: did not find %i. son '%s'\n", count, key_name);
259                            free(key_name);
260                        }
261
262                        if (gb_son) {
263                            const char *rest = NULp;
264                            if (second_bracket[1] == '/') { // continue search ?
265                                if (second_bracket[2]) {
266                                    rest = second_bracket+2;
267                                }
268                            }
269
270                            return rest
271                                ? GB_search_numbered(gb_son, rest, create) // recursive search
272                                : gb_son; // numbering occurred at end of search path
273                        }
274                    }
275                    else {
276                        fprintf(stderr, "Warning: don't know where to start numbered search in '%s'\n", str);
277                    }
278
279                    return NULp; // not found
280                }
281                else {
282                    fprintf(stderr, "Warning: Illegal content in search path - expected digits at '%s'\n", first_bracket+1);
283                }
284            }
285            else {
286                fprintf(stderr, "Warning: Unbalanced or illegal [] in search path (%s)\n", str);
287            }
288        }
289        // no brackets -> normal search
290    }
291    arb_assert(!GB_have_error());
292    return GB_search(gbd, str, create); // do normal search
293}
294
295// -----------------------
296//      class KnownDB
297
298class KnownDB {
299    RefPtr<GBDATA> gb_main;
300
301    string description;
302    string current_path;
303
304public:
305    KnownDB(GBDATA *gb_main_, const char *description_) :
306        gb_main(gb_main_),
307        description(description_),
308        current_path("/")
309    {}
310
311    const GBDATA *get_db() const { return gb_main; }
312    const string& get_description() const { return description; }
313
314    const string& get_path() const { return current_path; }
315    void set_path(const string& path) { current_path = path; }
316    void set_path(const char* path) { current_path = path; }
317};
318
319class hasDB {
320    GBDATA *db;
321public:
322    explicit hasDB(GBDATA *gbm) : db(gbm) {}
323    bool operator()(const KnownDB& kdb) { return kdb.get_db() == db; }
324};
325
326// --------------------------
327//      class DB_browser
328
329class DB_browser;
330static DB_browser *get_the_browser(bool autocreate);
331
332class DB_browser : virtual Noncopyable {
333    typedef vector<KnownDB>::iterator KnownDBiterator;
334
335    vector<KnownDB> known_databases;
336    size_t          current_db; // index of current db (in known_databases)
337
338    AW_window             *aww;                     // browser window
339    AW_option_menu_struct *oms;                     // the DB selector
340    AW_selection_list     *browse_list;             // the browse subwindow
341
342    static SmartPtr<DB_browser> the_browser;
343    friend DB_browser *get_the_browser(bool autocreate);
344
345    void update_DB_selector();
346
347public:
348    DB_browser() : current_db(0), aww(NULp), oms(NULp) {}
349
350    void add_db(GBDATA *gb_main, const char *description) {
351        known_databases.push_back(KnownDB(gb_main, description));
352        if (aww) update_DB_selector();
353    }
354
355    void del_db(GBDATA *gb_main) {
356        KnownDBiterator known = find_if(known_databases.begin(), known_databases.end(), hasDB(gb_main));
357        if (known != known_databases.end()) known_databases.erase(known);
358#if defined(DEBUG)
359        else arb_assert(0); // no need to delete unknown databases
360#endif // DEBUG
361    }
362
363    AW_window *get_window(AW_root *aw_root);
364    AW_selection_list *get_browser_list() { return browse_list; }
365
366    bool legal_selected_db() const { return current_db < known_databases.size(); }
367
368    size_t get_selected_db() const { arb_assert(legal_selected_db()); return current_db; }
369    void set_selected_db(size_t idx) { arb_assert(idx < known_databases.size()); current_db = idx; }
370
371    const char *get_path() const { return known_databases[get_selected_db()].get_path().c_str(); }
372    void set_path(const char *new_path) { known_databases[get_selected_db()].set_path(new_path); }
373
374    GBDATA *get_db() const {
375        return legal_selected_db() ? const_cast<GBDATA*>(known_databases[get_selected_db()].get_db()) : NULp;
376    }
377};
378
379
380// -----------------------------
381//      DB_browser singleton
382
383SmartPtr<DB_browser> DB_browser::the_browser;
384
385static DB_browser *get_the_browser(bool autocreate = true) {
386    if (DB_browser::the_browser.isNull() && autocreate) {
387        DB_browser::the_browser = new DB_browser;
388    }
389    return &*DB_browser::the_browser;
390}
391
392// --------------------------
393//      announce databases
394
395void AWT_announce_db_to_browser(GBDATA *gb_main, const char *description) {
396    get_the_browser()->add_db(gb_main, description);
397}
398
399static void AWT_announce_properties_to_browser(GBDATA *gb_defaults, const char *defaults_name) {
400    AWT_announce_db_to_browser(gb_defaults, GBS_global_string("Properties (%s)", defaults_name));
401}
402
403void AWT_browser_forget_db(GBDATA *gb_main) {
404    if (gb_main) {
405        DB_browser *browser = get_the_browser(false);
406        arb_assert(browser);
407        if (browser) browser->del_db(gb_main);
408    }
409}
410
411// ---------------------------------------
412//      browser window callbacks
413
414static void toggle_tmp_cb(AW_window *aww) {
415    AW_awar *awar_path = aww->get_root()->awar(AWAR_DBB_PATH);
416    char    *path      = awar_path->read_string();
417    bool     done      = false;
418
419    if (ARB_strBeginsWith(path, "/tmp")) {
420        if (path[4] == '/') {
421            awar_path->write_string(path+4);
422            done = true;
423        }
424        else if (path[4] == 0) {
425            awar_path->write_string("/");
426            done = true;
427        }
428    }
429
430    if (!done && !is_dbbrowser_pseudo_path(path)) {
431        char *path_in_tmp = GBS_global_string_copy("/tmp%s", path);
432
433        char *lslash = strrchr(path_in_tmp, '/');
434        if (lslash && !lslash[1]) { // ends with '/'
435            lslash[0] = 0; // cut-off trailing '/'
436        }
437        awar_path->write_string(path_in_tmp);
438        free(path_in_tmp);
439    }
440    free(path);
441}
442
443static void show_history_cb(AW_window *aww) {
444    aww->get_root()->awar(AWAR_DBB_PATH)->write_string(HISTORY_PSEUDO_PATH);
445}
446
447static void goto_root_cb(AW_window *aww) {
448    AW_awar *awar_path = aww->get_root()->awar(AWAR_DBB_PATH);
449    awar_path->write_string("/");
450}
451static void go_up_cb(AW_window *aww) {
452    AW_awar *awar_path = aww->get_root()->awar(AWAR_DBB_PATH);
453    char    *path      = awar_path->read_string();
454    char    *lslash    = strrchr(path, '/');
455
456    if (lslash) {
457        lslash[0] = 0;
458        if (!path[0]) strcpy(path, "/");
459        awar_path->write_string(path);
460    }
461}
462
463// --------------------------
464//      browser commands:
465
466#define BROWSE_CMD_PREFIX          "browse_cmd___"
467#define BROWSE_CMD_GOTO_VALID_NODE BROWSE_CMD_PREFIX "goto_valid_node"
468#define BROWSE_CMD_GO_UP           BROWSE_CMD_PREFIX "go_up"
469
470struct BrowserCommand {
471    const char *name;
472    GB_ERROR (*function)(AW_window *);
473};
474
475
476static GB_ERROR browse_cmd_go_up(AW_window *aww) {
477    go_up_cb(aww);
478    return NULp;
479}
480static GB_ERROR browse_cmd_goto_valid_node(AW_window *aww) {
481    AW_root *aw_root   = aww->get_root();
482    AW_awar *awar_path = aw_root->awar(AWAR_DBB_PATH);
483    char    *path      = awar_path->read_string();
484    int      len       = strlen(path);
485    GBDATA  *gb_main   = get_the_browser()->get_db();
486
487    {
488        GB_transaction t(gb_main);
489        while (len>0 && !GB_search_numbered(gb_main, path, GB_FIND)) {
490            GB_clear_error();
491            path[--len] = 0;
492        }
493    }
494
495    awar_path->write_string(len ? path : "/");
496    aw_root->awar(AWAR_DBB_BROWSE)->write_string("");
497    return NULp;
498}
499
500static BrowserCommand browser_command_table[] = {
501    { BROWSE_CMD_GOTO_VALID_NODE, browse_cmd_goto_valid_node },
502    { BROWSE_CMD_GO_UP, browse_cmd_go_up },
503    { NULp, NULp }
504};
505
506static void execute_DB_browser_command(AW_window *aww, const char *command) {
507    int idx;
508    for (idx = 0; browser_command_table[idx].name; ++idx) {
509        if (strcmp(command, browser_command_table[idx].name) == 0) {
510            GB_ERROR error = browser_command_table[idx].function(aww);
511            if (error) aw_message(error);
512            break;
513        }
514    }
515
516    if (!browser_command_table[idx].name) {
517        aw_message(GBS_global_string("Unknown DB-browser command '%s'", command));
518    }
519}
520
521// ----------------------------
522//      the browser window
523
524static AW_window *create_db_browser(AW_root *aw_root) {
525    return get_the_browser()->get_window(aw_root);
526}
527
528struct counterPair {
529    int occur, count;
530    counterPair() : occur(0), count(0) {}
531};
532
533inline void insert_history_selection(AW_selection_list *sel, const char *entry, int wanted_db) {
534    const char *colon = strchr(entry, ':');
535    if (colon && (atoi(entry) == wanted_db)) {
536        sel->insert(colon+1, colon+1);
537    }
538}
539
540
541static char *get_container_description(GBDATA *gbd) {
542    char *content = NULp;
543    const char *known_children[] = { "@name", "name", "key_name", "alignment_name", "group_name", "key_text", NULp };
544    for (int i = 0; known_children[i]; ++i) {
545        GBDATA *gb_known = GB_entry(gbd, known_children[i]);
546        if (gb_known && GB_read_type(gb_known) != GB_DB && !GB_nextEntry(gb_known)) { // exactly one child exits
547            char *asStr = GB_read_as_string(gb_known);
548            content     = GBS_global_string_copy("[%s=%s]", known_children[i], asStr);
549            free(asStr);
550            break;
551        }
552    }
553
554    return content;
555}
556
557static char *get_dbentry_content(GBDATA *gbd, GB_TYPES type, bool shorten_repeats, const MemDump& dump) {
558    arb_assert(type != GB_DB);
559
560    char *content = NULp;
561    if (!dump.wrapped()) content = GB_read_as_string(gbd);
562    if (!content) { // use dumper
563        long size;
564
565        switch (type) {
566            case GB_BIT:
567            case GB_BYTE:    size = 1;    break;
568            case GB_INT:     size = sizeof(int32_t);    break;
569            case GB_FLOAT:   size = sizeof(float);      break;
570            case GB_POINTER: size = sizeof(GBDATA*);    break;
571
572            case GB_BITS:
573            case GB_BYTES:
574            case GB_INTS:
575            case GB_FLOATS:
576            case GB_STRING:  size = GB_read_count(gbd); break;
577
578            default: aw_assert(0); break;
579        }
580
581        const int     plen = 30;
582        GBS_strstruct buf(dump.mem_needed_for_dump(size)+plen);
583
584        if (!dump.wrapped()) buf.nprintf(plen, "<%li bytes>: ", size);
585        dump.dump_to(buf, GB_read_pntr(gbd), size);
586
587        content         = buf.release();
588        shorten_repeats = false;
589    }
590    arb_assert(content);
591
592    size_t len = shorten_repeats ? GBS_shorten_repeated_data(content) : strlen(content);
593    if (!dump.wrapped() && len>(ENTRY_MAX_LENGTH+15)) {
594        content[ENTRY_MAX_LENGTH] = 0;
595        freeset(content, GBS_global_string_copy("%s [rest skipped]", content));
596    }
597    return content;
598}
599
600static void update_browser_selection_list(AW_root *aw_root, AW_selection_list *id) {
601    arb_assert(!GB_have_error());
602    DB_browser *browser = get_the_browser();
603    char       *path    = aw_root->awar(AWAR_DBB_PATH)->read_string();
604    bool        is_root;
605    GBDATA     *node    = NULp;
606
607    {
608        GBDATA *gb_main = browser->get_db();
609        if (gb_main) {
610            GB_transaction ta(gb_main);
611            is_root = (strcmp(path, "/") == 0);
612            node    = GB_search_numbered(gb_main, path, GB_FIND);
613        }
614    }
615
616    id->clear();
617
618    if (!node) {
619        if (strcmp(path, HISTORY_PSEUDO_PATH) == 0) {
620            GB_clear_error(); // ignore error about invalid key
621            char *history = aw_root->awar(AWAR_DBB_HISTORY)->read_string();
622            id->insert("Previously visited nodes:", "");
623            char *start   = history;
624            int   curr_db = aw_root->awar(AWAR_DBB_DB)->read_int();
625
626            for (char *lf = strchr(start, '\n'); lf; start = lf+1, lf = strchr(start, '\n')) {
627                lf[0] = 0;
628                insert_history_selection(id, start, curr_db);
629            }
630            insert_history_selection(id, start, curr_db);
631            free(history);
632        }
633        else {
634            if (GB_have_error()) id->insert(GBS_global_string("Error: %s", GB_await_error()), "");
635            id->insert("No such node!", "");
636            id->insert("-> goto valid node", BROWSE_CMD_GOTO_VALID_NODE);
637        }
638    }
639    else {
640        map<string, counterPair> child_count;
641        GB_transaction           ta(browser->get_db());
642
643        for (GBDATA *child = GB_child(node); child; child = GB_nextChild(child)) {
644            const char *key_name   = GB_read_key_pntr(child);
645            child_count[key_name].occur++;
646        }
647
648        int maxkeylen = 0;
649        int maxtypelen = 0;
650        for (map<string, counterPair>::iterator i = child_count.begin(); i != child_count.end(); ++i) {
651            {
652                int keylen   = i->first.length();
653                int maxcount = i->second.occur;
654
655                if (maxcount != 1) {
656                    keylen += 2;    // brackets
657                    while (maxcount) { maxcount /= 10; keylen++; } // increase keylen for each digit
658                }
659
660                if (keylen>maxkeylen) maxkeylen = keylen;
661            }
662
663            {
664                GBDATA     *child     = GB_entry(node, i->first.c_str()); // find first child
665                const char *type_name = GB_get_type_name(child);
666                int         typelen   = strlen(type_name);
667
668                if (typelen>maxtypelen) maxtypelen = typelen;
669            }
670        }
671
672        if (!is_root) {
673            id->insert(GBS_global_string("%-*s   parent container", maxkeylen, ".."), BROWSE_CMD_GO_UP);
674            id->insert(GBS_global_string("%-*s   container", maxkeylen, "."), "");
675        }
676        else {
677            id->insert(GBS_global_string("%-*s   root container", maxkeylen, "/"), "");
678        }
679
680        // collect children and sort them
681
682        vector<list_entry> sorted_children;
683
684        MemDump simpleDump(false, true, false);
685        for (GBDATA *child = GB_child(node); child; child = GB_nextChild(child)) {
686            list_entry entry;
687            entry.key_name   = GB_read_key_pntr(child);
688            entry.childCount = -1;
689            entry.type       = GB_read_type(child);
690            entry.gbd        = child;
691
692            int occurrences = child_count[entry.key_name].occur;
693            if (occurrences != 1) {
694                entry.childCount = child_count[entry.key_name].count;
695                child_count[entry.key_name].count++;
696            }
697            char *display = NULp;
698            if (entry.type == GB_DB) {
699                display = get_container_description(entry.gbd);
700            }
701            else {
702                display = get_dbentry_content(entry.gbd, entry.type, true, simpleDump);
703            }
704            if (display) entry.content = display;
705            sorted_children.push_back(entry);
706        }
707
708        list_entry::sort_order = (SortOrder)aw_root->awar(AWAR_DBB_ORDER)->read_int();
709        if (list_entry::sort_order != SORT_NONE) {
710            sort(sorted_children.begin(), sorted_children.end());
711        }
712
713        for (vector<list_entry>::iterator ch = sorted_children.begin(); ch != sorted_children.end(); ++ch) {
714            const list_entry&  entry            = *ch;
715            const char        *key_name         = entry.key_name;
716            char              *numbered_keyname = NULp;
717
718            if (entry.childCount >= 0) {
719                numbered_keyname = GBS_global_string_copy("%s[%i]", key_name, entry.childCount);
720            }
721
722            key_name = numbered_keyname ? numbered_keyname : key_name;
723            const char *displayed = GBS_global_string("%-*s   %-*s   %s", maxkeylen, key_name, maxtypelen, GB_get_type_name(entry.gbd), entry.content.c_str());
724            id->insert(displayed, key_name);
725
726            free(numbered_keyname);
727        }
728    }
729    id->insert_default("", "");
730    id->update();
731
732    free(path);
733    arb_assert(!GB_have_error());
734}
735
736static void order_changed_cb(AW_root *aw_root) {
737    DB_browser *browser = get_the_browser();
738    update_browser_selection_list(aw_root, browser->get_browser_list());
739}
740
741inline char *strmove(char *dest, char *source) {
742    return (char*)memmove(dest, source, strlen(source)+1);
743}
744
745static void add_to_history(AW_root *aw_root, const char *path) {
746    // adds 'path' to history
747
748    if (strcmp(path, HISTORY_PSEUDO_PATH) != 0) {
749        int      db           = aw_root->awar(AWAR_DBB_DB)->read_int();
750        AW_awar *awar_history = aw_root->awar(AWAR_DBB_HISTORY);
751        char    *old_history  = awar_history->read_string();
752        char    *entry        = GBS_global_string_copy("%i:%s", db, path);
753        int      entry_len    = strlen(entry);
754
755        char *found = strstr(old_history, entry);
756        while (found) {
757            if (found == old_history || found[-1] == '\n') { // found start of an entry
758                if (found[entry_len] == '\n') {
759                    strmove(found, found+entry_len+1);
760                    found = strstr(old_history, entry);
761                }
762                else if (found[entry_len] == 0) { // found as last entry
763                    if (found == old_history) { // which is also first entry
764                        old_history[0] = 0; // empty history
765                    }
766                    else {
767                        strmove(found, found+entry_len+1);
768                    }
769                    found = strstr(old_history, entry);
770                }
771                else {
772                    found = strstr(found+1, entry);
773                }
774            }
775            else {
776                found = strstr(found+1, entry);
777            }
778        }
779
780        if (old_history[0]) {
781            char *new_history = GBS_global_string_copy("%s\n%s", entry, old_history);
782
783            while (strlen(old_history)>HISTORY_MAX_LENGTH) { // shorten history
784                char *llf = strrchr(old_history, '\n');
785                if (!llf) break;
786                llf[0]    = 0;
787            }
788
789            awar_history->write_string(new_history);
790            free(new_history);
791        }
792        else {
793            awar_history->write_string(entry);
794        }
795
796        free(entry);
797        free(old_history);
798    }
799}
800
801static bool    inside_path_change = false;
802static GBDATA *gb_tracked_node    = NULp;
803
804static void selected_node_modified_cb(GBDATA *gb_node, GB_CB_TYPE cb_type) {
805    arb_assert(gb_node == gb_tracked_node);
806
807    if (cb_type & GB_CB_DELETE) {
808        gb_tracked_node = NULp; // no need to remove callback ?
809    }
810
811    if (!inside_path_change) { // ignore refresh callbacks triggered by dbbrowser-awars
812        static bool avoid_recursion = false;
813        if (!avoid_recursion) {
814            LocallyModify<bool> flag(avoid_recursion, true);
815            GlobalStringBuffers *old_buffers = GBS_store_global_buffers();
816
817            AW_root *aw_root   = AW_root::SINGLETON;
818            AW_awar *awar_path = aw_root->awar_no_error(AWAR_DBB_PATH);
819            if (awar_path) { // avoid crash during exit
820                AW_awar    *awar_child = aw_root->awar(AWAR_DBB_BROWSE);
821                const char *child      = awar_child->read_char_pntr();
822
823                if (child[0]) {
824                    const char *path     = awar_path->read_char_pntr();
825                    const char *new_path;
826
827                    if (!path[0] || !path[1]) {
828                        new_path = GBS_global_string("/%s", child);
829                    }
830                    else {
831                        new_path = GBS_global_string("%s/%s", path, child);
832                    }
833
834                    char *fixed_path = GBS_string_eval(new_path, "//=/");
835                    awar_path->write_string(fixed_path);
836                    free(fixed_path);
837                }
838                else {
839                    awar_path->touch();
840                }
841            }
842            GBS_restore_global_buffers(old_buffers);
843        }
844    }
845}
846static void untrack_node() {
847    if (gb_tracked_node) {
848        GB_remove_callback(gb_tracked_node, GB_CB_ALL, makeDatabaseCallback(selected_node_modified_cb));
849        gb_tracked_node = NULp;
850    }
851}
852static void track_node(GBDATA *gb_node) {
853    untrack_node();
854    GB_ERROR error = GB_add_callback(gb_node, GB_CB_ALL, makeDatabaseCallback(selected_node_modified_cb));
855    if (error) {
856        aw_message(error);
857    }
858    else {
859        gb_tracked_node = gb_node;
860    }
861}
862
863static string get_node_info_string(AW_root *aw_root, GBDATA *gb_selected_node, const char *fullpath) {
864    string info;
865    info += GBS_global_string("Fullpath  | '%s'\n", fullpath);
866
867    if (!gb_selected_node) {
868        info += "Address   | NULp\n";
869        info += GBS_global_string("Error     | %s\n", GB_have_error() ? GB_await_error() : "<none>");
870    }
871    else {
872        add_to_history(aw_root, fullpath);
873
874        info += GBS_global_string("Address   | %p\n", gb_selected_node);
875        info += GBS_global_string("Key index | %i\n", GB_get_quark(gb_selected_node));
876
877
878        GB_SizeInfo sizeInfo;
879        bool        collect_recursive = aw_root->awar(AWAR_DBB_RECSIZE)->read_int();
880
881        GB_TYPES type = GB_read_type(gb_selected_node);
882        if (collect_recursive || type != GB_DB) {
883            sizeInfo.collect(gb_selected_node);
884        }
885
886        string structure_add;
887        string childs;
888
889        if (type == GB_DB) {
890            long struct_size = GB_calc_structure_size(gb_selected_node);
891            if (collect_recursive) {
892                structure_add = GBS_global_string(" (this: %s)", GBS_readable_size(struct_size, "b"));
893            }
894            else {
895                sizeInfo.structure = struct_size;
896            }
897
898            info += "Node type | container\n";
899
900            childs = GBS_global_string("Childs    | %li", GB_number_of_subentries(gb_selected_node));
901            if (collect_recursive) {
902                childs = childs+" (rec: " + GBS_readable_size(sizeInfo.containers, "containers");
903                childs = childs+" + " + GBS_readable_size(sizeInfo.terminals, "terminals");
904                childs = childs+" = " + GBS_readable_size(sizeInfo.terminals+sizeInfo.containers, "nodes")+')';
905            }
906            childs += '\n';
907
908            {
909                LocallyModify<bool> flag2(inside_path_change, true);
910                aw_root->awar(AWAR_DBB_BROWSE)->write_string("");
911                aw_root->awar(AWAR_DBB_PATH)->write_string(fullpath);
912            }
913        }
914        else {
915            info += GBS_global_string("Node type | data [type=%s]\n", GB_get_type_name(gb_selected_node));
916        }
917
918        long overall = sizeInfo.mem+sizeInfo.structure;
919
920        info += GBS_global_string("Data size | %7s\n", GBS_readable_size(sizeInfo.data, "b"));
921        info += GBS_global_string("Memory    | %7s  %5.2f%%\n", GBS_readable_size(sizeInfo.mem, "b"), double(sizeInfo.mem)/overall*100+.0049);
922        info += GBS_global_string("Structure | %7s  %5.2f%%", GBS_readable_size(sizeInfo.structure, "b"), double(sizeInfo.structure)/overall*100+.0049) + structure_add + '\n';
923        info += GBS_global_string("Overall   | %7s\n", GBS_readable_size(overall, "b"));
924        if (sizeInfo.data) {
925            info += GBS_global_string("CompRatio | %5.2f%% (mem-only: %5.2f%%)\n", double(overall)/sizeInfo.data*100+.0049, double(sizeInfo.mem)/sizeInfo.data*100+.0049);
926        }
927        info += childs;
928
929        {
930            bool is_tmp             = GB_is_temporary(gb_selected_node);
931            bool not_tmp_but_in_tmp = !is_tmp && GB_in_temporary_branch(gb_selected_node);
932
933            if (is_tmp || not_tmp_but_in_tmp) {
934                info += GBS_global_string("Temporary | yes%s\n", not_tmp_but_in_tmp ? " (in temporary branch)" : "");
935            }
936        }
937
938        GBDATA *gb_recurse_here = NULp;
939        char   *recursed_path   = NULp;
940        {
941            AW_awar *awar_this = aw_root->awar_no_error(fullpath+1); // skip leading slash
942            if (awar_this) {
943                bool is_mapped  = awar_this->is_mapped();
944                info           += "AWAR      | yes\n";
945                if (is_mapped) {
946                    gb_recurse_here = awar_this->gb_var;
947                    recursed_path   = ARB_strdup(GB_get_db_path(gb_recurse_here));
948                    info            = info + "          | mapped to '" + recursed_path + "' (see below)\n";
949                }
950            }
951        }
952
953        info += GBS_global_string("Security  | read=%i write=%i delete=%i\n",
954                                  GB_read_security_read(gb_selected_node),
955                                  GB_read_security_write(gb_selected_node),
956                                  GB_read_security_delete(gb_selected_node));
957
958        char *callback_info = GB_get_callback_info(gb_selected_node);
959        if (callback_info) {
960            ConstStrArray callbacks;
961            GBT_splitNdestroy_string(callbacks, callback_info, "\n", SPLIT_DROPEMPTY);
962
963            for (size_t i = 0; i<callbacks.size(); ++i) {
964                const char *prefix = i ? "         " : "Callbacks";
965                info               = info + prefix + " | " + callbacks[i] + '\n';
966            }
967
968            if (gb_selected_node == gb_tracked_node) {
969                info += "          | (Note: one callback was installed by this browser)\n";
970            }
971        }
972
973        if (type != GB_DB) {
974            MemDump  dump    = make_userdefined_MemDump(aw_root);
975            char    *content = get_dbentry_content(gb_selected_node, GB_read_type(gb_selected_node), false, dump);
976            if (content[0]) {
977                info = info+"\nContent:\n"+content+'\n';
978            }
979            else {
980                info += "\nNo content.\n";
981            }
982            free(content);
983        }
984
985        if (gb_recurse_here) {
986            GBDATA     *gb_sel_main = GB_get_root(gb_selected_node);
987            GBDATA     *gb_sub_main = GB_get_root(gb_recurse_here);
988            const bool  same_DB     = gb_sel_main == gb_sub_main;
989
990            GB_transaction ta(gb_sub_main);  // target database may differ from current
991
992            string subinfo = get_node_info_string(aw_root, gb_recurse_here, recursed_path);
993
994            info +=
995                "\n"
996                + string(same_DB
997                   ?
998                   "===========================\n"
999                   "Recursive database element:\n"
1000                   :
1001                   "===================================================\n"
1002                   "Recursive database element (in different database):\n"
1003                    )
1004                + "\n"
1005                + subinfo;
1006
1007            freenull(recursed_path);
1008        }
1009    }
1010    return info;
1011}
1012
1013static void child_changed_cb(AW_root *aw_root) {
1014    char *child = aw_root->awar(AWAR_DBB_BROWSE)->read_string();
1015    if (strncmp(child, BROWSE_CMD_PREFIX, sizeof(BROWSE_CMD_PREFIX)-1) == 0) { // a symbolic browser command
1016        execute_DB_browser_command(get_the_browser()->get_window(aw_root), child);
1017    }
1018    else {
1019        char *path = aw_root->awar(AWAR_DBB_PATH)->read_string();
1020
1021        if (strcmp(path, HISTORY_PSEUDO_PATH) == 0) {
1022            if (child[0]) {
1023                LocallyModify<bool> flag(inside_path_change, true);
1024                aw_root->awar(AWAR_DBB_PATH)->write_string(child);
1025            }
1026        }
1027        else {
1028            static bool avoid_recursion = false;
1029            if (!avoid_recursion) {
1030                LocallyModify<bool> flag(avoid_recursion, true);
1031
1032                char *fullpath;
1033                if (strcmp(path, "/") == 0) {
1034                    fullpath = GBS_global_string_copy("/%s", child);
1035                }
1036                else if (child[0] == 0) {
1037                    fullpath = ARB_strdup(path);
1038                }
1039                else {
1040                    fullpath = GBS_global_string_copy("%s/%s", path, child);
1041                }
1042
1043                DB_browser *browser = get_the_browser();
1044                GBDATA     *gb_main = browser->get_db();
1045
1046                if (gb_main) {
1047                    GB_transaction  ta(gb_main);
1048                    GBDATA         *gb_selected_node = GB_search_numbered(gb_main, fullpath, GB_FIND);
1049
1050                    string info = get_node_info_string(aw_root, gb_selected_node, fullpath);
1051
1052
1053                    aw_root->awar(AWAR_DBB_INFO)->write_string(info.c_str());
1054                }
1055                free(fullpath);
1056            }
1057        }
1058
1059        free(path);
1060    }
1061    free(child);
1062}
1063
1064static void path_changed_cb(AW_root *aw_root) {
1065    static bool avoid_recursion = false;
1066    if (!avoid_recursion) {
1067        arb_assert(!GB_have_error());
1068        LocallyModify<bool> flag(avoid_recursion, true);
1069
1070        DB_browser *browser    = get_the_browser();
1071        char       *goto_child = NULp;
1072
1073        GBDATA *gb_main = browser->get_db();
1074        if (gb_main) {
1075            GB_transaction  t(gb_main);
1076            AW_awar        *awar_path = aw_root->awar(AWAR_DBB_PATH);
1077            char           *path      = awar_path->read_string();
1078            GBDATA         *found     = GB_search_numbered(gb_main, path, GB_FIND);
1079
1080            if (found && GB_read_type(found) != GB_DB) { // exists, but is not a container
1081                char *lslash = strrchr(path, '/');
1082                if (lslash) {
1083                    goto_child = ARB_strdup(lslash+1);
1084                    lslash[lslash == path] = 0; // truncate at last slash (but keep sole slash)
1085                    awar_path->write_string(path);
1086                }
1087            }
1088
1089            if (found) {
1090                LocallyModify<bool> flag2(inside_path_change, true);
1091                add_to_history(aw_root, goto_child ? GBS_global_string("%s/%s", path, goto_child) : path);
1092                GBDATA *father = GB_get_father(found);
1093                track_node(father ? father : found);
1094            }
1095            else if (is_dbbrowser_pseudo_path(path)) {
1096                GB_clear_error(); // ignore error about invalid key
1097            }
1098            else if (GB_have_error()) {
1099                aw_message(GB_await_error());
1100            }
1101            browser->set_path(path);
1102            free(path);
1103        }
1104
1105        update_browser_selection_list(aw_root, browser->get_browser_list());
1106
1107        LocallyModify<bool> flag2(inside_path_change, true);
1108        aw_root->awar(AWAR_DBB_BROWSE)->rewrite_string(null2empty(goto_child));
1109        arb_assert(!GB_have_error());
1110    }
1111}
1112static void db_changed_cb(AW_root *aw_root) {
1113    int         selected = aw_root->awar(AWAR_DBB_DB)->read_int();
1114    DB_browser *browser  = get_the_browser();
1115
1116    LocallyModify<bool> flag(inside_path_change, true);
1117    browser->set_selected_db(selected);
1118    aw_root->awar(AWAR_DBB_PATH)->rewrite_string(browser->get_path());
1119}
1120
1121void DB_browser::update_DB_selector() {
1122    if (!oms) oms = aww->create_option_menu(AWAR_DBB_DB);
1123    else aww->clear_option_menu(oms);
1124
1125    int idx = 0;
1126    for (KnownDBiterator i = known_databases.begin(); i != known_databases.end(); ++i, ++idx) {
1127        const KnownDB& db = *i;
1128        aww->insert_option(db.get_description().c_str(), "", idx);
1129    }
1130    aww->update_option_menu();
1131}
1132
1133AW_window *DB_browser::get_window(AW_root *aw_root) {
1134    arb_assert(!known_databases.empty()); // have no db to browse
1135
1136    if (!aww) {
1137        // select current db+path
1138        {
1139            int wanted_db = aw_root->awar(AWAR_DBB_DB)->read_int();
1140            int known     = known_databases.size();
1141            if (wanted_db >= known) {
1142                wanted_db = 0;
1143                aw_root->awar(AWAR_DBB_DB)->write_int(wanted_db);
1144                aw_root->awar(AWAR_DBB_PATH)->write_string("/"); // reset
1145            }
1146            set_selected_db(wanted_db);
1147
1148            char *wanted_path = aw_root->awar(AWAR_DBB_PATH)->read_string();
1149            known_databases[wanted_db].set_path(wanted_path);
1150            free(wanted_path);
1151        }
1152
1153        AW_window_simple *aws = new AW_window_simple;
1154        aww                   = aws;
1155        aws->init(aw_root, "DB_BROWSER", "ARB database browser");
1156        aws->load_xfig("dbbrowser.fig");
1157
1158        aws->at("close"); aws->callback(AW_POPDOWN);
1159        aws->create_button("CLOSE", "CLOSE", "C");
1160
1161        aws->at("db");
1162        update_DB_selector();
1163
1164        aws->at("order");
1165        aws->create_option_menu(AWAR_DBB_ORDER);
1166        for (int idx = 0; idx<SORT_COUNT; ++idx) {
1167            aws->insert_option(sort_order_name[idx], "", idx);
1168        }
1169        aws->update_option_menu();
1170
1171        aws->at("path");
1172        aws->create_input_field(AWAR_DBB_PATH, 10);
1173
1174        aws->auto_space(10, 10);
1175        aws->button_length(8);
1176
1177        aws->at("navigation");
1178        aws->callback(go_up_cb); aws->create_button("go_up", "Up");
1179        aws->callback(goto_root_cb); aws->create_button("goto_root", "Top");
1180        aws->callback(show_history_cb); aws->create_button("history", "History");
1181        aws->callback(toggle_tmp_cb); aws->create_button("toggle_tmp", "/tmp");
1182
1183        aws->label("Rec.size"); aws->create_toggle(AWAR_DBB_RECSIZE);
1184
1185        aws->at("browse");
1186        browse_list = aws->create_selection_list(AWAR_DBB_BROWSE);
1187        update_browser_selection_list(aw_root, browse_list);
1188
1189        aws->at("infoopt");
1190        aws->label("ASCII"); aws->create_toggle     (AWAR_DUMP_ASCII);
1191        aws->label("Hex");   aws->create_toggle     (AWAR_DUMP_HEX);
1192        aws->label("Sep?");  aws->create_toggle     (AWAR_DUMP_SPACE);
1193        aws->label("Width"); aws->create_input_field(AWAR_DUMP_WIDTH, 3);
1194        aws->label("Block"); aws->create_input_field(AWAR_DUMP_BLOCK, 3);
1195
1196        aws->at("info");
1197        aws->create_text_field(AWAR_DBB_INFO, 40, 40);
1198
1199        // add callbacks
1200        aw_root->awar(AWAR_DBB_BROWSE)->add_callback(child_changed_cb);
1201        aw_root->awar(AWAR_DBB_PATH)->add_callback(path_changed_cb);
1202        aw_root->awar(AWAR_DBB_DB)->add_callback(db_changed_cb);
1203        aw_root->awar(AWAR_DBB_ORDER)->add_callback(order_changed_cb);
1204
1205        db_changed_cb(aw_root); // force update
1206    }
1207    return aww;
1208}
1209
1210static void callallcallbacks(AW_window *aww, int mode) {
1211    static bool running = false; // avoid deadlock
1212    if (!running) {
1213        LocallyModify<bool> flag(running, true);
1214        aww->get_root()->callallcallbacks(mode);
1215    }
1216}
1217
1218
1219
1220void AWT_create_debug_menu(AW_window *awmm) {
1221    awmm->create_menu("4debugz", "z", AWM_ALL);
1222
1223    awmm->insert_menu_topic(awmm->local_id("-db_browser"), "Browse loaded database(s)", "B", NULp, AWM_ALL, create_db_browser);
1224
1225    awmm->sep______________();
1226    {
1227        awmm->insert_sub_menu("Callbacks (dangerous! use at your own risk)", "C", AWM_ALL);
1228        awmm->insert_menu_topic("!run_all_cbs_alph",  "Call all callbacks (alpha-order)",     "a", "", AWM_ALL, makeWindowCallback(callallcallbacks, 0));
1229        awmm->insert_menu_topic("!run_all_cbs_nalph", "Call all callbacks (alpha-reverse)",   "l", "", AWM_ALL, makeWindowCallback(callallcallbacks, 1));
1230        awmm->insert_menu_topic("!run_all_cbs_loc",   "Call all callbacks (code-order)",      "c", "", AWM_ALL, makeWindowCallback(callallcallbacks, 2));
1231        awmm->insert_menu_topic("!run_all_cbs_nloc",  "Call all callbacks (code-reverse)",    "o", "", AWM_ALL, makeWindowCallback(callallcallbacks, 3));
1232        awmm->insert_menu_topic("!run_all_cbs_rnd",   "Call all callbacks (random)",          "r", "", AWM_ALL, makeWindowCallback(callallcallbacks, 4));
1233        awmm->sep______________();
1234        awmm->insert_menu_topic("!forget_called_cbs", "Forget called",     "F", "", AWM_ALL, makeWindowCallback(callallcallbacks, -1));
1235        awmm->insert_menu_topic("!mark_all_called",   "Mark all called",   "M", "", AWM_ALL, makeWindowCallback(callallcallbacks, -2));
1236        awmm->sep______________();
1237        {
1238            awmm->insert_sub_menu("Call repeated", "p", AWM_ALL);
1239            awmm->insert_menu_topic("!run_all_cbs_alph_inf",  "Call all callbacks (alpha-order repeated)",     "a", "", AWM_ALL, makeWindowCallback(callallcallbacks, 8|0));
1240            awmm->insert_menu_topic("!run_all_cbs_nalph_inf", "Call all callbacks (alpha-reverse repeated)",   "l", "", AWM_ALL, makeWindowCallback(callallcallbacks, 8|1));
1241            awmm->insert_menu_topic("!run_all_cbs_loc_inf",   "Call all callbacks (code-order repeated)",      "c", "", AWM_ALL, makeWindowCallback(callallcallbacks, 8|2));
1242            awmm->insert_menu_topic("!run_all_cbs_nloc_inf",  "Call all callbacks (code-reverse repeated)",    "o", "", AWM_ALL, makeWindowCallback(callallcallbacks, 8|3));
1243            awmm->insert_menu_topic("!run_all_cbs_rnd_inf",   "Call all callbacks (random repeated)",          "r", "", AWM_ALL, makeWindowCallback(callallcallbacks, 8|4));
1244            awmm->close_sub_menu();
1245        }
1246        awmm->close_sub_menu();
1247    }
1248    awmm->sep______________();
1249
1250    awmm->insert_menu_topic(awmm->local_id("-client_ntree"), "Start ARB_NTREE as client", "N", "", AWM_ALL, makeWindowCallback(AW_system_async_cb, "arb_ntree :"));
1251}
1252
1253#if 1
1254void AWT_check_action_ids(AW_root *, const char *) {
1255}
1256#else
1257void AWT_check_action_ids(AW_root *aw_root, const char *suffix) {
1258    // check actions ids (see #428)
1259    // suffix is appended to filenames (needed if one application may have different states)
1260    GB_ERROR error = NULp;
1261    {
1262        SmartPtr<ConstStrArray> action_ids = aw_root->get_action_ids();
1263
1264        const char *checksdir = GB_path_in_ARBLIB("macros/.checks");
1265        char       *save      = GBS_global_string_copy("%s/%s%s_action.ids", checksdir, aw_root->program_name, suffix);
1266
1267        FILE *out       = fopen(save, "wt");
1268        if (!out) error = GB_IO_error("writing", save);
1269        else {
1270            for (size_t i = 0; i<action_ids->size(); ++i) {
1271                fprintf(out, "%s\n", (*action_ids)[i]);
1272            }
1273            fclose(out);
1274        }
1275
1276        if (!error) {
1277            char *expected              = GBS_global_string_copy("%s.expected", save);
1278            bool  IDs_have_changed      = ARB_textfiles_have_difflines(expected, save, 0, TDM_NOT_DIFF_LINECOUNT);
1279            if (IDs_have_changed) error = GBS_global_string("action ids differ from expected (see console)");
1280            free(expected);
1281        }
1282
1283        if (!error) GB_unlink(save);
1284        free(save);
1285    }
1286    if (error) fprintf(stderr, "AWT_check_action_ids: Error: %s\n", error);
1287}
1288#endif
1289
1290#endif // DEBUG
1291
1292AW_root *AWT_create_root(const char *properties, const char *program, UserActionTracker *user_tracker) {
1293    AW_root *aw_root = new AW_root(properties, program, false, user_tracker);
1294#if defined(DEBUG)
1295    AWT_announce_properties_to_browser(AW_ROOT_DEFAULT, properties);
1296#endif // DEBUG
1297    init_Advisor(aw_root);
1298    return aw_root;
1299}
1300
1301void AWT_trigger_remote_action(UNFIXED, GBDATA *gb_main, const char *remote_action_spec) {
1302    /*! trigger one or several action(s) (e.g. menu entries) in remote applications
1303     * @param gb_main             database root
1304     * @param remote_action_spec  "app:action[;app:action]*"
1305     */
1306
1307    ConstStrArray appAction;
1308    GBT_split_string(appAction, remote_action_spec, ";", SPLIT_DROPEMPTY);
1309
1310    GB_ERROR error = NULp;
1311    if (appAction.empty()) {
1312        error = "No action found";
1313    }
1314    else {
1315        for (unsigned a = 0; a<appAction.size() && !error; ++a) {
1316            ConstStrArray cmd;
1317            GBT_split_string(cmd, appAction[a], ":", SPLIT_DROPEMPTY);
1318
1319            if (cmd.size() != 2) {
1320                error = GBS_global_string("Invalid action '%s'", appAction[a]);
1321            }
1322            else {
1323                const char *app    = cmd[0];
1324                const char *action = cmd[1];
1325
1326                ARB_timeout after(2000, MS);
1327                error = GBT_remote_action_with_timeout(gb_main, app, action, &after, false);
1328            }
1329        }
1330    }
1331
1332    aw_message_if(error);
1333}
1334
1335// ------------------------
1336//      callback guards
1337
1338static void before_callback_guard() {
1339    if (GB_have_error()) {
1340        GB_ERROR error = GB_await_error();
1341        aw_message(GBS_global_string("Error not clear before calling callback\n"
1342                                     "Unhandled error was:\n"
1343                                     "%s", error));
1344#if defined(DEVEL_RALF)
1345        arb_assert(0);
1346#endif // DEVEL_RALF
1347    }
1348}
1349static void after_callback_guard() {
1350    if (GB_have_error()) {
1351        GB_ERROR error = GB_await_error();
1352        aw_message(GBS_global_string("Error not handled by callback!\n"
1353                                     "Unhandled error was:\n"
1354                                     "'%s'", error));
1355#if defined(DEVEL_RALF)
1356        arb_assert(0);
1357#endif // DEVEL_RALF
1358    }
1359}
1360
1361void AWT_install_cb_guards() {
1362    arb_assert(!GB_have_error());
1363    AW_cb::set_AW_cb_guards(before_callback_guard, after_callback_guard);
1364}
1365void AWT_install_postcb_cb(AW_postcb_cb postcb_cb) {
1366    AW_cb::set_AW_postcb_cb(postcb_cb);
1367}
1368
Note: See TracBrowser for help on using the repository browser.