summaryrefslogtreecommitdiff
path: root/atari/gui.c
blob: c0b8cb2fb2f1336f70cad0c96dcf60fb3948c9f7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
/*
 * Copyright 2010 <ole@monochrom.net>
 *
 * This file is part of NetSurf, http://www.netsurf-browser.org/
 *
 * NetSurf is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; version 2 of the License.
 *
 * NetSurf is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

/*
	This File provides all the mandatory functions prefixed with gui_
*/

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <time.h>
#include <limits.h>
#include <unistd.h>
#include <string.h>
#include <stdbool.h>
#include <hubbub/hubbub.h>

#include "content/urldb.h"
#include "content/fetch.h"
#include "content/fetchers/resource.h"
#include "css/utils.h"
#include "desktop/gui.h"
#include "desktop/local_history.h"
#include "desktop/plotters.h"
#include "desktop/netsurf.h"
#include "desktop/401login.h"

#include "utils/nsoption.h"
#include "desktop/save_complete.h"
#include "desktop/textinput.h"
#include "desktop/treeview.h"
#include "desktop/browser.h"
#include "desktop/browser_private.h"
#include "desktop/mouse.h"
#include "render/font.h"
#include "utils/schedule.h"
#include "utils/url.h"
#include "utils/log.h"
#include "utils/messages.h"
#include "utils/utils.h"

#include "atari/gemtk/gemtk.h"
#include "atari/gui.h"
#include "atari/misc.h"
#include "atari/findfile.h"
#include "atari/schedule.h"
#include "atari/rootwin.h"
#include "atari/statusbar.h"
#include "atari/toolbar.h"
#include "atari/hotlist.h"
#include "atari/cookies.h"
#include "atari/history.h"
#include "atari/login.h"
#include "atari/encoding.h"
#include "atari/res/netsurf.rsh"
#include "atari/plot/plot.h"
#include "atari/clipboard.h"
#include "atari/osspec.h"
#include "atari/search.h"
#include "atari/deskmenu.h"
#include "cflib.h"

#define TODO() (0)/*printf("%s Unimplemented!\n", __FUNCTION__)*/

struct gui_window *input_window = NULL;
struct gui_window *window_list = NULL;
void * h_gem_rsrc;
long next_poll;
bool rendering = false;
GRECT desk_area;


/* Comandline / Options: */
int option_window_width;
int option_window_height;
int option_window_x;
int option_window_y;

/* Defaults to option_homepage_url, commandline options overwrites that value */
const char * option_homepage_url;

/* path to choices file: */
char options[PATH_MAX];

EVMULT_IN aes_event_in = {
    .emi_flags = MU_MESAG | MU_TIMER | MU_KEYBD | MU_BUTTON | MU_M1,
    .emi_bclicks = 258,
    .emi_bmask = 3,
    .emi_bstate = 0,
    .emi_m1leave = MO_ENTER,
    .emi_m1 = {0,0,0,0},
    .emi_m2leave = 0,
    .emi_m2 = {0,0,0,0},
    .emi_tlow = 0,
    .emi_thigh = 0
};
EVMULT_OUT aes_event_out;
short aes_msg_out[8];



