source: branches/stable/AWT/AWT_db_browser.cxx

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