[elm_cnp_helper.c] add convert from html tag to efl tag
[framework/uifw/elementary.git] / src / lib / elm_cnp_helper.c
1 #ifdef HAVE_CONFIG_H
2 # include "elementary_config.h"
3 #endif
4 #include <Elementary.h>
5 #include "elm_priv.h"
6
7 #include <sys/mman.h>
8
9 #ifdef HAVE_ELEMENTARY_X
10
11 #define ARRAYINIT(foo)  [foo] =
12
13 //#define DEBUGON 1
14
15
16 #ifdef DEBUGON
17 # define cnp_debug(x...) fprintf(stderr, __FILE__": " x)
18 #else
19 # define cnp_debug(x...)
20 #endif
21
22 #define PROVIDER_SET "__elm_cnp_provider_set"
23
24 typedef struct _Paste_Image   Paste_Image;
25 typedef struct _Cnp_Selection Cnp_Selection;
26 typedef struct _Escape        Escape;
27 typedef struct _Tmp_Info      Tmp_Info;
28 typedef struct _Cnp_Atom      Cnp_Atom;
29 typedef struct _Saved_Type    Saved_Type;
30 typedef struct _Dropable      Dropable;
31
32 typedef Eina_Bool (*Converter_Fn_Cb)     (char *target, void *data, int size, void **data_ret, int *size_ret, Ecore_X_Atom *ttype, int *typesize);
33 typedef int       (*Response_Handler_Cb) (Cnp_Selection *sel, Ecore_X_Event_Selection_Notify *);
34 typedef int       (*Notify_Handler_Cb)   (Cnp_Selection *sel, Ecore_X_Event_Selection_Notify *);
35
36 enum
37 {
38    CNP_ATOM_TARGETS = 0,
39    CNP_ATOM_text_uri,
40    CNP_ATOM_text_urilist,
41    CNP_ATOM_text_x_vcard,
42    CNP_ATOM_image_png,
43    CNP_ATOM_image_jpeg,
44    CNP_ATOM_image_bmp,
45    CNP_ATOM_image_gif,
46    CNP_ATOM_image_tiff,
47    CNP_ATOM_image_svg,
48    CNP_ATOM_image_xpm,
49    CNP_ATOM_image_tga,
50    CNP_ATOM_image_ppm,
51    CNP_ATOM_XELM,
52    CNP_ATOM_text_html_utf8,
53    CNP_ATOM_text_html,
54    CNP_ATOM_UTF8STRING,
55    CNP_ATOM_STRING,
56    CNP_ATOM_TEXT,
57    CNP_ATOM_text_plain_utf8,
58    CNP_ATOM_text_plain,
59
60    CNP_N_ATOMS,
61 };
62
63 struct _Paste_Image
64 {
65    Evas_Object *entry;
66    const char  *tag;
67    const char  *file;
68    Evas_Object *img;
69 };
70
71 struct _Cnp_Selection
72 {
73    const char      *debug;
74    Evas_Object     *widget;
75    char            *selbuf;
76    Evas_Object     *requestwidget;
77    void            *udata;
78    Elm_Sel_Format   requestformat;
79    Elm_Drop_Cb      datacb;
80    Eina_Bool      (*set)     (Ecore_X_Window, const void *data, int size);
81    Eina_Bool      (*clear)   (void);
82    void           (*request) (Ecore_X_Window, const char *target);
83
84    Elm_Sel_Format    format;
85    Ecore_X_Selection ecore_sel;
86
87    Eina_Bool         active : 1;
88 };
89
90 struct _Escape
91 {
92    const char *escape;
93    const char  value;
94 };
95
96 struct _Tmp_Info
97 {
98    char *filename;
99    void *map;
100    int   fd;
101    int   len;
102 };
103
104 struct _Cnp_Atom
105 {
106    const char          *name;
107    Elm_Sel_Format       formats;
108    /* Called by ecore to do conversion */
109    Converter_Fn_Cb      converter;
110    Response_Handler_Cb  response;
111    Notify_Handler_Cb    notify;
112    /* Atom */
113    Ecore_X_Atom         atom;
114 };
115
116 struct _Saved_Type
117 {
118    const char  **types;
119    Paste_Image  *pi;
120    int           ntypes;
121    int           x, y;
122    Eina_Bool     textreq: 1;
123 };
124
125 struct _Dropable
126 {
127    Evas_Object     *obj;
128    /* FIXME: Cache window */
129    Elm_Sel_Format   types;
130    Elm_Drop_Cb      dropcb;
131    void            *cbdata;
132 };
133
134 static Tmp_Info *elm_cnp_tempfile_create(int size);
135 static int tmpinfo_free(Tmp_Info *tmp);
136
137 static Eina_Bool _elm_cnp_init(void);
138 static Eina_Bool selection_clear(void *udata __UNUSED__, int type, void *event);
139 static Eina_Bool selection_notify(void *udata __UNUSED__, int type, void *event);
140 static char *remove_tags(const char *p, int *len);
141 static char *mark_up(const char *start, int inlen, int *lenp);
142
143 static Evas_Object *image_provider(void *images, Evas_Object *entry, const char *item);
144 static void entry_deleted(void *images, Evas *e, Evas_Object *entry, void *unused);
145
146
147 static Eina_Bool targets_converter(char *target, void *data, int size, void **data_ret, int *size_ret, Ecore_X_Atom *ttype, int *typesize);
148 static Eina_Bool text_converter(char *target, void *data, int size, void **data_ret, int *size_ret, Ecore_X_Atom *ttype, int *typesize);
149 static Eina_Bool html_converter(char *target, void *data, int size, void **data_ret, int *size_ret, Ecore_X_Atom *ttype, int *typesize);
150 static Eina_Bool edje_converter(char *target, void *data, int size, void **data_ret, int *size_ret, Ecore_X_Atom *ttype, int *typesize);
151 static Eina_Bool uri_converter(char *target, void *data, int size, void **data_ret, int *size_ret, Ecore_X_Atom *ttype, int *typesize);
152 static Eina_Bool image_converter(char *target, void *data, int size, void **data_ret, int *size_ret, Ecore_X_Atom *ttype, int *typesize);
153 static Eina_Bool vcard_send(char *target, void *data, int size, void **data_ret, int *size_ret, Ecore_X_Atom *ttype, int *typesize);
154
155 static int response_handler_targets(Cnp_Selection *sel, Ecore_X_Event_Selection_Notify *);
156
157 static int notify_handler_targets(Cnp_Selection *sel, Ecore_X_Event_Selection_Notify *notify);
158 static int notify_handler_text(Cnp_Selection *sel, Ecore_X_Event_Selection_Notify *notify);
159 static int notify_handler_image(Cnp_Selection *sel, Ecore_X_Event_Selection_Notify *notify);
160 static int notify_handler_uri(Cnp_Selection *sel, Ecore_X_Event_Selection_Notify *notify);
161 static int notify_handler_html(Cnp_Selection *sel, Ecore_X_Event_Selection_Notify *notify);
162 static int vcard_receive(Cnp_Selection *sed, Ecore_X_Event_Selection_Notify *notify);
163
164 static Paste_Image *pasteimage_alloc(const char *file, int pathlen);
165 static Eina_Bool pasteimage_append(Paste_Image *pi, Evas_Object *entry);
166 static void pasteimage_free(Paste_Image *pi);
167
168 /* Optimisation: Turn this into a 256 byte table:
169  *      then can lookup in one index, not N checks */
170 static const Escape escapes[] = {
171        { "<br>",   '\n' },
172        { "<\t>",   '\t' },
173        { "gt;",    '>'  },
174        { "lt;",    '<'  },
175        { "amp;",   '&'  },
176        { "quot;",  '\'' },
177        { "dquot;", '"'  }
178 };
179 #define N_ESCAPES ((int)(sizeof(escapes) / sizeof(escapes[0])))
180
181 static Cnp_Atom atoms[CNP_N_ATOMS] = {
182      [CNP_ATOM_TARGETS] = {
183           "TARGETS",
184           (Elm_Sel_Format) -1, // everything
185           targets_converter,
186           response_handler_targets,
187           notify_handler_targets,
188           0
189      },
190      [CNP_ATOM_XELM] =  {
191           "application/x-elementary-markup",
192           ELM_SEL_FORMAT_MARKUP,
193           edje_converter,
194           NULL,
195           NULL,
196           0
197      },
198      [CNP_ATOM_text_uri] = {
199           "text/uri",
200           ELM_SEL_FORMAT_MARKUP | ELM_SEL_FORMAT_IMAGE, /* Either images or entries */
201           uri_converter,
202           NULL,
203           notify_handler_uri,
204           0
205      },
206      [CNP_ATOM_text_urilist] = {
207           "text/uri-list",
208           ELM_SEL_FORMAT_IMAGE,
209           uri_converter,
210           NULL,
211           notify_handler_uri,
212           0
213      },
214      [CNP_ATOM_text_x_vcard] = {
215           "text/x-vcard",
216           ELM_SEL_FORMAT_VCARD,
217           vcard_send, NULL,
218           vcard_receive, 0
219      },
220      [CNP_ATOM_image_png] = {
221           "image/png",
222           ELM_SEL_FORMAT_IMAGE,
223           image_converter,
224           NULL,
225           notify_handler_image,
226           0
227      },
228      [CNP_ATOM_image_jpeg] = {
229           "image/jpeg",
230           ELM_SEL_FORMAT_IMAGE,
231           image_converter,
232           NULL,
233           notify_handler_image,/* Raw image data is the same */
234           0
235      },
236      [CNP_ATOM_image_bmp] = {
237           "image/x-ms-bmp",
238           ELM_SEL_FORMAT_IMAGE,
239           image_converter,
240           NULL,
241           notify_handler_image,/* Raw image data is the same */
242           0
243      },
244      [CNP_ATOM_image_gif] = {
245           "image/gif",
246           ELM_SEL_FORMAT_IMAGE,
247           image_converter,
248           NULL,
249           notify_handler_image,/* Raw image data is the same */
250           0
251      },
252      [CNP_ATOM_image_tiff] = {
253           "image/tiff",
254           ELM_SEL_FORMAT_IMAGE,
255           image_converter,
256           NULL,
257           notify_handler_image,/* Raw image data is the same */
258           0
259      },
260      [CNP_ATOM_image_svg] = {
261           "image/svg+xml",
262           ELM_SEL_FORMAT_IMAGE,
263           image_converter,
264           NULL,
265           notify_handler_image,/* Raw image data is the same */
266           0
267      },
268      [CNP_ATOM_image_xpm] = {
269           "image/x-xpixmap",
270           ELM_SEL_FORMAT_IMAGE,
271           image_converter,
272           NULL,
273           notify_handler_image,/* Raw image data is the same */
274           0
275      },
276      [CNP_ATOM_image_tga] = {
277           "image/x-tga",
278           ELM_SEL_FORMAT_IMAGE,
279           image_converter,
280           NULL,
281           notify_handler_image,/* Raw image data is the same */
282           0
283      },
284      [CNP_ATOM_image_ppm] = {
285           "image/x-portable-pixmap",
286           ELM_SEL_FORMAT_IMAGE,
287           image_converter,
288           NULL,
289           notify_handler_image,/* Raw image data is the same */
290           0
291      },
292      [CNP_ATOM_text_html_utf8] = {
293           "text/html;charset=utf-8",
294           ELM_SEL_FORMAT_HTML,
295           html_converter,
296           NULL,
297           notify_handler_html,
298           0
299      },
300      [CNP_ATOM_text_html] = {
301           "text/html",
302           ELM_SEL_FORMAT_HTML,
303           html_converter,
304           NULL,
305           notify_handler_html, /* No encoding: Webkit only */
306           0
307      },
308      [CNP_ATOM_UTF8STRING] = {
309           "UTF8_STRING",
310           ELM_SEL_FORMAT_TEXT | ELM_SEL_FORMAT_MARKUP | ELM_SEL_FORMAT_HTML,
311           text_converter,
312           NULL,
313           notify_handler_text,
314           0
315      },
316      [CNP_ATOM_STRING] = {
317           "STRING",
318           ELM_SEL_FORMAT_TEXT | ELM_SEL_FORMAT_MARKUP | ELM_SEL_FORMAT_HTML,
319           text_converter,
320           NULL,
321           notify_handler_text,
322           0
323      },
324      [CNP_ATOM_TEXT] = {
325           "TEXT",
326           ELM_SEL_FORMAT_TEXT | ELM_SEL_FORMAT_MARKUP | ELM_SEL_FORMAT_HTML,
327           text_converter,
328           NULL,
329           NULL,
330           0
331      },
332      [CNP_ATOM_text_plain_utf8] = {
333           "text/plain;charset=utf-8",
334           ELM_SEL_FORMAT_TEXT | ELM_SEL_FORMAT_MARKUP | ELM_SEL_FORMAT_HTML,
335           text_converter,
336           NULL,
337           NULL,
338           0
339      },
340      [CNP_ATOM_text_plain] = {
341           "text/plain",
342           ELM_SEL_FORMAT_TEXT | ELM_SEL_FORMAT_MARKUP | ELM_SEL_FORMAT_HTML,
343           text_converter,
344           NULL,
345           NULL,
346           0
347      },
348 };
349
350 static Cnp_Selection selections[ELM_SEL_MAX] = {
351      ARRAYINIT(ELM_SEL_PRIMARY) {
352           .debug = "Primary",
353           .ecore_sel = ECORE_X_SELECTION_PRIMARY,
354           .set = ecore_x_selection_primary_set,
355           .clear = ecore_x_selection_primary_clear,
356           .request = ecore_x_selection_primary_request,
357      },
358      ARRAYINIT(ELM_SEL_SECONDARY) {
359           .debug = "Secondary",
360           .ecore_sel = ECORE_X_SELECTION_SECONDARY,
361           .set = ecore_x_selection_secondary_set,
362           .clear = ecore_x_selection_secondary_clear,
363           .request = ecore_x_selection_secondary_request,
364      },
365      ARRAYINIT(ELM_SEL_CLIPBOARD) {
366           .debug = "Clipboard",
367           .ecore_sel = ECORE_X_SELECTION_CLIPBOARD,
368           .set = ecore_x_selection_clipboard_set,
369           .clear = ecore_x_selection_clipboard_clear,
370           .request = ecore_x_selection_clipboard_request,
371      },
372      ARRAYINIT(ELM_SEL_XDND) {
373           .debug = "XDnD",
374           .ecore_sel = ECORE_X_SELECTION_XDND,
375           .request = ecore_x_selection_xdnd_request,
376      },
377 };
378
379 /* Data for DND in progress */
380 static Saved_Type savedtypes =  { NULL, NULL, 0, 0, 0, EINA_FALSE };
381
382 static void (*dragdonecb) (void *data, Evas_Object *obj) = NULL;
383 static void *dragdonedata = NULL;
384
385 static int _elm_cnp_init_count = 0;
386 /* FIXME: who left this out of XAtoms.h */
387 static Ecore_X_Atom clipboard_atom;
388
389 static Eina_List *pastedimages = NULL;
390
391 /**
392  * Drag & Drop functions
393  */
394
395 /* FIXME: Way too many globals */
396 static Eina_List *drops = NULL;
397 static Evas_Object *dragwin = NULL;
398 static int _dragx = 0, _dragy = 0;
399 static Ecore_Event_Handler *handler_pos = NULL;
400 static Ecore_Event_Handler *handler_drop = NULL;
401 static Ecore_Event_Handler *handler_enter = NULL;
402 static Ecore_Event_Handler *handler_status = NULL;
403
404 #endif
405
406 /* Stringshared, so I can just compare pointers later */
407 static const char *text_uri;
408
409
410 /* For convert EFL to HTML */
411
412 #define TAGPOS_START    0x00000001
413 #define TAGPOS_END      0x00000002
414 #define TAGPOS_ALONE    0x00000003
415
416 /* TEXTBLOCK tag using stack but close tag word has no mean maybe bug...
417  * TEXTBLOCK <b>bold<font>font</b>bold</font>
418  * HTML <b>bold<font>font bold</b>font</font> */
419
420 typedef struct _TagTable {
421      char *src;
422      char *dst;
423      char tagType;
424 }TagTable;
425
426 TagTable _EFLtoHTMLConvertTable[] = {
427        {"font", "font", 0},
428        {"underline", "del", 0},
429        {"strikethrough", "ins", 0},
430        {"br", "br", 1},
431        {"b", "b", 1},
432        {"item", "img", 1}
433 };
434
435 TagTable _HTMLtoEFLConvertTable[] = {
436        {"font", "", 0},
437        {"del", "underline", 0},
438        {"u", "underline", 0},
439        {"ins", "strikethrough", 0},
440        {"s", "strikethrough", 0},
441        {"br", "br", 1},
442        {"b", "b", 1},
443        {"strong", "b", 1},
444        {"img", "item", 1}
445 };
446
447
448 typedef struct _TagNode TagNode, *PTagNode;
449 struct _TagNode {
450      char *tag;  //EINA_STRINGSHARE if NULL just str
451      char *tag_str;
452      char *str;
453      char *pos_in_ori_str;
454      PTagNode matchTag;
455      void *tagData;
456      unsigned char tagPosType;
457 };
458
459 typedef struct _FontTagData FontTagData, *PFontTagData;
460 struct _FontTagData {
461      char *name;
462      char *color;
463      char *size;
464      char *bg_color;
465 };
466
467
468 typedef struct _ItemTagData ItemTagData, *PItemTagData;
469 struct _ItemTagData {
470      char *href;
471      char *width;
472      char *height;
473 };
474
475 #define SAFEFREE(ptr) \
476    do\
477 {\
478    if (ptr)\
479    free(ptr);\
480    ptr = NULL;\
481 } while(0);\
482
483 #define freeAndAssign(dst, value) \
484    do\
485 {\
486    if (value)\
487      {\
488         SAFEFREE(dst);\
489         dst = value;\
490      }\
491 } while(0);
492
493
494 static PTagNode _new_tag_node(char *tag, char *tag_str, char* str, char *pos_in_ori_str);
495 static PTagNode _get_start_node(char *str);
496 static PTagNode _get_next_node(PTagNode prev);
497 static void _delete_node(PTagNode node);
498 static void _link_match_tags(Eina_List *nodes);
499 static char *_get_tag_value(const char *tag_str, const char *tag_name);
500 static char *_convert_to_html(Eina_List* nodes);
501 static void _set_EFL_tag_data(Eina_List* nodes);
502 static char *_convert_to_edje(Eina_List* nodes);
503 static void _set_HTML_tag_data(Eina_List* nodes);
504 static PFontTagData _set_EFL_font_data(PFontTagData data, const char *tag_str);
505 static PItemTagData _set_EFL_item_data(PItemTagData data, const char *tag_str);
506 static PFontTagData _set_HTML_font_data(PFontTagData data, const char *tag_str);
507 static PItemTagData _set_HTML_img_data(PItemTagData data, const char *tag_str);
508
509 #ifdef DEBUGON
510 static void _dumpNode(Eina_List* nodes);
511 #endif
512
513 static PTagNode
514 _new_tag_node(char *tag, char *tag_str, char* str, char *pos_in_ori_str)
515 {
516    PTagNode newNode = calloc(1, sizeof(TagNode));
517    newNode->tag = tag;
518    newNode->tag_str = tag_str;
519    newNode->str = str;
520    newNode->pos_in_ori_str = pos_in_ori_str;
521    return newNode;
522 }
523
524 static PTagNode
525 _get_start_node(char *str)
526 {
527    char *startStr = NULL;
528    if (!str || str[0] == '\0')
529      return NULL;
530
531    if (str[0] != '<')
532      {
533         char *tagStart = strchr(str, '<');
534         if (!tagStart)
535           startStr = strdup(str);
536         else
537           {
538              int strLength = tagStart - str;
539              startStr = malloc(sizeof(char) * (strLength + 1));
540              strncpy(startStr, str, strLength);
541              startStr[strLength] = '\0';
542           }
543      }
544
545    return _new_tag_node(NULL, NULL, startStr, str);
546 }
547
548 static PTagNode
549 _get_next_node(PTagNode prev)
550 {
551    PTagNode retTag = NULL;
552    char *tagStart;
553    char *tagEnd;
554    char *tagNameEnd = NULL;
555    char *nextTagStart;
556
557    if (prev->tag == NULL)
558      tagStart = strchr(prev->pos_in_ori_str, '<');
559    else
560      tagStart = strchr(prev->pos_in_ori_str + 1, '<');
561
562    if (!tagStart)
563      return retTag;
564
565    tagEnd = strchr(tagStart, '>');
566    nextTagStart = strchr(tagStart + 1, '<');
567
568    if (!tagEnd || (nextTagStart && (nextTagStart < tagEnd)))
569         return _get_start_node(tagStart + 1);
570
571    int spCnt = 5;
572    char *spArray[spCnt];
573    spArray[0] = strchr(tagStart, '=');
574    spArray[1] = strchr(tagStart, '_');
575    spArray[2] = strchr(tagStart, ' ');
576    spArray[3] = strchr(tagStart, '\t');
577    spArray[4] = strchr(tagStart, '\n');
578    tagNameEnd = tagEnd;
579
580    int i;
581    for (i = 0; i < spCnt; i++)
582      {
583         if (spArray[i] && spArray[i] < tagNameEnd)
584           tagNameEnd = spArray[i];
585      }
586
587    int tagLength = tagNameEnd - tagStart - 1;
588    char *tagName = NULL;
589    if (!strncmp(&tagStart[1], "color", tagLength))
590      tagName = strndup("font", 4);
591    else if (!strncmp(&tagStart[1], "/color", tagLength))
592      tagName = strndup("/font", 5);
593    else if (!strncmp(&tagStart[1], "/item", tagLength))
594      tagName = strdup("");
595    else
596      tagName = strndup(&tagStart[1], tagLength);
597
598    int tagStrLength = 0;
599    char *tagStr = NULL;
600    if (tagName)
601      {
602         tagStrLength = tagEnd - tagStart + 1;
603         tagStr = strndup(tagStart, tagStrLength);
604      }
605
606    unsigned int strLength = nextTagStart ? (unsigned int)(nextTagStart - tagEnd - 1) : strlen(&tagEnd[1]);
607    char *str = strndup(&tagEnd[1], strLength);
608
609    retTag = _new_tag_node(tagName, tagStr, str, tagStart);
610    return retTag;
611 }
612
613
614 static void
615 _delete_node(PTagNode node)
616 {
617    if (node)
618      {
619         SAFEFREE(node->tag_str);
620         SAFEFREE(node->str);
621
622         if (node->tagData)
623           {
624              if (node->tag)
625                {
626                   if (!strcmp("font", node->tag))
627                     {
628                        PFontTagData data = node->tagData;
629                        SAFEFREE(data->name);
630                        SAFEFREE(data->color);
631                        SAFEFREE(data->size);
632                        SAFEFREE(data->bg_color);
633                     }
634                   if (!strcmp("item", node->tag))
635                     {
636                        PItemTagData data = node->tagData;
637                        SAFEFREE(data->href);
638                        SAFEFREE(data->width);
639                        SAFEFREE(data->height);
640                     }
641
642                }
643              SAFEFREE(node->tagData);
644           }
645         SAFEFREE(node->tag);
646         SAFEFREE(node);
647      }
648 }
649
650 static void
651 _link_match_tags(Eina_List *nodes)
652 {
653    Eina_List *stack = NULL;
654
655    PTagNode trail, popData;
656    Eina_List *l, *r;
657
658    EINA_LIST_FOREACH(nodes, l, trail)
659      {
660         if (!trail->tag || trail->tag[0] == '\0')
661           continue;
662         if (!strcmp("br", trail->tag))
663           {
664              trail->tagPosType = TAGPOS_ALONE;
665              continue;
666           }
667         else if (!strcmp("item", trail->tag) || !strcmp("img", trail->tag))
668           {
669              trail->tagPosType = TAGPOS_ALONE;
670              continue;
671           }
672
673         if (trail->tag[0] != '/') // PUSH
674           {
675              stack = eina_list_append(stack, trail);
676 /*             eina_array_push(stack, trail);
677              cnp_debug("stack: %d, tag %s\n", eina_array_count_get(stack), trail->tag);*/
678              cnp_debug("stack: %d, tag %s\n", eina_list_count(stack), trail->tag);
679           }
680         else // POP
681           {
682              if (!eina_list_count(stack))
683                {
684                   cnp_debug("tag not matched %s\n", trail->tag);
685                   continue;
686                }
687
688              EINA_LIST_REVERSE_FOREACH(stack, r, popData)
689                {
690                   if (popData->tag && !strcmp(popData->tag, &trail->tag[1]))
691                     {
692                        popData->tagPosType = TAGPOS_START;
693                        trail->tagPosType = TAGPOS_END;
694                        popData->matchTag = trail;
695                        trail->matchTag = popData;
696                        stack = eina_list_remove_list(stack, r);
697                        break;
698                     }
699                }
700 /*             popData = eina_array_pop(stack);
701
702              popData->tagPosType = TAGPOS_START;
703              trail->tagPosType = TAGPOS_END;
704              popData->matchTag = trail;
705              trail->matchTag = popData;
706              cnp_debug("pop stack: %d, tag %s\n", eina_array_count_get(stack), trail->tag);
707              */
708           }
709      }
710
711 /*   if (eina_array_count_get(stack))
712      cnp_debug("stack state: %d, tag %s\n", eina_array_count_get(stack), trail->tag);*/
713
714    /* Make Dummy close tag */
715 /*   while ((popData = eina_array_pop(stack)))  */
716
717    EINA_LIST_REVERSE_FOREACH(stack, r, popData)
718      {
719         PTagNode newData;
720         int tagLength = strlen(popData->tag);
721         char *tagName = malloc(sizeof(char) * (tagLength + 2));
722
723         tagName[0] = '/';
724         tagName[1] = '\0';
725         strcat(tagName, popData->tag);
726
727         newData = _new_tag_node(tagName, NULL, NULL, NULL);
728         popData->tagPosType = TAGPOS_START;
729         newData->tagPosType = TAGPOS_END;
730         popData->matchTag = newData;
731         newData->matchTag = popData;
732         nodes = eina_list_append(nodes, newData);
733 /*        cnp_debug("stack: %d, tag %s\n", eina_array_count_get(stack), popData->tag);*/
734      }
735 /*   cnp_debug("stack_top: %d\n", eina_array_count_get(stack));
736    eina_array_free(stack);*/
737    eina_list_free(stack);
738 }
739
740 static char *
741 _get_tag_value(const char *tag_str, const char *tag_name)
742 {
743    if (!tag_name || !tag_str)
744      return NULL;
745
746    char *tag;
747    if ((tag = strstr(tag_str, tag_name)))
748      {
749         if (tag[strlen(tag_name)] == '_')
750           return NULL;
751         char *value = strchr(tag, '=');
752         if (value)
753           {
754              do
755                {
756                   value++;
757                } while (!isalnum(*value) && *value != '#');
758
759              int spCnt = 6;
760              char *spArray[spCnt];
761              spArray[0] = strchr(value, ' ');
762              spArray[1] = strchr(value, '>');
763              spArray[2] = strchr(value, '\"');
764              spArray[3] = strchr(value, '\'');
765              spArray[4] = strchr(value, '\t');
766              spArray[5] = strchr(value, '\n');
767              char *valueEnd = strchr(value, '\0');
768
769              int i;
770              for (i = 0; i < spCnt; i++)
771                {
772                   if (spArray[i] && spArray[i] < valueEnd)
773                     valueEnd = spArray[i];
774                }
775
776              int valueLength = valueEnd - value;
777              return strndup(value, valueLength);
778           }
779      }
780    return NULL;
781 }
782
783 static PFontTagData
784 _set_EFL_font_data(PFontTagData data, const char *tag_str)
785 {
786    char *value;
787
788    if (!data)
789      data = calloc(1, sizeof(FontTagData));
790    value = _get_tag_value(tag_str, "font_size");
791    freeAndAssign(data->size, value);
792    value = _get_tag_value(tag_str, "color");
793    freeAndAssign(data->color, value);
794    value = _get_tag_value(tag_str, "bgcolor");
795    freeAndAssign(data->bg_color, value);
796    value = _get_tag_value(tag_str, "font");
797    freeAndAssign(data->name, value);
798
799    return data;
800 }
801
802 static PItemTagData
803 _set_EFL_item_data(PItemTagData data, const char *tag_str)
804 {
805    char *value;
806
807    if (!data)
808      data = calloc(1, sizeof(ItemTagData));
809    value = _get_tag_value(tag_str, "href");
810    if (value)
811      {
812         char *path = strstr(value, "file://");
813         if (path)
814           {
815              char *modify = malloc(sizeof(char) * (strlen(value) + 1));
816              strncpy(modify, "file://", 7);
817              modify[7] = '\0';
818              path += 7;
819              while (path[1] && path[0] && path[1] == '/' && path[0] == '/')
820                {
821                   path++;
822                }
823              strcat(modify, path);
824              data->href = modify;
825              cnp_debug("image href ---%s---\n", data->href);
826           }
827         else
828           freeAndAssign(data->href, value);
829         free(value);
830      }
831
832    value = _get_tag_value(tag_str, "absize");
833    if (value)
834      {
835         char *xpos = strchr(value, 'x');
836         if (xpos)
837           {
838              int absizeLen = strlen(value);
839              freeAndAssign(data->width, strndup(value, xpos - value));
840              freeAndAssign(data->height, strndup(xpos + 1, absizeLen - (xpos - value) - 1));
841              cnp_debug("image width: -%s-, height: -%s-\n", data->width, data->height);
842           }
843         free(value);
844      }
845    return data;
846 }
847
848 static void
849 _set_EFL_tag_data(Eina_List* nodes)
850 {
851    PTagNode trail;
852    Eina_List *l;
853
854    EINA_LIST_FOREACH(nodes, l, trail)
855      {
856         if (!trail->tag)
857           continue;
858         if (!strcmp("font", trail->tag))
859              trail->tagData = _set_EFL_font_data(trail->tagData, trail->tag_str);
860         else if (!strcmp("item", trail->tag))
861              trail->tagData = _set_EFL_item_data(trail->tagData, trail->tag_str);
862      }
863 }
864
865 static PFontTagData
866 _set_HTML_font_data(PFontTagData data, const char *tag_str)
867 {
868    char *value;
869
870    if (!data)
871      data = calloc(1, sizeof(FontTagData));
872    value = _get_tag_value(tag_str, "size");
873    freeAndAssign(data->size, value);
874    value = _get_tag_value(tag_str, "color");
875    freeAndAssign(data->color, value);
876    value = _get_tag_value(tag_str, "bgcolor");
877    freeAndAssign(data->bg_color, value);
878    value = _get_tag_value(tag_str, "face");
879    freeAndAssign(data->name, value);
880
881    return data;
882 }
883
884 static PItemTagData
885 _set_HTML_img_data(PItemTagData data, const char *tag_str)
886 {
887    char *value;
888
889    if (!data)
890      data = calloc(1, sizeof(ItemTagData));
891    value = _get_tag_value(tag_str, "src");
892    if (value)
893      {
894         char *path = strstr(value, "file://");
895         if (path)
896           {
897              char *modify = malloc(sizeof(char) * (strlen(value) + 1));
898              strncpy(modify, "file://", 7);
899              modify[7] = '\0';
900              path += 7;
901              while (path[1] && path[0] && path[1] == '/' && path[0] == '/')
902                {
903                   path++;
904                }
905              strcat(modify, path);
906              data->href = modify;
907              cnp_debug("image src ---%s---\n", data->href);
908           }
909         else
910           freeAndAssign(data->href, value);
911         free(value);
912      }
913
914    value = _get_tag_value(tag_str, "width");
915    freeAndAssign(data->width, value);
916    value = _get_tag_value(tag_str, "height");
917    freeAndAssign(data->height, value);
918    return data;
919 }
920
921 static void
922 _set_HTML_tag_data(Eina_List* nodes)
923 {
924    PTagNode trail;
925    Eina_List *l;
926
927    EINA_LIST_FOREACH(nodes, l, trail)
928      {
929         if (!trail->tag)
930           continue;
931         if (!strcmp("font", trail->tag))
932              trail->tagData = _set_HTML_font_data(trail->tagData, trail->tag_str);
933         else if (!strcmp("img", trail->tag))
934              trail->tagData = _set_HTML_img_data(trail->tagData, trail->tag_str);
935      }
936 }
937
938 #ifdef DEBUGON
939 static void
940 _dumpNode(Eina_List* nodes)
941 {
942    PTagNode trail;
943    Eina_List *l;
944
945    EINA_LIST_FOREACH(nodes, l, trail)
946      {
947         cnp_debug("tag: %s, tag_str: %s, str: %s, tagPosType: %d\n",
948                trail->tag, trail->tag_str, trail->str, trail->tagPosType);
949         cnp_debug("matchTag: %x ", (unsigned int)trail->matchTag);
950         if (trail->matchTag)
951           cnp_debug("matchTag->tag_str: %s", trail->matchTag->tag_str);
952         if (trail->tagData)
953           {
954              if (!strcmp(trail->tag, "font"))
955                {
956                   PFontTagData data = trail->tagData;
957                   cnp_debug(" tagData->name: %s, tagData->color: %s, tagData->size: %s, tagData->bg_color: %s",
958                          data->name, data->color, data->size, data->bg_color);
959                }
960              else if (!strcmp(trail->tag, "item") || !strcmp(trail->tag, "img"))
961                {
962                   PItemTagData data = trail->tagData;
963                   cnp_debug(" tagData->href: %s, tagData->width: %s, tagData->height: %s",
964                          data->href, data->width, data->height);
965                }
966              else
967                cnp_debug("\nERROR!!!! not need tagData");
968           }
969         cnp_debug("\n");
970      }
971 }
972 #endif
973
974 static char *
975 _convert_to_html(Eina_List* nodes)
976 {
977    PTagNode trail;
978    Eina_List *l;
979
980    Eina_Strbuf *html = eina_strbuf_new();
981
982    int tableCnt = sizeof(_EFLtoHTMLConvertTable) / sizeof(TagTable);
983
984    EINA_LIST_FOREACH(nodes, l, trail)
985      {
986         if (trail->tag)
987           {
988              char *tagName = trail->tagPosType == TAGPOS_END ?
989                 trail->matchTag->tag : trail->tag;
990              int j;
991              for(j = 0; j < tableCnt; j++)
992                {
993                   if (!strcmp(_EFLtoHTMLConvertTable[j].src, tagName))
994                     {
995                        switch(trail->tagPosType)
996                          {
997                           case TAGPOS_END:
998                              eina_strbuf_append(html, "</");
999                              break;
1000                           default:
1001                              eina_strbuf_append(html, "<");
1002                              break;
1003                          }
1004
1005                        eina_strbuf_append(html, _EFLtoHTMLConvertTable[j].dst);
1006                        if (trail->tagPosType != TAGPOS_END)
1007                          {
1008                             if (!strcmp(_EFLtoHTMLConvertTable[j].src, "font"))
1009                               {
1010                                  PFontTagData data = trail->tagData;
1011                                  if (data->name)
1012                                    {
1013                                    }
1014                                  if (data->color)
1015                                    eina_strbuf_append_printf(html, " color=\"%s\"", data->color);
1016                                  if (data->size)
1017                                    eina_strbuf_append_printf(html, " size=\"%s\"", data->size);
1018                                  if (data->bg_color)
1019                                    {
1020                                    }
1021                               }
1022                             else if (!strcmp(_EFLtoHTMLConvertTable[j].src, "item"))
1023                               {
1024                                  PItemTagData data = trail->tagData;
1025                                  if (data->href)
1026                                    eina_strbuf_append_printf(html, " src=\"%s\"", data->href);
1027                                  if (data->width)
1028                                    eina_strbuf_append_printf(html, " width=\"%s\"", data->width);
1029                                  if (data->height)
1030                                    eina_strbuf_append_printf(html, " height=\"%s\"", data->height);
1031                               }
1032                          }
1033                        switch(trail->tagPosType)
1034                          {
1035                           case TAGPOS_ALONE:
1036                              eina_strbuf_append(html, " />");
1037                              break;
1038                           default:
1039                              eina_strbuf_append(html, ">");
1040                              break;
1041                          }
1042                        break;
1043                     }
1044                }
1045           }
1046         if (trail->str)
1047           eina_strbuf_append(html, trail->str);
1048      }
1049
1050    char *ret = eina_strbuf_string_steal(html);
1051    eina_strbuf_free(html);
1052    return ret;
1053 }
1054
1055 #define IMAGE_DEFAULT_WIDTH "240"
1056 #define IMAGE_DEFAULT_HEIGHT "180"
1057
1058
1059 static char *
1060 _convert_to_edje(Eina_List* nodes)
1061 {
1062    PTagNode trail;
1063    Eina_List *l;
1064
1065    Eina_Strbuf *html = eina_strbuf_new();
1066
1067    int tableCnt = sizeof(_HTMLtoEFLConvertTable) / sizeof(TagTable);
1068
1069    EINA_LIST_FOREACH(nodes, l, trail)
1070      {
1071         if (trail->tag)
1072           {
1073              char *tagName = trail->tagPosType == TAGPOS_END ?
1074                 trail->matchTag->tag : trail->tag;
1075              int j;
1076              for(j = 0; j < tableCnt; j++)
1077                {
1078                   if (!strcmp(_HTMLtoEFLConvertTable[j].src, tagName))
1079                     {
1080                        if (_HTMLtoEFLConvertTable[j].dst[0] != '\0')
1081                          {
1082                             switch(trail->tagPosType)
1083                               {
1084                                case TAGPOS_END:
1085                                   eina_strbuf_append(html, "</");
1086                                   break;
1087                                default:
1088                                   eina_strbuf_append(html, "<");
1089                                   break;
1090                               }
1091
1092                             eina_strbuf_append(html, _HTMLtoEFLConvertTable[j].dst);
1093                          }
1094                        if (trail->tagPosType != TAGPOS_END)
1095                          {
1096                             if (!strcmp(_HTMLtoEFLConvertTable[j].src, "font"))
1097                               {
1098                                  PFontTagData data = trail->tagData;
1099                                  if (data->name)
1100                                    {
1101                                    }
1102                                  if (data->color)
1103                                    eina_strbuf_append_printf(html, "<color=%s>", data->color);
1104                                  if (data->size)
1105                                    eina_strbuf_append_printf(html, "<font_size=%s>", data->size);
1106                                  if (data->bg_color)
1107                                    {
1108                                    }
1109                                  break;
1110                               }
1111                             else if (!strcmp(_HTMLtoEFLConvertTable[j].src, "img"))
1112                               {
1113                                  PItemTagData data = trail->tagData;
1114                                  char *width = IMAGE_DEFAULT_WIDTH, *height = IMAGE_DEFAULT_HEIGHT;
1115                                  if (data->href)
1116                                    eina_strbuf_append_printf(html, " href=%s", data->href);
1117                                  if (data->width)
1118                                    width = data->width;
1119                                  if (data->height)
1120                                    height = data->height;
1121                                  eina_strbuf_append_printf(html, " absize=%sx%s></item>", width, height);
1122                                  break;
1123                               }
1124                          }
1125                        else
1126                          {
1127                             if (_HTMLtoEFLConvertTable[j].dst[0] == '\0')
1128                               {
1129                                  if (!strcmp(_HTMLtoEFLConvertTable[j].src, "font"))
1130                                    {
1131                                       if (trail->matchTag->tagData)
1132                                         {
1133                                            PFontTagData data = trail->matchTag->tagData;
1134                                            if (data->name)
1135                                              {
1136                                              }
1137                                            if (data->color)
1138                                              eina_strbuf_append_printf(html, "</color>");
1139                                            if (data->size)
1140                                              eina_strbuf_append_printf(html, "</font>");
1141                                            if (data->bg_color)
1142                                              {
1143                                              }
1144                                            break;
1145                                         }
1146                                    }
1147                               }
1148                          }
1149                        switch(trail->tagPosType)
1150                          {
1151                           case TAGPOS_ALONE:
1152                              eina_strbuf_append(html, " />");
1153                              break;
1154                           default:
1155                              eina_strbuf_append(html, ">");
1156                              break;
1157                          }
1158                        break;
1159                     }
1160                }/* for(j = 0; j < tableCnt; j++) end */
1161           }
1162         if (trail->str)
1163           eina_strbuf_append(html, trail->str);
1164      }
1165
1166    char *ret = eina_strbuf_string_steal(html);
1167    eina_strbuf_free(html);
1168    return ret;
1169
1170 }
1171 Eina_Bool
1172 elm_selection_set(Elm_Sel_Type selection, Evas_Object *widget, Elm_Sel_Format format, const char *selbuf)
1173 {
1174 #ifdef HAVE_ELEMENTARY_X
1175    Cnp_Selection *sel;
1176
1177    if ((unsigned int)selection >= (unsigned int)ELM_SEL_MAX) return EINA_FALSE;
1178    if (!_elm_cnp_init_count) _elm_cnp_init();
1179    if ((!selbuf) && (format != ELM_SEL_FORMAT_IMAGE))
1180      return elm_selection_clear(selection, widget);
1181
1182    sel = selections + selection;
1183
1184    sel->active = 1;
1185    sel->widget = widget;
1186
1187    sel->set(elm_win_xwindow_get(widget),&selection,sizeof(Elm_Sel_Type));
1188    sel->format = format;
1189    sel->selbuf = selbuf ? strdup(selbuf) : NULL;
1190
1191    return EINA_TRUE;
1192 #else
1193    return EINA_FALSE;
1194 #endif
1195 }
1196
1197 Eina_Bool
1198 elm_selection_clear(Elm_Sel_Type selection, Evas_Object *widget)
1199 {
1200 #ifdef HAVE_ELEMENTARY_X
1201    Cnp_Selection *sel;
1202
1203    if ((unsigned int)selection >= (unsigned int)ELM_SEL_MAX) return EINA_FALSE;
1204    if (!_elm_cnp_init_count) _elm_cnp_init();
1205
1206    sel = selections + selection;
1207
1208    /* No longer this selection: Consider it gone! */
1209    if ((!sel->active) || (sel->widget != widget)) return EINA_TRUE;
1210
1211    sel->active = 0;
1212    sel->widget = NULL;
1213    sel->clear();
1214
1215    return EINA_TRUE;
1216 #else
1217    return EINA_FALSE;
1218 #endif
1219 }
1220
1221 Eina_Bool
1222 elm_selection_get(Elm_Sel_Type selection, Elm_Sel_Format format,
1223                   Evas_Object *widget, Elm_Drop_Cb datacb, void *udata)
1224 {
1225 #ifdef HAVE_ELEMENTARY_X
1226    Evas_Object *top;
1227    Cnp_Selection *sel;
1228
1229    if ((unsigned int)selection >= (unsigned int)ELM_SEL_MAX) return EINA_FALSE;
1230    if (!_elm_cnp_init_count) _elm_cnp_init();
1231
1232    sel = selections + selection;
1233    top = elm_widget_top_get(widget);
1234    if (!top) return EINA_FALSE;
1235
1236    sel->requestformat = format;
1237    sel->requestwidget = widget;
1238    sel->request(elm_win_xwindow_get(top), ECORE_X_SELECTION_TARGET_TARGETS);
1239    sel->datacb = datacb;
1240    sel->udata = udata;
1241
1242    return EINA_TRUE;
1243 #else
1244    return EINA_FALSE;
1245 #endif
1246 }
1247
1248 #ifdef HAVE_ELEMENTARY_X
1249
1250 static Eina_Bool
1251 _elm_cnp_init(void)
1252 {
1253    int i;
1254
1255    if (_elm_cnp_init_count++) return EINA_TRUE;
1256    for (i = 0; i < CNP_N_ATOMS; i++)
1257      {
1258         atoms[i].atom = ecore_x_atom_get(atoms[i].name);
1259         ecore_x_selection_converter_atom_add(atoms[i].atom,
1260                                              atoms[i].converter);
1261      }
1262    clipboard_atom = ecore_x_atom_get("CLIPBOARD");
1263
1264    ecore_event_handler_add(ECORE_X_EVENT_SELECTION_CLEAR, selection_clear, NULL);
1265    ecore_event_handler_add(ECORE_X_EVENT_SELECTION_NOTIFY, selection_notify, NULL);
1266
1267    text_uri = eina_stringshare_add("text/uri-list");
1268    return EINA_TRUE;
1269 }
1270
1271 static Eina_Bool
1272 selection_clear(void *udata __UNUSED__, int type __UNUSED__, void *event)
1273 {
1274    Ecore_X_Event_Selection_Clear *ev = event;
1275    Cnp_Selection *sel;
1276    int i;
1277
1278    for (i = 0; i < ELM_SEL_MAX; i++)
1279      {
1280         if (selections[i].ecore_sel == ev->selection) break;
1281      }
1282    cnp_debug("selection %d clear\n", i);
1283    /* Not me... Don't care */
1284    if (i == ELM_SEL_MAX) return ECORE_CALLBACK_PASS_ON;
1285
1286    sel = selections + i;
1287    sel->active = 0;
1288    sel->widget = NULL;
1289    sel->selbuf = NULL;
1290
1291    return ECORE_CALLBACK_PASS_ON;
1292 }
1293
1294
1295 /*
1296  * Response to a selection notify:
1297  *      - So we have asked for the selection list.
1298  *      - If it's the targets list, parse it, and fire of what we want,
1299  *      else it's the data we want.
1300  */
1301 static Eina_Bool
1302 selection_notify(void *udata __UNUSED__, int type __UNUSED__, void *event)
1303 {
1304    Ecore_X_Event_Selection_Notify *ev = event;
1305    Cnp_Selection *sel;
1306    int i;
1307
1308    cnp_debug("selection notify callback: %d\n",ev->selection);
1309    switch (ev->selection)
1310      {
1311       case ECORE_X_SELECTION_CLIPBOARD:
1312          sel = selections + ELM_SEL_CLIPBOARD;
1313          break;
1314       case ECORE_X_SELECTION_PRIMARY:
1315          sel = selections + ELM_SEL_PRIMARY;
1316          break;
1317       case ECORE_X_SELECTION_SECONDARY:
1318          sel = selections + ELM_SEL_SECONDARY;
1319          break;
1320       case ECORE_X_SELECTION_XDND:
1321          sel = selections + ELM_SEL_XDND;
1322          break;
1323       default:
1324          return ECORE_CALLBACK_PASS_ON;
1325      }
1326    cnp_debug("Target is %s\n", ev->target);
1327
1328    for (i = 0; i < CNP_N_ATOMS; i++)
1329      {
1330         if (!strcmp(ev->target, atoms[i].name))
1331           {
1332              if (atoms[i].notify)
1333                {
1334                   cnp_debug("Found something: %s\n", atoms[i].name);
1335                   atoms[i].notify(sel, ev);
1336                }
1337              else
1338                {
1339                   cnp_debug("Ignored: No handler!\n");
1340                }
1341           }
1342      }
1343
1344    return ECORE_CALLBACK_PASS_ON;
1345 }
1346
1347
1348
1349 static Eina_Bool
1350 targets_converter(char *target __UNUSED__, void *data, int size __UNUSED__, void **data_ret, int *size_ret, Ecore_X_Atom *ttype, int *typesize)
1351 {
1352    int i,count;
1353    Ecore_X_Atom *aret;
1354    Cnp_Selection *sel;
1355
1356    if (!data_ret) return EINA_FALSE;
1357
1358    sel = selections + *((int *)data);
1359
1360    for (i = 0, count = 0; i < CNP_N_ATOMS ; i++)
1361      {
1362         if (sel->format & atoms[i].formats) count++;
1363      }
1364
1365    aret = malloc(sizeof(Ecore_X_Atom) * count);
1366    for (i = 0, count = 0; i < CNP_N_ATOMS; i++)
1367      {
1368         if (sel->format & atoms[i].formats) aret[count ++] = atoms[i].atom;
1369      }
1370
1371    *data_ret = aret;
1372    if (typesize) *typesize = 32 /* urk */;
1373    if (ttype) *ttype = ECORE_X_ATOM_ATOM;
1374    if (size_ret) *size_ret = count;
1375
1376    return EINA_TRUE;
1377 }
1378
1379 static Eina_Bool
1380 image_converter(char *target __UNUSED__, void *data __UNUSED__, int size __UNUSED__, void **data_ret __UNUSED__, int *size_ret __UNUSED__, Ecore_X_Atom *ttype __UNUSED__, int *typesize __UNUSED__)
1381 {
1382    cnp_debug("Image converter called\n");
1383    return EINA_TRUE;
1384 }
1385
1386 static Eina_Bool
1387 vcard_send(char *target __UNUSED__, void *data __UNUSED__, int size __UNUSED__, void **data_ret, int *size_ret, Ecore_X_Atom *ttype __UNUSED__, int *typesize __UNUSED__)
1388 {
1389    Cnp_Selection *sel;
1390
1391    cnp_debug("Vcard send called\n");
1392
1393    sel = selections + *((int *)data);
1394
1395    if (data_ret) *data_ret = strdup(sel->selbuf);
1396    if (size_ret) *size_ret = strlen(sel->selbuf);
1397
1398    return EINA_TRUE;
1399 }
1400 /*
1401  * Callback to handle a targets response on a selection request:
1402  * So pick the format we'd like; and then request it.
1403  */
1404 static int
1405 notify_handler_targets(Cnp_Selection *sel, Ecore_X_Event_Selection_Notify *notify)
1406 {
1407    Ecore_X_Selection_Data_Targets *targets;
1408    Ecore_X_Atom *atomlist;
1409    int i, j;
1410
1411    targets = notify->data;
1412    atomlist = (Ecore_X_Atom *)(targets->data.data);
1413
1414    for (j = 1; j < CNP_N_ATOMS; j++)
1415      {
1416         cnp_debug("\t%s %d\n", atoms[j].name, atoms[j].atom);
1417         if (!(atoms[j].formats & sel->requestformat)) continue;
1418         for (i = 0; i < targets->data.length; i++)
1419           {
1420              if ((atoms[j].atom == atomlist[i]) && (atoms[j].notify))
1421                {
1422                   cnp_debug("Atom %s matches\n",atoms[j].name);
1423                   goto done;
1424                }
1425           }
1426      }
1427
1428    cnp_debug("Couldn't find anything that matches\n");
1429    return ECORE_CALLBACK_PASS_ON;
1430
1431 done:
1432    cnp_debug("Sending request for %s\n",atoms[j].name);
1433    sel->request(elm_win_xwindow_get(sel->requestwidget), atoms[j].name);
1434
1435    return ECORE_CALLBACK_PASS_ON;
1436 }
1437
1438 static int
1439 response_handler_targets(Cnp_Selection *sel, Ecore_X_Event_Selection_Notify *notify)
1440 {
1441    Ecore_X_Selection_Data_Targets *targets;
1442    Ecore_X_Atom *atomlist;
1443    Evas_Object *top;
1444    int i,j;
1445
1446    targets = notify->data;
1447    atomlist = (Ecore_X_Atom *)(targets->data.data);
1448
1449    /* Start from 1: Skip targets */
1450    for (j = 1 ; j < CNP_N_ATOMS ; j ++)
1451      {
1452         if (!(atoms[j].formats & sel->requestformat)) continue;
1453         for (i = 0 ; i < targets->data.length ; i ++)
1454           {
1455              if ((atoms[j].atom == atomlist[i]) && (atoms[j].response))
1456                {
1457                   /* Found a match: Use it */
1458                   goto found;
1459                }
1460           }
1461      }
1462 found:
1463    if (j == CNP_N_ATOMS)
1464      {
1465         cnp_debug("No matching type found\n");
1466         return 0;
1467      }
1468
1469    top = elm_widget_top_get(sel->requestwidget);
1470    if (!top) return 0;
1471
1472    sel->request(elm_win_xwindow_get(top), atoms[j].name);
1473    return 0;
1474 }
1475
1476
1477 static int
1478 notify_handler_text(Cnp_Selection *sel, Ecore_X_Event_Selection_Notify *notify)
1479 {
1480    Ecore_X_Selection_Data *data;
1481    char *str;
1482
1483    data = notify->data;
1484
1485    if (sel->datacb)
1486      {
1487         Elm_Selection_Data ddata;
1488         
1489         str = mark_up((char *)data->data, data->length, NULL);
1490         ddata.x = ddata.y = 0;
1491         ddata.format = ELM_SEL_FORMAT_TEXT;
1492         ddata.data = str;
1493         ddata.len = data->length;
1494         sel->datacb(sel->udata, sel->widget, &ddata);
1495         free(str);
1496         return 0;
1497      }
1498    
1499    cnp_debug("Notify handler text %d %d %p\n", data->format,data->length, data->data);
1500    str = mark_up((char *)data->data, data->length, NULL);
1501    cnp_debug("String is %s (from %s)\n", str, data->data);
1502    elm_entry_entry_insert(sel->requestwidget, str);
1503    free(str);
1504    return 0;
1505 }
1506
1507
1508 /**
1509  * So someone is pasting an image into my entry or widget...
1510  */
1511 static int
1512 notify_handler_uri(Cnp_Selection *sel, Ecore_X_Event_Selection_Notify *notify)
1513 {
1514    Ecore_X_Selection_Data *data;
1515    Ecore_X_Selection_Data_Files *files;
1516    Paste_Image *pi;
1517    char *p;
1518
1519    data = notify->data;
1520    cnp_debug("data->format is %d %p %p\n", data->format, notify, data);
1521    if (data->content == ECORE_X_SELECTION_CONTENT_FILES)
1522      {
1523         cnp_debug("got a files list\n");
1524         files = notify->data;
1525         if (files->num_files > 1)
1526           {
1527              /* Don't handle many items */
1528              cnp_debug("more then one file: Bailing\n");
1529              return 0;
1530           }
1531         p = files->files[0];
1532      }
1533    else
1534      {
1535         p = (char *)data->data;
1536      }
1537
1538    if (!p)
1539      {
1540         cnp_debug("Couldn't find a file\n");
1541         return 0;
1542      }
1543    cnp_debug("Got %s\n",p);
1544    if (sel->datacb)
1545      {
1546         Elm_Selection_Data ddata;
1547         
1548         ddata.x = ddata.y = 0;
1549         ddata.format = ELM_SEL_FORMAT_MARKUP;
1550         ddata.data = p;
1551         ddata.len = data->length;
1552         sel->datacb(sel->udata, sel->widget, &ddata);
1553         return 0;
1554      }
1555    if (strncmp(p, "file://", 7))
1556      {
1557         /* Try and continue if it looks sane */
1558         if (*p != '/') return 0;
1559      }
1560    else
1561      {
1562         p += strlen("file://");
1563      }
1564
1565    if (savedtypes.pi) pasteimage_free(savedtypes.pi);
1566    pi = pasteimage_alloc(p, strlen(p));
1567    if (savedtypes.textreq)
1568      {
1569         savedtypes.textreq = 0;
1570         savedtypes.pi = pi;
1571      }
1572    else
1573      {
1574         pasteimage_append(pi, sel->requestwidget);
1575         savedtypes.pi = NULL;
1576      }
1577    return 0;
1578 }
1579
1580 /**
1581  * Just receieved an vcard, either through cut and paste, or dnd.
1582  */
1583 static int
1584 vcard_receive(Cnp_Selection *sel, Ecore_X_Event_Selection_Notify *notify)
1585 {
1586    Dropable *dropable;
1587    Eina_List *l;
1588    Ecore_X_Selection_Data *data;
1589
1590    data = notify->data;
1591    cnp_debug("vcard receive\n");
1592
1593    if (sel == (selections + ELM_SEL_XDND))
1594      {
1595         Elm_Selection_Data ddata;
1596
1597         cnp_debug("drag & drop\n");
1598         /* FIXME: this needs to be generic: Used for all receives */
1599         EINA_LIST_FOREACH(drops, l, dropable)
1600           {
1601              if (dropable->obj == sel->requestwidget) break;
1602           }
1603         if (!dropable)
1604           {
1605              cnp_debug("Unable to find drop object");
1606              ecore_x_dnd_send_finished();
1607              return 0;
1608           }
1609         dropable = eina_list_data_get(l);
1610         ddata.x = savedtypes.x;
1611         ddata.y = savedtypes.y;
1612         ddata.format = ELM_SEL_FORMAT_VCARD;
1613         ddata.data = data->data;
1614         ddata.len = data->length;
1615         dropable->dropcb(dropable->cbdata, dropable->obj, &ddata);
1616         ecore_x_dnd_send_finished();
1617      }
1618    else if (sel->datacb)
1619      {
1620         Elm_Selection_Data ddata;
1621         ddata.x = ddata.y = 0;
1622         ddata.format = ELM_SEL_FORMAT_IMAGE;
1623         ddata.data = data->data;
1624         ddata.len = data->length;
1625         sel->datacb(sel->udata, sel->widget, &ddata);
1626      }
1627    else
1628      {
1629         cnp_debug("Paste request\n");
1630      }
1631
1632    return 0;
1633
1634 }
1635
1636
1637 static int
1638 notify_handler_image(Cnp_Selection *sel, Ecore_X_Event_Selection_Notify *notify)
1639 {
1640    Ecore_X_Selection_Data *data;
1641    Tmp_Info *tmp;
1642    Paste_Image *pi;
1643
1644    cnp_debug("got a png (or a jpeg)!\n");
1645    data = notify->data;
1646
1647    cnp_debug("Size if %d\n", data->length);
1648
1649    if (sel->datacb)
1650      {
1651         Elm_Selection_Data ddata;
1652
1653         ddata.x = ddata.y = 0;
1654         ddata.format = ELM_SEL_FORMAT_IMAGE;
1655         ddata.data = data->data;
1656         ddata.len = data->length;
1657         sel->datacb(sel->udata, sel->widget, &ddata);
1658         return 0;
1659      }
1660
1661    /* generate tmp name */
1662    tmp = elm_cnp_tempfile_create(data->length);
1663    memcpy(tmp->map, data->data, data->length);
1664    munmap(tmp->map,data->length);
1665
1666    /* FIXME: Add to paste image data to clean up */
1667    pi = pasteimage_alloc(tmp->filename, strlen(tmp->filename));
1668    pasteimage_append(pi, sel->requestwidget);
1669
1670    tmpinfo_free(tmp);
1671    return 0;
1672 }
1673
1674
1675 /**
1676  *    Warning: Generic text/html can';t handle it sanely.
1677  *    Firefox sends ucs2 (i think).
1678  *       chrome sends utf8... blerg
1679  */
1680 static int
1681 notify_handler_html(Cnp_Selection *sel, Ecore_X_Event_Selection_Notify *notify)
1682 {
1683    Ecore_X_Selection_Data *data;
1684
1685    cnp_debug("Got some HTML: Checking encoding is useful\n");
1686    data = notify->data;
1687
1688    if (sel->datacb)
1689      {
1690         Elm_Selection_Data ddata;
1691         ddata.x = ddata.y = 0;
1692         ddata.format = ELM_SEL_FORMAT_HTML;
1693         ddata.data = data->data;
1694         ddata.len = data->length;
1695         sel->datacb(sel->udata, sel->widget, &ddata);
1696         return 0;
1697      }
1698
1699    char *stripstr = NULL;
1700    stripstr = malloc(sizeof(char) * (data->length + 1));
1701    strncpy(stripstr, (char *)data->data, data->length);
1702    stripstr[data->length] = '\0';
1703    cnp_debug("String is %s (%d bytes)\n", stripstr, data->length);
1704    elm_entry_entry_insert(sel->requestwidget, stripstr);
1705    free(stripstr);
1706    return 0;
1707 }
1708
1709
1710 static Eina_Bool
1711 text_converter(char *target __UNUSED__, void *data, int size __UNUSED__, void **data_ret, int *size_ret, Ecore_X_Atom *ttype __UNUSED__, int *typesize __UNUSED__)
1712 {
1713    Cnp_Selection *sel;
1714
1715    cnp_debug("text converter\n");
1716    sel = selections + *((int *)data);
1717    if (!sel->active) return EINA_TRUE;
1718
1719    if ((sel->format & ELM_SEL_FORMAT_MARKUP) ||
1720        (sel->format & ELM_SEL_FORMAT_HTML))
1721      {
1722         *data_ret = remove_tags(sel->selbuf, size_ret);
1723      }
1724    else if (sel->format & ELM_SEL_FORMAT_TEXT)
1725      {
1726         *data_ret = strdup(sel->selbuf);
1727         *size_ret = strlen(sel->selbuf);
1728      }
1729    else if (sel->format & ELM_SEL_FORMAT_IMAGE)
1730      {
1731         cnp_debug("Image %s\n", evas_object_type_get(sel->widget));
1732         cnp_debug("Elm type: %s\n", elm_object_widget_type_get(sel->widget));
1733         evas_object_image_file_get(elm_photocam_internal_image_get(sel->widget), (const char **)data_ret, NULL);
1734         if (!*data_ret) *data_ret = strdup("No file");
1735         else *data_ret = strdup(*data_ret);
1736         *size_ret = strlen(*data_ret);
1737      }
1738    return EINA_TRUE;
1739 }
1740
1741 static Eina_Bool
1742 edje_converter(char *target __UNUSED__, void *data, int size __UNUSED__, void **data_ret, int *size_ret, Ecore_X_Atom *ttype __UNUSED__, int *typesize __UNUSED__)
1743 {
1744    Cnp_Selection *sel;
1745
1746    sel = selections + *((int *)data);
1747 /*   if (data_ret) *data_ret = strdup(sel->selbuf);
1748    if (size_ret) *size_ret = strlen(sel->selbuf);*/
1749    char *edje = NULL;
1750
1751    if (data_ret && (sel->format & ELM_SEL_FORMAT_HTML))
1752      {
1753         Eina_List *nodeList = NULL;
1754         Eina_List *trail;
1755         PTagNode nodeData;
1756
1757         nodeData = _get_start_node(sel->selbuf);
1758
1759         while (nodeData)
1760           {
1761              nodeList = eina_list_append(nodeList, nodeData);
1762              nodeData = _get_next_node(nodeData);
1763           }
1764
1765         _link_match_tags(nodeList);
1766
1767         _set_HTML_tag_data(nodeList);
1768
1769 #ifdef DEBUGON
1770         _dumpNode(nodeList);
1771 #endif
1772         edje = _convert_to_edje(nodeList);
1773
1774         cnp_debug("convert edje: %s\n", edje);
1775
1776         EINA_LIST_FOREACH(nodeList, trail, nodeData)
1777            _delete_node(nodeData);
1778         eina_list_free(nodeList);
1779
1780      }
1781    if (data_ret)
1782      {
1783         if (edje)
1784           *data_ret = edje;
1785         else
1786           *data_ret = strdup(sel->selbuf);
1787      }
1788    if (size_ret)
1789      {
1790         if (edje)
1791           *size_ret = strlen(edje);
1792         else
1793           *size_ret = strlen(sel->selbuf);
1794      }
1795
1796    return EINA_TRUE;
1797 }
1798
1799 static Eina_Bool
1800 html_converter(char *target __UNUSED__, void *data, int size __UNUSED__, void **data_ret, int *size_ret, Ecore_X_Atom *ttype __UNUSED__, int *typesize __UNUSED__)
1801 {
1802    Cnp_Selection *sel;
1803
1804    sel = selections + *(int *)data;
1805
1806    char *html = NULL;
1807    if (data_ret && (sel->format & ELM_SEL_FORMAT_MARKUP))
1808      {
1809         Eina_List *nodeList = NULL;
1810         Eina_List *trail;
1811         PTagNode nodeData;
1812
1813         nodeData = _get_start_node(sel->selbuf);
1814
1815         while (nodeData)
1816           {
1817              nodeList = eina_list_append(nodeList, nodeData);
1818              nodeData = _get_next_node(nodeData);
1819           }
1820
1821         _link_match_tags(nodeList);
1822
1823         _set_EFL_tag_data(nodeList);
1824
1825 #ifdef DEBUGON
1826         _dumpNode(nodeList);
1827 #endif
1828         html = _convert_to_html(nodeList);
1829
1830         cnp_debug("convert html: %s\n", html);
1831
1832         EINA_LIST_FOREACH(nodeList, trail, nodeData)
1833            _delete_node(nodeData);
1834         eina_list_free(nodeList);
1835      }
1836    if (data_ret)
1837      {
1838         if (html)
1839           *data_ret = html;
1840         else
1841           *data_ret = strdup(sel->selbuf);
1842      }
1843
1844    if (size_ret)
1845      {
1846         if (html)
1847           *size_ret = strlen(html);
1848         else
1849           *size_ret = strlen(sel->selbuf);
1850      }
1851
1852    return EINA_TRUE;
1853 }
1854
1855 static Eina_Bool
1856 uri_converter(char *target __UNUSED__, void *data, int size __UNUSED__, void **data_ret, int *size_ret, Ecore_X_Atom *ttype __UNUSED__, int *typesize __UNUSED__)
1857 {
1858    Cnp_Selection *sel;
1859    sel = selections + *((int *)data);
1860    cnp_debug("Uri converter\n");
1861    if (data_ret) *data_ret = strdup(sel->selbuf);
1862    if (size_ret) *size_ret = strlen(sel->selbuf);
1863    return EINA_TRUE;
1864 }
1865
1866 /*
1867  * Image paste provide
1868  */
1869
1870 /* FIXME: Should add provider for each pasted item: Use data to store it
1871  * much easier */
1872 static Evas_Object *
1873 image_provider(void *images __UNUSED__, Evas_Object *entry, const char *item)
1874 {
1875    Paste_Image *pi;
1876    Eina_List *l;
1877
1878    cnp_debug("image provider for %s called\n", item);
1879    EINA_LIST_FOREACH(pastedimages, l, pi)
1880      {
1881         cnp_debug("is it %s?\n",pi->tag);
1882         if (!strcmp(pi->tag, item))
1883           {
1884              /* Found it */
1885              Evas_Object *o;
1886              o = evas_object_image_filled_add(evas_object_evas_get(entry));
1887              /* FIXME: Handle eets */
1888              cnp_debug("file is %s (object is %p)\n", pi->file, o);
1889              evas_object_image_file_set(o, pi->file, NULL);
1890              evas_object_show(o);
1891              return o;
1892           }
1893      }
1894    return NULL;
1895 }
1896
1897
1898 static Paste_Image *
1899 pasteimage_alloc(const char *file, int pathlen)
1900 {
1901    Paste_Image *pi;
1902    int len;
1903    char *buf, *filebuf;
1904    int prefixlen = strlen("file://");
1905
1906    pi = calloc(1, sizeof(Paste_Image));
1907    if (!pi) return NULL;
1908
1909    len = snprintf(NULL, 0, "pasteimage-%p", pi);
1910    len++;
1911    buf = malloc(len);
1912    if (!buf)
1913      {
1914         free(pi);
1915         return NULL;
1916      }
1917    snprintf(buf, len, "pasteimage-%p", pi);
1918    pi->tag = buf;
1919
1920    if (file)
1921      {
1922         if (strstr(file,"file://")) file += prefixlen;
1923         filebuf = alloca(pathlen + 1);
1924         strncpy(filebuf, file, pathlen);
1925         filebuf[pathlen] = 0;
1926         pi->file = strdup(filebuf);
1927      }
1928
1929    return pi;
1930 }
1931
1932 static void
1933 pasteimage_free(Paste_Image *pi)
1934 {
1935    if (!pi) return;
1936    if (pi->file) free((void*)pi->file);
1937    if (pi->tag) free((void*)pi->tag);
1938    free(pi);
1939 }
1940
1941 static Eina_Bool
1942 pasteimage_provider_set(Evas_Object *entry)
1943 {
1944    void *v;
1945    const char *type;
1946
1947    if (!entry) return EINA_FALSE;
1948    type = elm_widget_type_get(entry);
1949    cnp_debug("type is %s\n", type);
1950    if ((!type) || (strcmp(type, "entry"))) return EINA_FALSE;
1951
1952    v = evas_object_data_get(entry, PROVIDER_SET);
1953    if (!v)
1954      {
1955         evas_object_data_set(entry, PROVIDER_SET, pasteimage_provider_set);
1956         elm_entry_item_provider_append(entry, image_provider, NULL);
1957         evas_object_event_callback_add(entry, EVAS_CALLBACK_FREE,
1958                                        entry_deleted, NULL);
1959      }
1960    return EINA_TRUE;
1961 }
1962
1963
1964 static Eina_Bool
1965 pasteimage_append(Paste_Image *pi, Evas_Object *entry)
1966 {
1967    char *entrytag;
1968    int len;
1969    static const char *tagstring = "<item absize=240x180 href=file://%s></item>";
1970
1971    if (!pi) return EINA_FALSE;
1972    if (!entry) return EINA_FALSE;
1973
1974    pasteimage_provider_set(entry);
1975
1976    len = strlen(tagstring)+strlen(pi->file);
1977
1978    pastedimages = eina_list_append(pastedimages, pi);
1979    entrytag = alloca(len + 1);
1980    snprintf(entrytag, len + 1, tagstring, pi->file);
1981    elm_entry_entry_insert(entry, entrytag);
1982
1983    return EINA_TRUE;
1984 }
1985
1986 static void
1987 entry_deleted(void *images __UNUSED__, Evas *e __UNUSED__, Evas_Object *entry, void *unused __UNUSED__)
1988 {
1989    Paste_Image *pi;
1990    Eina_List *l,*next;
1991
1992    EINA_LIST_FOREACH_SAFE(pastedimages, l, next, pi)
1993      {
1994         if (pi->entry == entry)
1995           pastedimages = eina_list_remove_list(pastedimages, l);
1996      }
1997 }
1998
1999
2000 static char *
2001 remove_tags(const char *p, int *len)
2002 {
2003    char *q,*ret;
2004    int i;
2005    if (!p) return NULL;
2006
2007    q = malloc(strlen(p) + 1);
2008    if (!q) return NULL;
2009    ret = q;
2010
2011    while (*p)
2012      {
2013         if ((*p != '<') && (*p != '&')) *q++ = *p++;
2014         else if (*p == '<')
2015           {
2016              if ((p[1] == 'b') && (p[2] == 'r') &&
2017                  ((p[3] == ' ') || (p[3] == '/') || (p[3] == '>')))
2018                *q++ = '\n';
2019              while ((*p) && (*p != '>')) p++;
2020              p++;
2021           }
2022         else if (*p == '&')
2023           {
2024              p++;
2025              for (i = 0 ; i < N_ESCAPES ; i++)
2026                {
2027                   if (!strncmp(p,escapes[i].escape, strlen(escapes[i].escape)))
2028                     {
2029                        p += strlen(escapes[i].escape);
2030                        *q = escapes[i].value;
2031                        q++;
2032                        break;
2033                     }
2034                }
2035              if (i == N_ESCAPES) *q ++= '&';
2036           }
2037      }
2038    *q = 0;
2039    if (len) *len = q - ret;
2040    return ret;
2041 }
2042
2043 /* Mark up */
2044 static char *
2045 mark_up(const char *start, int inlen, int *lenp)
2046 {
2047    int l, i;
2048    const char *p;
2049    char *q, *ret;
2050    const char *endp = NULL;
2051
2052    if (!start) return NULL;
2053    if (inlen >= 0) endp = start + inlen;
2054    /* First pass: Count characters */
2055    for (l = 0, p = start; ((!endp) || (p < endp)) && (*p); p++)
2056      {
2057         for (i = 0 ; i < N_ESCAPES ; i ++)
2058           {
2059              if (*p == escapes[i].value)
2060                {
2061                   l += strlen(escapes[i].escape);
2062                   break;
2063                }
2064           }
2065         if (i == N_ESCAPES) l++;
2066      }
2067
2068    q = ret = malloc(l + 1);
2069
2070    /* Second pass: Change characters */
2071    for (p = start; *p; )
2072      {
2073         for (i = 0; i < N_ESCAPES; i++)
2074           {
2075              if (*p == escapes[i].value)
2076                {
2077                   strcpy(q, escapes[i].escape);
2078                   q += strlen(escapes[i].escape);
2079                   p ++;
2080                   break;
2081                }
2082           }
2083         if (i == N_ESCAPES) *q++ = *p++;
2084      }
2085    *q = 0;
2086
2087    if (lenp) *lenp = l;
2088    return ret;
2089 }
2090
2091
2092 static Eina_Bool
2093 _dnd_enter(void *data __UNUSED__, int etype __UNUSED__, void *ev)
2094 {
2095    Ecore_X_Event_Xdnd_Enter *enter = ev;
2096    int i;
2097
2098    /* Skip it */
2099    if ((!enter) || (!enter->num_types) || (!enter->types)) return EINA_TRUE;
2100
2101    cnp_debug("Types\n");
2102    savedtypes.ntypes = enter->num_types;
2103    if (savedtypes.types) free(savedtypes.types);
2104    savedtypes.types = malloc(sizeof(char *) * enter->num_types);
2105    if (!savedtypes.types) return EINA_FALSE;
2106
2107    for (i = 0; i < enter->num_types; i++)
2108      {
2109         savedtypes.types[i] = eina_stringshare_add(enter->types[i]);
2110         cnp_debug("Type is %s %p %p\n", enter->types[i],
2111                   savedtypes.types[i],text_uri);
2112         if (savedtypes.types[i] == text_uri)
2113           {
2114              /* Request it, so we know what it is */
2115              cnp_debug("Sending uri request\n");
2116              savedtypes.textreq = 1;
2117              savedtypes.pi = NULL; /* FIXME: Free? */
2118              ecore_x_selection_xdnd_request(enter->win, text_uri);
2119           }
2120      }
2121
2122    /* FIXME: Find an object and make it current */
2123    return EINA_TRUE;
2124 }
2125
2126 static Eina_Bool
2127 _dnd_drop(void *data __UNUSED__, int etype __UNUSED__, void *ev)
2128 {
2129    struct _Ecore_X_Event_Xdnd_Drop *drop;
2130    Dropable *dropable;
2131    Eina_List *l;
2132    Ecore_Evas *ee;
2133    Ecore_X_Window xwin;
2134    Elm_Selection_Data ddata;
2135    int x, y, w, h;
2136    int i, j;
2137
2138    drop = ev;
2139
2140    // check we still have something to drop
2141    if (!drops) return EINA_TRUE;
2142
2143    /* Find any widget in our window; then work out geometry rel to our window */
2144    for (l = drops; l; l = l->next)
2145      {
2146         dropable = l->data;
2147         xwin = (Ecore_X_Window)ecore_evas_window_get
2148            (ecore_evas_ecore_evas_get(evas_object_evas_get
2149                                       (dropable->obj)));
2150         if (xwin == drop->win) break;
2151      }
2152    /* didn't find a window */
2153    if (!l) return EINA_TRUE;
2154
2155    /* Calculate real (widget relative) position */
2156    // - window position
2157    // - widget position
2158    ee = ecore_evas_ecore_evas_get(evas_object_evas_get(dropable->obj));
2159    ecore_evas_geometry_get(ee, &x, &y, NULL, NULL);
2160    savedtypes.x = drop->position.x - x;
2161    savedtypes.y = drop->position.y - y;
2162
2163    cnp_debug("Drop position is %d,%d\n", savedtypes.x, savedtypes.y);
2164
2165    for (; l; l = l->next)
2166      {
2167         dropable = l->data;
2168         evas_object_geometry_get(dropable->obj, &x, &y, &w, &h);
2169         if ((savedtypes.x >= x) && (savedtypes.y >= y) &&
2170             (savedtypes.x < x + w) && (savedtypes.y < y + h))
2171           break; /* found! */
2172      }
2173
2174    if (!l) return EINA_TRUE; /* didn't find one */
2175
2176    evas_object_geometry_get(dropable->obj, &x, &y, NULL, NULL);
2177    savedtypes.x -= x;
2178    savedtypes.y -= y;
2179
2180    /* Find our type from the previous list */
2181    for (i = 0; i < CNP_N_ATOMS; i++)
2182      {
2183         for (j = 0; j < savedtypes.ntypes; j++)
2184           {
2185              if (!strcmp(savedtypes.types[j], atoms[i].name)) goto found;
2186           }
2187      }
2188
2189    cnp_debug("Didn't find a target\n");
2190    return EINA_TRUE;
2191
2192 found:
2193    cnp_debug("Found a target we'd like: %s\n", atoms[i].name);
2194    cnp_debug("0x%x\n",xwin);
2195
2196    if (i == CNP_ATOM_text_urilist)
2197      {
2198         cnp_debug("We found a URI... (%scached) %s\n",
2199                   savedtypes.pi ? "" : "not ",
2200                   savedtypes.pi->file);
2201         if (savedtypes.pi)
2202           {
2203              char *entrytag;
2204              static const char *tagstring = "<item absize=240x180 href="
2205                 "file://%s></item>";
2206              ddata.x = savedtypes.x;
2207              ddata.y = savedtypes.y;
2208
2209              /* If it's markup that also supports images */
2210              if ((dropable->types & ELM_SEL_FORMAT_MARKUP) &&
2211                  (dropable->types & ELM_SEL_FORMAT_IMAGE))
2212                {
2213                   int len;
2214                   ddata.format = ELM_SEL_FORMAT_MARKUP;
2215                   pasteimage_provider_set(dropable->obj);
2216
2217                   pastedimages = eina_list_append(pastedimages, savedtypes.pi);
2218                   len = strlen(tagstring) + strlen(savedtypes.pi->file);
2219                   entrytag = alloca(len + 1);
2220                   snprintf(entrytag, len + 1, tagstring, savedtypes.pi->file);
2221                   ddata.data = entrytag;
2222                   cnp_debug("Insert %s\n", (char *)ddata.data);
2223                   dropable->dropcb(dropable->cbdata, dropable->obj, &ddata);
2224                   ecore_x_dnd_send_finished();
2225                   return EINA_TRUE;
2226                }
2227              else if (dropable->types & ELM_SEL_FORMAT_IMAGE)
2228                {
2229                   cnp_debug("Doing image insert (%s)\n", savedtypes.pi->file);
2230                   ddata.format = ELM_SEL_FORMAT_IMAGE;
2231                   ddata.data = (char *)savedtypes.pi->file;
2232                   dropable->dropcb(dropable->cbdata, dropable->obj, &ddata);
2233                   ecore_x_dnd_send_finished();
2234
2235                   pasteimage_free(savedtypes.pi);
2236                   savedtypes.pi = NULL;
2237
2238                   return EINA_TRUE;
2239                }
2240              else
2241                {
2242                   cnp_debug("Item doesn't support images... passing\n");
2243                   pasteimage_free(savedtypes.pi);
2244                   return EINA_TRUE;
2245                }
2246           }
2247         else if (savedtypes.textreq)
2248           {
2249              /* Already asked: Pretend we asked now, and paste immediately when
2250               * it comes in */
2251              savedtypes.textreq = 0;
2252              ecore_x_dnd_send_finished();
2253              return EINA_TRUE;
2254           }
2255      }
2256
2257    cnp_debug("doing a request then\n");
2258    selections[ELM_SEL_XDND].requestwidget = dropable->obj;
2259    selections[ELM_SEL_XDND].requestformat = ELM_SEL_FORMAT_MARKUP;
2260    selections[ELM_SEL_XDND].active = EINA_TRUE;
2261
2262    ecore_x_selection_xdnd_request(xwin, atoms[i].name);
2263
2264    return EINA_TRUE;
2265 }
2266 static Eina_Bool
2267 _dnd_position(void *data __UNUSED__, int etype __UNUSED__, void *ev)
2268 {
2269    struct _Ecore_X_Event_Xdnd_Position *pos;
2270    Ecore_X_Rectangle rect;
2271
2272    pos = ev;
2273
2274    /* Need to send a status back */
2275    /* FIXME: Should check I can drop here */
2276    /* FIXME: Should highlight widget */
2277    rect.x = pos->position.x - 5;
2278    rect.y = pos->position.y - 5;
2279    rect.width = 10;
2280    rect.height = 10;
2281    ecore_x_dnd_send_status(EINA_TRUE, EINA_FALSE, rect, pos->action);
2282
2283    return EINA_TRUE;
2284 }
2285
2286 /**
2287  * When dragging this is callback response from the destination.
2288  * The important thing we care about: Can we drop; thus update cursor
2289  * appropriately.
2290  */
2291 static Eina_Bool
2292 _dnd_status(void *data __UNUSED__, int etype __UNUSED__, void *ev)
2293 {
2294    struct _Ecore_X_Event_Xdnd_Status *status = ev;
2295
2296    if (!status) return EINA_TRUE;
2297
2298    /* Only thing we care about: will accept */
2299    if (status->will_accept)
2300      {
2301         cnp_debug("Will accept\n");
2302      }
2303    else
2304      { /* Won't accept */
2305         cnp_debug("Won't accept accept\n");
2306      }
2307    return EINA_TRUE;
2308 }
2309
2310 /**
2311  * Add a widget as drop target.
2312  */
2313 Eina_Bool
2314 elm_drop_target_add(Evas_Object *obj, Elm_Sel_Type format, Elm_Drop_Cb dropcb, void *cbdata)
2315 {
2316    Dropable *drop;
2317    Ecore_X_Window xwin;
2318    Eina_List *item;
2319    int first;
2320
2321    if (!obj) return EINA_FALSE;
2322    if (!_elm_cnp_init_count) _elm_cnp_init();
2323
2324    /* Is this the first? */
2325    first = (!drops) ? 1 : 0;
2326
2327    EINA_LIST_FOREACH(drops, item, drop)
2328      {
2329         if (drop->obj == obj)
2330           {
2331              /* Update: Not a new one */
2332              drop->dropcb = dropcb;
2333              drop->cbdata = cbdata;
2334              drop->types = format;
2335              return EINA_TRUE;
2336           }
2337      }
2338
2339    /* Create new drop */
2340    drop = calloc(1, sizeof(Dropable));
2341    if (!drop) return EINA_FALSE;
2342    /* FIXME: Check for eina's deranged error method */
2343    drops = eina_list_append(drops, drop);
2344
2345    if (!drops/* || or other error */)
2346      {
2347         free(drop);
2348         return EINA_FALSE;
2349      }
2350    drop->dropcb = dropcb;
2351    drop->cbdata = cbdata;
2352    drop->types = format;
2353    drop->obj = obj;
2354
2355    evas_object_event_callback_add(obj, EVAS_CALLBACK_DEL,
2356                                   /* I love C and varargs */
2357                                   (Evas_Object_Event_Cb)elm_drop_target_del,
2358                                   obj);
2359    /* FIXME: Handle resizes */
2360
2361    /* If not the first: We're done */
2362    if (!first) return EINA_TRUE;
2363
2364    xwin = (Ecore_X_Window)ecore_evas_window_get
2365       (ecore_evas_ecore_evas_get(evas_object_evas_get(obj)));
2366
2367    ecore_x_dnd_aware_set(xwin, EINA_TRUE);
2368
2369    cnp_debug("Adding drop target calls\n");
2370    handler_enter = ecore_event_handler_add(ECORE_X_EVENT_XDND_ENTER,
2371                                            _dnd_enter, NULL);
2372    handler_pos = ecore_event_handler_add(ECORE_X_EVENT_XDND_POSITION,
2373                                          _dnd_position, NULL);
2374    handler_drop = ecore_event_handler_add(ECORE_X_EVENT_XDND_DROP,
2375                                           _dnd_drop, NULL);
2376
2377    return EINA_TRUE;
2378 }
2379
2380 Eina_Bool
2381 elm_drop_target_del(Evas_Object *obj)
2382 {
2383    Dropable *drop,*del;
2384    Eina_List *item;
2385    Ecore_X_Window xwin;
2386
2387    del = NULL;
2388    EINA_LIST_FOREACH(drops, item, drop)
2389      {
2390         if (drop->obj == obj)
2391           {
2392              drops = eina_list_remove_list(drops, item);
2393              del = drop;
2394              break;
2395           }
2396      }
2397    if (!del) return EINA_FALSE;
2398
2399    evas_object_event_callback_del(obj, EVAS_CALLBACK_FREE,
2400                                   (Evas_Object_Event_Cb)elm_drop_target_del);
2401    free(drop);
2402    /* If still drops there: All fine.. continue */
2403    if (drops) return EINA_TRUE;
2404
2405    cnp_debug("Disabling DND\n");
2406    xwin = (Ecore_X_Window)ecore_evas_window_get
2407       (ecore_evas_ecore_evas_get(evas_object_evas_get(obj)));
2408    ecore_x_dnd_aware_set(xwin, EINA_FALSE);
2409
2410    ecore_event_handler_del(handler_pos);
2411    ecore_event_handler_del(handler_drop);
2412    ecore_event_handler_del(handler_enter);
2413
2414    if (savedtypes.pi)
2415      {
2416         pasteimage_free(savedtypes.pi);
2417         savedtypes.pi = NULL;
2418      }
2419
2420    return EINA_TRUE;
2421 }
2422
2423
2424 static void
2425 _drag_mouse_up(void *un __UNUSED__, Evas *e __UNUSED__, Evas_Object *obj, void *data __UNUSED__)
2426 {
2427    evas_object_event_callback_del(obj, EVAS_CALLBACK_MOUSE_UP, _drag_mouse_up);
2428    ecore_x_dnd_drop();
2429    if (dragdonecb)
2430      {
2431         dragdonecb(dragdonecb,selections[ELM_SEL_XDND].widget);
2432         dragdonecb = NULL;
2433      }
2434    if (dragwin)
2435      {
2436         evas_object_del(dragwin);
2437         dragwin = NULL;
2438      }
2439 }
2440
2441 static void
2442 _drag_move(void *data __UNUSED__, Ecore_X_Xdnd_Position *pos)
2443 {
2444    evas_object_move(dragwin,
2445                     pos->position.x - _dragx,
2446                     pos->position.y - _dragy);
2447 }
2448
2449
2450 Eina_Bool
2451 elm_drag_start(Evas_Object *obj, Elm_Sel_Format format, const char *data, void (*dragdone) (void *data, Evas_Object *), void *donecbdata)
2452 {
2453    Ecore_X_Window xwin;
2454    Cnp_Selection *sel;
2455    Elm_Sel_Type xdnd = ELM_SEL_XDND;
2456    Ecore_Evas *ee;
2457    int x, y, x2, y2, x3, y3;
2458    Evas_Object *icon;
2459    int w, h;
2460
2461    if (!_elm_cnp_init_count) _elm_cnp_init();
2462
2463    xwin = elm_win_xwindow_get(obj);
2464
2465    cnp_debug("starting drag...\n");
2466
2467    ecore_x_dnd_type_set(xwin, "text/uri-list", 1);
2468    sel = selections + ELM_SEL_XDND;
2469    sel->active = 1;
2470    sel->widget = obj;
2471    sel->format = format;
2472    sel->selbuf = data ? strdup(data) : NULL;
2473    dragdonecb = dragdone;
2474    dragdonedata = donecbdata;
2475
2476    ecore_x_dnd_callback_pos_update_set(_drag_move, NULL);
2477    ecore_x_dnd_begin(xwin, (unsigned char *)&xdnd, sizeof(Elm_Sel_Type));
2478    evas_object_event_callback_add(obj, EVAS_CALLBACK_MOUSE_UP,
2479                                   _drag_mouse_up, NULL);
2480
2481    handler_status = ecore_event_handler_add(ECORE_X_EVENT_XDND_STATUS,
2482                                             _dnd_status, NULL);
2483
2484    dragwin = elm_win_add(NULL, "Elm Drag Object", ELM_WIN_UTILITY);
2485    elm_win_override_set(dragwin, 1);
2486
2487    /* FIXME: Images only */
2488    icon = elm_icon_add(dragwin);
2489    elm_icon_file_set(icon, data + 7, NULL); /* 7!? "file://" */
2490    elm_win_resize_object_add(dragwin,icon);
2491    evas_object_size_hint_weight_set(icon, EVAS_HINT_EXPAND, EVAS_HINT_EXPAND);
2492    evas_object_size_hint_align_set(icon, EVAS_HINT_FILL, EVAS_HINT_FILL);
2493
2494    /* Position subwindow appropriately */
2495    ee = ecore_evas_ecore_evas_get(evas_object_evas_get(obj));
2496    ecore_evas_geometry_get(ee, &x, &y, NULL, NULL);
2497    evas_object_geometry_get(obj, &x2, &y2, &w, &h);
2498    x += x2;
2499    y += y2;
2500    evas_object_move(dragwin, x, y);
2501    evas_object_resize(icon, w, h);
2502    evas_object_resize(dragwin, w, h);
2503
2504    evas_object_show(icon);
2505    evas_object_show(dragwin);
2506
2507    evas_pointer_canvas_xy_get(evas_object_evas_get(obj), &x3, &y3);
2508    _dragx = x3 - x2;
2509    _dragy = y3 - y2;
2510
2511    return EINA_TRUE;
2512 }
2513
2514 static Tmp_Info *
2515 elm_cnp_tempfile_create(int size)
2516 {
2517    Tmp_Info *info;
2518    const char *tmppath;
2519    int len;
2520
2521    info = malloc(sizeof(Tmp_Info));
2522    if (!info) return NULL;
2523
2524    tmppath = getenv("TMP");
2525    if (!tmppath) tmppath = P_tmpdir;
2526    if (!tmppath) tmppath = "/tmp";
2527    len = snprintf(NULL, 0, "%s/%sXXXXXX", tmppath, "elmcnpitem-");
2528    if (len < 0)
2529      {
2530         free(info);
2531         return NULL;
2532      }
2533    len++;
2534    info->filename = malloc(len);
2535    if (!info->filename)
2536      {
2537         free(info);
2538         return NULL;
2539      }
2540    snprintf(info->filename,len,"%s/%sXXXXXX", tmppath, "elmcnpitem-");
2541
2542    info->fd = mkstemp(info->filename);
2543
2544 # ifdef __linux__
2545      {
2546         char *tmp;
2547         /* And before someone says anything see POSIX 1003.1-2008 page 400 */
2548         long pid;
2549
2550         pid = (long)getpid();
2551         /* Use pid instead of /proc/self: That way if can be passed around */
2552         len = snprintf(NULL,0,"/proc/%li/fd/%i", pid, info->fd);
2553         len++;
2554         tmp = malloc(len);
2555         if (tmp)
2556           {
2557              snprintf(tmp,len, "/proc/%li/fd/%i", pid, info->fd);
2558              unlink(info->filename);
2559              free(info->filename);
2560              info->filename = tmp;
2561           }
2562      }
2563 # endif
2564
2565    cnp_debug("filename is %s\n", info->filename);
2566    if (size < 1)
2567      {
2568         /* Set map to NULL and return */
2569         info->map = NULL;
2570         info->len = 0;
2571         return info;
2572      }
2573
2574    /* Map it in */
2575    if (ftruncate(info->fd, size))
2576      {
2577         perror("ftruncate");
2578         info->map = NULL;
2579         info->len = 0;
2580         return info;
2581      }
2582
2583    info->map = mmap(NULL, size, PROT_READ|PROT_WRITE, MAP_SHARED, info->fd, 0);
2584    if (info->map == MAP_FAILED)
2585      {
2586         perror("mmap");
2587         info->map = NULL;
2588         info->len = 0;
2589      }
2590
2591    return info;
2592 }
2593
2594
2595 static int
2596 tmpinfo_free(Tmp_Info *info)
2597 {
2598    if (!info) return 0;
2599    free(info->filename);
2600    free(info);
2601    return 0;
2602 }
2603
2604 #else
2605 /* Stubs for windows */
2606 Eina_Bool
2607 elm_drag_start(Evas_Object *o, Elm_Sel_Format f, const char *d, void (*donecb)(void *, Evas_Object *),void *cbdata)
2608 {
2609    return EINA_FALSE;
2610 }
2611
2612 Eina_Bool
2613 elm_drop_target_add(Evas_Object *obj, Elm_Sel_Type format, Elm_Drop_Cb dropcb, void *cbdata)
2614 {
2615    return EINA_FALSE;
2616 }
2617
2618 Eina_Bool
2619 elm_drop_target_del(Evas_Object *o)
2620 {
2621    return EINA_TRUE;
2622 }
2623 #endif
2624
2625 /* vim:set ts=8 sw=3 sts=3 expandtab cino=>5n-2f0^-2{2(0W1st0 :*/