void gui_poll(bool active)
{

	struct gui_window *tmp;
    short mx, my, dummy;
    unsigned short nkc = 0;

    aes_event_in.emi_tlow = schedule_run();

    if(active || rendering)
        aes_event_in.emi_tlow = 0;

    if(aes_event_in.emi_tlow < 0) {
        aes_event_in.emi_tlow = 10000;
        printf("long poll!\n");
    }

    struct gui_window * g;

    if( !active ) {
        if(input_window && input_window->root->redraw_slots.areas_used > 0) {
            window_process_redraws(input_window->root);
        }
    }

    graf_mkstate(&mx, &my, &dummy, &dummy);
    aes_event_in.emi_m1.g_x = mx;
    aes_event_in.emi_m1.g_y = my;
    evnt_multi_fast(&aes_event_in, aes_msg_out, &aes_event_out);
    if(gemtk_wm_dispatch_event(&aes_event_in, &aes_event_out, aes_msg_out) == 0) {
        if( (aes_event_out.emo_events & MU_MESAG) != 0 ) {
            LOG(("WM: %d\n", aes_msg_out[0]));
            switch(aes_msg_out[0]) {

            case MN_SELECTED:
                LOG(("Menu Item: %d\n",aes_msg_out[4]));
                deskmenu_dispatch_item(aes_msg_out[3], aes_msg_out[4]);
                break;
            default:
                break;
            }
        }
        if((aes_event_out.emo_events & MU_KEYBD) != 0) {
            uint16_t nkc = gem_to_norm( (short)aes_event_out.emo_kmeta,
                                        (short)aes_event_out.emo_kreturn);
            deskmenu_dispatch_keypress(aes_event_out.emo_kreturn,
                                       aes_event_out.emo_kmeta, nkc);
        }
    }

    tmp = window_list;
    while(tmp){
		if(tmp->root->redraw_slots.areas_used > 0){
			window_process_redraws(tmp->root);
		}
		tmp = tmp->next;
    }

	// TODO: implement generic treeview redraw function
	// TODO: rename hl to atari_hotlist or create getter for it...

	atari_hotlist_redraw();
	atari_cookie_manager_redraw();
	atari_global_history_redraw();

}


struct gui_window *
gui_create_browser_window(struct browser_window *bw,
                          struct browser_window *clone,
                          bool new_tab) {
    struct gui_window *gw=NULL;
    LOG(( "gw: %p, BW: %p, clone %p, tab: %d\n" , gw,  bw, clone,
          (int)new_tab
        ));

    gw = calloc( sizeof(struct gui_window), 1);
    if (gw == NULL)
        return NULL;

    LOG(("new window: %p, bw: %p\n", gw, bw));
    window_create(gw, bw, clone, WIDGET_STATUSBAR|WIDGET_TOOLBAR|WIDGET_RESIZE\
                  |WIDGET_SCROLL);
    if (gw->root->win) {
        GRECT pos = {
            option_window_x, option_window_y,
            option_window_width, option_window_height
        };
        gui_window_set_url(gw, "");
        gui_window_set_pointer(gw, BROWSER_POINTER_DEFAULT);
        gui_set_input_gui_window(gw);
        window_open(gw->root, gw, pos);
    }

    /* add the window to the window list: */
    if( window_list == NULL ) {
        window_list = gw;
        gw->next = NULL;
        gw->prev = NULL;
    } else {
        struct gui_window * tmp = window_list;
        while( tmp->next != NULL ) {
            tmp = tmp->next;
        }
        tmp->next = gw;
        gw->prev = tmp;
        gw->next = NULL;
    }

    return( gw );

}

void gui_window_destroy(struct gui_window *w)
{
    if (w == NULL)
        return;

    LOG(("%s\n", __FUNCTION__ ));

    if (input_window == w) {
        gui_set_input_gui_window(NULL);
    }

    nsatari_search_session_destroy(w->search);
    free(w->browser);
    free(w->status);
    free(w->title);
    free(w->url);

    /* unlink the window: */
    if(w->prev != NULL ) {
        w->prev->next = w->next;
    } else {
        window_list = w->next;
    }
    if( w->next != NULL ) {
        w->next->prev = w->prev;
    }

    window_unref_gui_window(w->root, w);

    free(w);
    w = NULL;

    if(input_window == NULL) {
        w = window_list;
        while( w != NULL ) {
            if(w->root) {
                gui_set_input_gui_window(w);
                break;
            }
            w = w->next;
        }
    }
}

void gui_window_get_dimensions(struct gui_window *w, int *width, int *height,
                               bool scaled)
{
    if (w == NULL)
        return;
    GRECT rect;
    window_get_grect(w->root, BROWSER_AREA_CONTENT, &rect);
    *width = rect.g_w;
    *height = rect.g_h;
}

void gui_window_set_title(struct gui_window *gw, const char *title)
{

    if (gw == NULL)
        return;

    if (gw->root) {

        int l;
        char * conv;
        l = strlen(title)+1;
        if (utf8_to_local_encoding(title, l-1, &conv) == UTF8_CONVERT_OK ) {
            l = MIN((uint32_t)atari_sysinfo.aes_max_win_title_len, strlen(conv));
            if(gw->title == NULL)
                gw->title = malloc(l);
            else
                gw->title = realloc(gw->title, l);

            strncpy(gw->title, conv, l);
            free( conv );
        } else {
            l = MIN((size_t)atari_sysinfo.aes_max_win_title_len, strlen(title));
            if(gw->title == NULL)
                gw->title = malloc(l);
            else
                gw->title = realloc(gw->title, l);
            strncpy(gw->title, title, l);
        }
        gw->title[l] = 0;
        if(input_window == gw)
            window_set_title(gw->root, gw->title);
    }
}

/**
 * set the status bar message
 */
void gui_window_set_status(struct gui_window *w, const char *text)
{
    int l;
    if (w == NULL || text == NULL)
        return;

    assert(w->root);

    l = strlen(text)+1;
    if(w->status == NULL)
        w->status = malloc(l);
    else
        w->status = realloc(w->status, l);

    strncpy(w->status, text, l);
    w->status[l] = 0;

    if(input_window == w)
        window_set_stauts(w->root, (char*)text);
}

void gui_window_redraw_window(struct gui_window *gw)
{
    CMP_BROWSER b;
    GRECT rect;
    if (gw == NULL)
        return;
    b = gw->browser;
    window_get_grect(gw->root, BROWSER_AREA_CONTENT, &rect);
    window_schedule_redraw_grect(gw->root, &rect);
}

void gui_window_update_box(struct gui_window *gw, const struct rect *rect)
{
    GRECT area;
    struct gemtk_wm_scroll_info_s *slid;

    if (gw == NULL)
        return;

    slid = gemtk_wm_get_scroll_info(gw->root->win);

    window_get_grect(gw->root, BROWSER_AREA_CONTENT, &area);
    area.g_x += rect->x0 - (slid->x_pos * slid->x_unit_px);
    area.g_y += rect->y0 - (slid->y_pos * slid->y_unit_px);
    area.g_w = rect->x1 - rect->x0;
    area.g_h = rect->y1 - rect->y0;
    //dbg_grect("update box", &area);
    window_schedule_redraw_grect(gw->root, &area);
}

bool gui_window_get_scroll(struct gui_window *w, int *sx, int *sy)
{
    int x,y;
    if (w == NULL)
        return false;

    window_get_scroll(w->root, sx, sy);

    return( true );
}

void gui_window_set_scroll(struct gui_window *w, int sx, int sy)
{
    int units = 0;
    if ((w == NULL)
            || (w->browser->bw == NULL)
            || (w->browser->bw->current_content == NULL))
        return;

    LOG(("scroll (gui_window: %p) %d, %d\n", w, sx, sy));
    window_scroll_by(w->root, sx, sy);
    return;

}

void gui_window_scroll_visible(struct gui_window *w, int x0, int y0, int x1, int y1)
{
    LOG(("%s:(%p, %d, %d, %d, %d)", __func__, w, x0, y0, x1, y1));
    gui_window_set_scroll(w,x0,y0);
}


/* It seems this method is called when content size got adjusted,
	so that we can adjust scroll info. We also have to call it when tab
	change occurs.
*/
void gui_window_update_extent(struct gui_window *gw)
{

    if( gw->browser->bw->current_content != NULL ) {
        // TODO: store content size!
        if(window_get_active_gui_window(gw->root) == gw) {
            window_set_content_size( gw->root,
                                     content_get_width(gw->browser->bw->current_content),
                                     content_get_height(gw->browser->bw->current_content)
                                   );
            window_update_back_forward(gw->root);
            GRECT area;
            window_get_grect(gw->root, BROWSER_AREA_CONTENT, &area);
            window_schedule_redraw_grect(gw->root, &area);
        }
    }
}


void gui_clear_selection(struct gui_window *g)
{

}



/**
 * set the pointer shape
 */
void gui_window_set_pointer(struct gui_window *gw, gui_pointer_shape shape)
{
    if (gw == NULL)
        return;

    switch (shape) {
    case GUI_POINTER_POINT: /* link */
        gw->cursor = &gem_cursors.hand;
        break;

    case GUI_POINTER_MENU:
        gw->cursor = &gem_cursors.menu;
        break;

    case GUI_POINTER_CARET: /* input */
        gw->cursor = &gem_cursors.ibeam;
        break;

    case GUI_POINTER_CROSS:
        gw->cursor = &gem_cursors.cross;
        break;

    case GUI_POINTER_MOVE:
        gw->cursor = &gem_cursors.sizeall;
        break;

    case GUI_POINTER_RIGHT:
    case GUI_POINTER_LEFT:
        gw->cursor = &gem_cursors.sizewe;
        break;

    case GUI_POINTER_UP:
    case GUI_POINTER_DOWN:
        gw->cursor = &gem_cursors.sizens;
        break;

    case GUI_POINTER_RU:
    case GUI_POINTER_LD:
        gw->cursor = &gem_cursors.sizenesw;
        break;

    case GUI_POINTER_RD:
    case GUI_POINTER_LU:
        gw->cursor = &gem_cursors.sizenwse;
        break;

    case GUI_POINTER_WAIT:
        gw->cursor = &gem_cursors.wait;
        break;

    case GUI_POINTER_PROGRESS:
        gw->cursor = &gem_cursors.appstarting;
        break;

    case GUI_POINTER_NO_DROP:
        gw->cursor = &gem_cursors.nodrop;
        break;

    case GUI_POINTER_NOT_ALLOWED:
        gw->cursor = &gem_cursors.deny;
        break;

    case GUI_POINTER_HELP:
        gw->cursor = &gem_cursors.help;
        break;

    default:
        gw->cursor = &gem_cursors.arrow;
        break;
    }

    if (input_window == gw) {
        gem_set_cursor(gw->cursor);
    }
}

void gui_window_hide_pointer(struct gui_window *w)
{
    TODO();
}


void gui_window_set_url(struct gui_window *w, const char *url)
{
    int l;

    if (w == NULL)
        return;

    l = strlen(url)+1;

    if (w->url == NULL) {
        w->url = malloc(l);
    } else {
        w->url = realloc(w->url, l);
    }
    strncpy(w->url, url, l);
    w->url[l] = 0;
    if(input_window == w->root->active_gui_window) {
        toolbar_set_url(w->root->toolbar, url);
    }
}

struct gui_window * gui_window_get_input_window(void)
{
	return(input_window);
}

char * gui_window_get_url(struct gui_window *gw)
{
	if (gw == NULL) {
		return(NULL);
	}
	return(gw->url);
}

char * gui_window_get_title(struct gui_window *gw)
{
	if (gw == NULL) {
		return(NULL);
	}
	return(gw->title);
}

static void throbber_advance( void * data )
{

    struct gui_window * gw = (struct gui_window *)data;

    if (gw->root == NULL)
        return;
    if (gw->root->toolbar == NULL)
        return;

    if (gw->root->toolbar->throbber.running == false)
        return;

    toolbar_throbber_progress(gw->root->toolbar);
    schedule(100, throbber_advance, gw );
}

void gui_window_start_throbber(struct gui_window *w)
{
    GRECT work;
    if (w == NULL)
        return;

    toolbar_set_throbber_state(w->root->toolbar, true);
    schedule(100, throbber_advance, w );
    rendering = true;
}

void gui_window_stop_throbber(struct gui_window *w)
{
    if (w == NULL)
        return;
    if (w->root->toolbar->throbber.running == false)
        return;

    schedule_remove(throbber_advance, w);

    toolbar_set_throbber_state(w->root->toolbar, false);

    rendering = false;
}

/* Place caret in window */
void gui_window_place_caret(struct gui_window *w, int x, int y, int height,
		const struct rect *clip)
{
    window_place_caret(w->root, 1, x, y, height, NULL);
    w->root->caret.state |= CARET_STATE_ENABLED;
    return;
}


/**
 * clear window caret
 */
void
gui_window_remove_caret(struct gui_window *w)
{
    if (w == NULL)
        return;

    if ((w->root->caret.state & CARET_STATE_ENABLED) != 0) {
        //printf("gw hide caret\n");
        window_place_caret(w->root, 0, -1, -1, -1, NULL);
        w->root->caret.state &= ~CARET_STATE_ENABLED;
    }
    return;
}

void
gui_window_set_icon(struct gui_window *g, hlcache_handle *icon)
{
    struct bitmap *bmp_icon;

    bmp_icon = (icon != NULL) ? content_get_bitmap(icon) : NULL;
    g->icon = bmp_icon;
    if(input_window == g) {
        window_set_icon(g->root, bmp_icon);
    }
}

void
gui_window_set_search_ico(hlcache_handle *ico)
{
    TODO();
}

void gui_window_new_content(struct gui_window *w)
{
    struct gemtk_wm_scroll_info_s *slid = gemtk_wm_get_scroll_info(w->root->win);
    slid->x_pos = 0;
    slid->y_pos = 0;
    gemtk_wm_update_slider(w->root->win, GEMTK_WM_VH_SLIDER);
    gui_window_redraw_window(w);
}

bool gui_window_scroll_start(struct gui_window *w)
{
    TODO();
    return true;
}

bool gui_window_drag_start(struct gui_window *g, gui_drag_type type,
                           const struct rect *rect)
{
    TODO();
    return true;
}

void gui_window_save_link(struct gui_window *g, const char *url,
                          const char *title)
{
    LOG(("%s -> %s", title, url ));
    TODO();
}

void gui_drag_save_object(gui_save_type type, hlcache_handle *c,
                          struct gui_window *w)
{
    LOG((""));
    TODO();
}

void gui_drag_save_selection(struct gui_window *g, const char *selection)
{
    LOG((""));
    TODO();
}

void gui_start_selection(struct gui_window *w)
{

}


/**
 * Core asks front end for clipboard contents.
 *
 * \param  buffer  UTF-8 text, allocated by front end, ownership yeilded to core
 * \param  length  Byte length of UTF-8 text in buffer
 */
void gui_get_clipboard(char **buffer, size_t *length)
{
    char *clip;
    size_t clip_len;

    *length = 0;
    *buffer = 0;

    clip = scrap_txt_read();

    if(clip == NULL) {
        return;
    } else {

        // clipboard is in atari encoding, convert it to utf8:

        char *utf8 = NULL;
        utf8_convert_ret ret;

        clip_len = strlen(clip);
        if (clip_len > 0) {
            ret = utf8_to_local_encoding(clip, clip_len, &utf8);
            if (ret == UTF8_CONVERT_OK && utf8 != NULL) {
                *buffer = utf8;
                *length = strlen(utf8);
            } else {
                assert(ret == UTF8_CONVERT_OK && utf8 != NULL);
            }
        }

        free(clip);
    }
}

/**
 * Core tells front end to put given text in clipboard
 *
 * \param  buffer    UTF-8 text, owned by core
 * \param  length    Byte length of UTF-8 text in buffer
 * \param  styles    Array of styles given to text runs, owned by core, or NULL
 * \param  n_styles  Number of text run styles in array
 */
void gui_set_clipboard(const char *buffer, size_t length,
                       nsclipboard_styles styles[], int n_styles)
{
    if (length > 0 && buffer != NULL) {

        // convert utf8 input to atari encoding:

        utf8_convert_ret ret;
        char *clip = NULL;

        ret = utf8_to_local_encoding(buffer,length, &clip);
        if (ret == UTF8_CONVERT_OK) {
            scrap_txt_write(clip);
        } else {
            assert(ret == UTF8_CONVERT_OK);
        }
        free(clip);
    }
}


void gui_create_form_select_menu(struct browser_window *bw,
                                 struct form_control *control)
{
    TODO();
}

/**
 * Broadcast an URL that we can't handle.
 */
void gui_launch_url(const char *url)
{
    TODO();
    LOG(("launch file: %s\n", url));
}

void gui_401login_open(nsurl *url, const char *realm,
                       nserror (*cb)(bool proceed, void *pw), void *cbpw)
{
    bool bres;
    char * out = NULL;
    bres = login_form_do( url, (char*)realm, &out);
    if (bres) {
        LOG(("url: %s, realm: %s, auth: %s\n", url, realm, out ));
        urldb_set_auth_details(url, realm, out);
    }
    if (out != NULL) {
        free( out );
    }
    if (cb != NULL) {
        cb(bres, cbpw);
    }

}

void gui_cert_verify(nsurl *url, const struct ssl_cert_info *certs,
                     unsigned long num,
                     nserror (*cb)(bool proceed, void *pw), void *cbpw)
{
    LOG((""));

    bool bres;

    // TODO: localize string
    int b = form_alert(1, "[2][SSL Verify failed, continue?][Continue|Abort]");
    bres = (b==1)? true : false;
    LOG(("Trust: %d", bres ));
    urldb_set_cert_permissions(url, bres);
    cb(bres, cbpw);
}

void gui_set_input_gui_window(struct gui_window *gw)
{
    LOG(("Setting input window from: %p to %p\n", input_window, gw));
    input_window = gw;
}

void gui_quit(void)
{
    LOG((""));

    struct gui_window * gw = window_list;
    struct gui_window * tmp = window_list;

	/* Destroy all remaining browser windows: */
    while (gw) {
        tmp = gw->next;
        browser_window_destroy(gw->browser->bw);
        gw = tmp;
    }

	/* destroy the treeview windows: */
    atari_global_history_destroy();
    atari_hotlist_destroy();
    atari_cookie_manager_destroy();

	/* shutdown netsurf treeview framework: */
    treeview_fini();

	/* shutdown the toolbar framework: */
    toolbar_exit();

	/* save persistent informations: */
    urldb_save_cookies(nsoption_charp(cookie_file));
    urldb_save(nsoption_charp(url_file));

    deskmenu_destroy();
    gemtk_wm_exit();

    rsrc_free();

    LOG(("Shutting down plotter"));
    plot_finalise();
    LOG(("done"));
}




static bool
process_cmdline(int argc, char** argv)
{
    int opt;
    bool set_default_dimensions = true;

    LOG(("argc %d, argv %p", argc, argv));

    if ((nsoption_int(window_width) != 0) && (nsoption_int(window_height) != 0)) {

        option_window_width = nsoption_int(window_width);
        option_window_height = nsoption_int(window_height);
        option_window_x = nsoption_int(window_x);
        option_window_y = nsoption_int(window_y);

        if (option_window_width <= desk_area.g_w
                && option_window_height < desk_area.g_h) {
            set_default_dimensions = false;
        }
    }

    if (set_default_dimensions) {
        if( sys_type() == SYS_TOS ) {
            /* on single tasking OS, start as fulled window: */
            option_window_width = desk_area.g_w;
            option_window_height = desk_area.g_h;
            option_window_x = desk_area.g_w/2-(option_window_width/2);
            option_window_y = (desk_area.g_h/2)-(option_window_height/2);
        } else {
            option_window_width = 600;
            option_window_height = 360;
            option_window_x = 10;
            option_window_y = 30;
        }
    }

    if (nsoption_charp(homepage_url) != NULL)
        option_homepage_url = nsoption_charp(homepage_url);
    else
        option_homepage_url = NETSURF_HOMEPAGE;

    while((opt = getopt(argc, argv, "w:h:")) != -1) {
        switch (opt) {
        case 'w':
            option_window_width = atoi(optarg);
            break;

        case 'h':
            option_window_height = atoi(optarg);
            break;

        default:
            fprintf(stderr,
                    "Usage: %s [w,h,v] url\n",
                    argv[0]);
            return false;
        }
    }

    if (optind < argc) {
        option_homepage_url = argv[optind];
    }
    return true;
}

static inline void create_cursor(int flags, short mode, void * form,
                                 MFORM_EX * m)
{
    m->flags = flags;
    m->number = mode;
    if( flags & MFORM_EX_FLAG_USERFORM ) {
        m->number = mode;
        m->tree = (OBJECT*)form;
    }
}

nsurl *gui_get_resource_url(const char *path)
{
    char buf[PATH_MAX];
    char *raw;
    nsurl *url = NULL;

    atari_find_resource((char*)&buf, path, path);
    raw = path_to_url((char*)&buf);
    if (raw != NULL) {
        nsurl_create(raw, &url);
        free(raw);
    }

    return url;
}

/**
 * Set option defaults for atari frontend
 *
 * @param defaults The option table to update.
 * @return error status.
 */
static nserror set_defaults(struct nsoption_s *defaults)
{
    /* Set defaults for absent option strings */
    nsoption_setnull_charp(cookie_file, strdup("cookies"));
    if (nsoption_charp(cookie_file) == NULL) {
        LOG(("Failed initialising string options"));
	return NSERROR_BAD_PARAMETER;
    }
    return NSERROR_OK;
}

static void gui_init(int argc, char** argv)
{
    char buf[PATH_MAX];
    OBJECT * cursors;

    atari_find_resource(buf, "netsurf.rsc", "./res/netsurf.rsc");
    LOG(("Using RSC file: %s ", (char*)&buf));
    if (rsrc_load(buf)==0) {

		char msg[1024];

		snprintf(msg, 1024, "Unable to open GEM Resource file (%s)!", buf);
        die(msg);
    }

    wind_get_grect(0, WF_WORKXYWH, &desk_area);

    create_cursor(0, POINT_HAND, NULL, &gem_cursors.hand );
    create_cursor(0, TEXT_CRSR,  NULL, &gem_cursors.ibeam );
    create_cursor(0, THIN_CROSS, NULL, &gem_cursors.cross);
    create_cursor(0, BUSY_BEE, NULL, &gem_cursors.wait);
    create_cursor(0, ARROW, NULL, &gem_cursors.arrow);
    create_cursor(0, OUTLN_CROSS, NULL, &gem_cursors.sizeall);
    create_cursor(0, OUTLN_CROSS, NULL, &gem_cursors.sizenesw);
    create_cursor(0, OUTLN_CROSS, NULL, &gem_cursors.sizenwse);
    cursors = gemtk_obj_get_tree(CURSOR);
    create_cursor(MFORM_EX_FLAG_USERFORM, CURSOR_APPSTART,
                  cursors, &gem_cursors.appstarting);
    gem_set_cursor( &gem_cursors.appstarting );
    create_cursor(MFORM_EX_FLAG_USERFORM, CURSOR_SIZEWE,
                  cursors, &gem_cursors.sizewe);
    create_cursor(MFORM_EX_FLAG_USERFORM, CURSOR_SIZENS,
                  cursors, &gem_cursors.sizens);
    create_cursor(MFORM_EX_FLAG_USERFORM, CURSOR_NODROP,
                  cursors, &gem_cursors.nodrop);
    create_cursor(MFORM_EX_FLAG_USERFORM, CURSOR_DENY,
                  cursors, &gem_cursors.deny);
    create_cursor(MFORM_EX_FLAG_USERFORM, CURSOR_MENU,
                  cursors, &gem_cursors.menu);
    create_cursor(MFORM_EX_FLAG_USERFORM, CURSOR_HELP,
                  cursors, &gem_cursors.help);

    LOG(("Enabling core select menu"));
    nsoption_set_bool(core_select_menu, true);

    LOG(("Loading url.db from: %s", nsoption_charp(url_file) ));
    if( strlen(nsoption_charp(url_file)) ) {
        urldb_load(nsoption_charp(url_file));
    }

    LOG(("Loading cookies from: %s", nsoption_charp(cookie_file) ));
    if( strlen(nsoption_charp(cookie_file)) ) {
        urldb_load_cookies(nsoption_charp(cookie_file));
    }

    if (process_cmdline(argc,argv) != true)
        die("unable to process command line.\n");

    LOG(("Initializing NKC..."));
    nkc_init();


    LOG(("Initializing plotters..."));
    plot_init(nsoption_charp(atari_font_driver));

    aes_event_in.emi_m1leave = MO_LEAVE;
    aes_event_in.emi_m1.g_w = 1;
    aes_event_in.emi_m1.g_h = 1;
    //next_poll = clock() + (CLOCKS_PER_SEC>>3);
}

static char *theapp = (char*)"NetSurf";
static void gui_init2(int argc, char** argv)
{
    deskmenu_init();
    menu_register( -1, theapp);
    if (sys_type() & (SYS_MAGIC|SYS_NAES|SYS_XAAES)) {
        menu_register( _AESapid, (char*)"  NetSurf ");
    }
    gemtk_wm_init();

    /* Initialize the netsurf treeview framework with default font size: */
    treeview_init(0);

	/* Initialize the specific treeview windows: */
    atari_global_history_init();
    atari_hotlist_init();
    atari_cookie_manager_init();

    /* Initialize the toolbar framework: */
    toolbar_init();
}

/* #define WITH_DBG_LOGFILE 1 */
/** Entry point from OS.
 *
 * /param argc The number of arguments in the string vector.
 * /param argv The argument string vector.
 * /return The return code to the OS
 */
int main(int argc, char** argv)
{
    char messages[PATH_MAX];
    const char *addr;
    char * file_url = NULL;
    struct stat stat_buf;
    nsurl *url;
    nserror ret;

    /* @todo logging file descriptor update belongs in a nslog_init callback */
    setbuf(stderr, NULL);
    setbuf(stdout, NULL);
#ifdef WITH_DBG_LOGFILE
    freopen("stdout.log", "a+", stdout);
    freopen("stderr.log", "a+", stderr);
#endif

    graf_mouse(BUSY_BEE, NULL);

    init_app(NULL);

    init_os_info();

    atari_find_resource((char*)&messages, "messages", "res/messages");
    atari_find_resource((char*)&options, "Choices", "Choices");

    /* initialise logging - not fatal if it fails but not much we can
     * do about it
     */
    nslog_init(NULL, &argc, argv);

    /* user options setup */
    ret = nsoption_init(set_defaults, &nsoptions, &nsoptions_default);
    if (ret != NSERROR_OK) {
		die("Options failed to initialise");
    }
    nsoption_read(options, NULL);
    nsoption_commandline(&argc, argv, NULL);

    /* common initialisation */
    LOG(("Initialising core..."));
    ret = netsurf_init(messages);
    if (ret != NSERROR_OK) {
	die("NetSurf failed to initialise");
    }

    LOG(("Initializing GUI..."));
    gui_init(argc, argv);

    LOG(("Initializing GUI2"));
    gui_init2(argc, argv);

    graf_mouse( ARROW , NULL);

    LOG(("Creating initial browser window..."));
    addr = option_homepage_url;
    if (strncmp(addr, "file://", 7) && strncmp(addr, "http://", 7)) {
		if (stat(addr, &stat_buf) == 0) {
			file_url = local_file_to_url(addr);
			addr = file_url;
		}
    }

    /* create an initial browser window */
    ret = nsurl_create(addr, &url);
    if (ret == NSERROR_OK) {
	ret = browser_window_create(BROWSER_WINDOW_VERIFIABLE |
				    BROWSER_WINDOW_HISTORY,
				    url,
				    NULL,
				    NULL,
				    NULL);
	nsurl_unref(url);
    }
    if (ret != NSERROR_OK) {
	warn_user(messages_get_errorcode(ret), 0);
    } else {
	LOG(("Entering NetSurf mainloop..."));
	netsurf_main_loop();
    }

    netsurf_exit();

    free(file_url);

#ifdef WITH_DBG_LOGFILE
    fclose(stdout);
    fclose(stderr);
#endif
	LOG(("exit_gem"));
    exit_gem();

    return 0;
}