Merge "base.src : thumbscroll_friction value changed from 3.0 to 1.0"
[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_edje(Cnp_Selection *sel, Ecore_X_Event_Selection_Notify *notify);
162 static int notify_handler_html(Cnp_Selection *sel, Ecore_X_Event_Selection_Notify *notify);
163 static int vcard_receive(Cnp_Selection *sed, Ecore_X_Event_Selection_Notify *notify);
164
165 static Paste_Image *pasteimage_alloc(const char *file, int pathlen);
166 static Eina_Bool pasteimage_append(Paste_Image *pi, Evas_Object *entry);
167 static void pasteimage_free(Paste_Image *pi);
168
169 /* Optimisation: Turn this into a 256 byte table:
170  *      then can lookup in one index, not N checks */
171 static const Escape escapes[] = {
172        { "<br>",   '\n' },
173        { "<\t>",   '\t' },
174        { "gt;",    '>'  },
175        { "lt;",    '<'  },
176        { "amp;",   '&'  },
177        { "quot;",  '\'' },
178        { "dquot;", '"'  }
179 };
180 #define N_ESCAPES ((int)(sizeof(escapes) / sizeof(escapes[0])))
181
182 static Cnp_Atom atoms[CNP_N_ATOMS] = {
183      [CNP_ATOM_TARGETS] = {
184           "TARGETS",
185           (Elm_Sel_Format) -1, // everything
186           targets_converter,
187           response_handler_targets,
188           notify_handler_targets,
189           0
190      },
191      [CNP_ATOM_XELM] =  {
192           "application/x-elementary-markup",
193           ELM_SEL_FORMAT_TEXT | ELM_SEL_FORMAT_MARKUP | ELM_SEL_FORMAT_HTML,
194           edje_converter,
195           NULL,
196           notify_handler_edje,
197           0
198      },
199      [CNP_ATOM_text_uri] = {
200           "text/uri",
201           ELM_SEL_FORMAT_MARKUP | ELM_SEL_FORMAT_IMAGE, /* Either images or entries */
202           uri_converter,
203           NULL,
204           notify_handler_uri,
205           0
206      },
207      [CNP_ATOM_text_urilist] = {
208           "text/uri-list",
209           ELM_SEL_FORMAT_IMAGE,
210           uri_converter,
211           NULL,
212           notify_handler_uri,
213           0
214      },
215      [CNP_ATOM_text_x_vcard] = {
216           "text/x-vcard",
217           ELM_SEL_FORMAT_VCARD,
218           vcard_send, NULL,
219           vcard_receive, 0
220      },
221      [CNP_ATOM_image_png] = {
222           "image/png",
223           ELM_SEL_FORMAT_IMAGE,
224           image_converter,
225           NULL,
226           notify_handler_image,
227           0
228      },
229      [CNP_ATOM_image_jpeg] = {
230           "image/jpeg",
231           ELM_SEL_FORMAT_IMAGE,
232           image_converter,
233           NULL,
234           notify_handler_image,/* Raw image data is the same */
235           0
236      },
237      [CNP_ATOM_image_bmp] = {
238           "image/x-ms-bmp",
239           ELM_SEL_FORMAT_IMAGE,
240           image_converter,
241           NULL,
242           notify_handler_image,/* Raw image data is the same */
243           0
244      },
245      [CNP_ATOM_image_gif] = {
246           "image/gif",
247           ELM_SEL_FORMAT_IMAGE,
248           image_converter,
249           NULL,
250           notify_handler_image,/* Raw image data is the same */
251           0
252      },
253      [CNP_ATOM_image_tiff] = {
254           "image/tiff",
255           ELM_SEL_FORMAT_IMAGE,
256           image_converter,
257           NULL,
258           notify_handler_image,/* Raw image data is the same */
259           0
260      },
261      [CNP_ATOM_image_svg] = {
262           "image/svg+xml",
263           ELM_SEL_FORMAT_IMAGE,
264           image_converter,
265           NULL,
266           notify_handler_image,/* Raw image data is the same */
267           0
268      },
269      [CNP_ATOM_image_xpm] = {
270           "image/x-xpixmap",
271           ELM_SEL_FORMAT_IMAGE,
272           image_converter,
273           NULL,
274           notify_handler_image,/* Raw image data is the same */
275           0
276      },
277      [CNP_ATOM_image_tga] = {
278           "image/x-tga",
279           ELM_SEL_FORMAT_IMAGE,
280           image_converter,
281           NULL,
282           notify_handler_image,/* Raw image data is the same */
283           0
284      },
285      [CNP_ATOM_image_ppm] = {
286           "image/x-portable-pixmap",
287           ELM_SEL_FORMAT_IMAGE,
288           image_converter,
289           NULL,
290           notify_handler_image,/* Raw image data is the same */
291           0
292      },
293      [CNP_ATOM_text_html_utf8] = {
294           "text/html;charset=utf-8",
295           ELM_SEL_FORMAT_HTML,
296           html_converter,
297           NULL,
298           notify_handler_html,
299           0
300      },
301      [CNP_ATOM_text_html] = {
302           "text/html",
303           ELM_SEL_FORMAT_HTML,
304           html_converter,
305           NULL,
306           notify_handler_html, /* No encoding: Webkit only */
307           0
308      },
309      [CNP_ATOM_UTF8STRING] = {
310           "UTF8_STRING",
311           ELM_SEL_FORMAT_TEXT | ELM_SEL_FORMAT_MARKUP | ELM_SEL_FORMAT_HTML,
312           text_converter,
313           NULL,
314           notify_handler_text,
315           0
316      },
317      [CNP_ATOM_STRING] = {
318           "STRING",
319           ELM_SEL_FORMAT_TEXT | ELM_SEL_FORMAT_MARKUP | ELM_SEL_FORMAT_HTML,
320           text_converter,
321           NULL,
322           notify_handler_text,
323           0
324      },
325      [CNP_ATOM_TEXT] = {
326           "TEXT",
327           ELM_SEL_FORMAT_TEXT | ELM_SEL_FORMAT_MARKUP | ELM_SEL_FORMAT_HTML,
328           text_converter,
329           NULL,
330           NULL,
331           0
332      },
333      [CNP_ATOM_text_plain_utf8] = {
334           "text/plain;charset=utf-8",
335           ELM_SEL_FORMAT_TEXT | ELM_SEL_FORMAT_MARKUP | ELM_SEL_FORMAT_HTML,
336           text_converter,
337           NULL,
338           NULL,
339           0
340      },
341      [CNP_ATOM_text_plain] = {
342           "text/plain",
343           ELM_SEL_FORMAT_TEXT | ELM_SEL_FORMAT_MARKUP | ELM_SEL_FORMAT_HTML,
344           text_converter,
345           NULL,
346           NULL,
347           0
348      },
349 };
350
351 static Cnp_Selection selections[ELM_SEL_MAX] = {
352      ARRAYINIT(ELM_SEL_PRIMARY) {
353           .debug = "Primary",
354           .ecore_sel = ECORE_X_SELECTION_PRIMARY,
355           .set = ecore_x_selection_primary_set,
356           .clear = ecore_x_selection_primary_clear,
357           .request = ecore_x_selection_primary_request,
358      },
359      ARRAYINIT(ELM_SEL_SECONDARY) {
360           .debug = "Secondary",
361           .ecore_sel = ECORE_X_SELECTION_SECONDARY,
362           .set = ecore_x_selection_secondary_set,
363           .clear = ecore_x_selection_secondary_clear,
364           .request = ecore_x_selection_secondary_request,
365      },
366      ARRAYINIT(ELM_SEL_CLIPBOARD) {
367           .debug = "Clipboard",
368           .ecore_sel = ECORE_X_SELECTION_CLIPBOARD,
369           .set = ecore_x_selection_clipboard_set,
370           .clear = ecore_x_selection_clipboard_clear,
371           .request = ecore_x_selection_clipboard_request,
372      },
373      ARRAYINIT(ELM_SEL_XDND) {
374           .debug = "XDnD",
375           .ecore_sel = ECORE_X_SELECTION_XDND,
376           .request = ecore_x_selection_xdnd_request,
377      },
378 };
379
380 /* Data for DND in progress */
381 static Saved_Type savedtypes =  { NULL, NULL, 0, 0, 0, EINA_FALSE };
382
383 static void (*dragdonecb) (void *data, Evas_Object *obj) = NULL;
384 static void *dragdonedata = NULL;
385
386 static int _elm_cnp_init_count = 0;
387 /* FIXME: who left this out of XAtoms.h */
388 static Ecore_X_Atom clipboard_atom;
389
390 static Eina_List *pastedimages = NULL;
391
392 /**
393  * Drag & Drop functions
394  */
395
396 /* FIXME: Way too many globals */
397 static Eina_List *drops = NULL;
398 static Evas_Object *dragwin = NULL;
399 static int _dragx = 0, _dragy = 0;
400 static Ecore_Event_Handler *handler_pos = NULL;
401 static Ecore_Event_Handler *handler_drop = NULL;
402 static Ecore_Event_Handler *handler_enter = NULL;
403 static Ecore_Event_Handler *handler_status = NULL;
404
405 #endif
406
407 /* Stringshared, so I can just compare pointers later */
408 static const char *text_uri;
409
410
411 /* For convert EFL to HTML */
412
413 #define TAGPOS_START    0x00000001
414 #define TAGPOS_END      0x00000002
415 #define TAGPOS_ALONE    0x00000003
416
417 /* TEXTBLOCK tag using stack but close tag word has no mean maybe bug...
418  * TEXTBLOCK <b>bold<font>font</b>bold</font>
419  * HTML <b>bold<font>font bold</b>font</font> */
420
421 typedef struct _TagTable {
422      char *src;
423      char *dst;
424      char tagType;
425 }TagTable;
426
427 TagTable _EFLtoHTMLConvertTable[] = {
428        {"font", "font", 0},
429        {"underline", "del", 0},
430        {"strikethrough", "ins", 0},
431        {"br", "br", 1},
432        {"b", "b", 1},
433        {"item", "img", 1}
434 };
435
436 TagTable _HTMLtoEFLConvertTable[] = {
437        {"font", "", 0},
438        {"del", "underline", 0},
439        {"u", "underline", 0},
440        {"ins", "strikethrough", 0},
441        {"s", "strikethrough", 0},
442        {"br", "br", 1},
443        {"b", "b", 1},
444        {"strong", "b", 1},
445        {"img", "item", 1}
446 };
447
448
449 typedef struct _TagNode TagNode, *PTagNode;
450 struct _TagNode {
451      char *tag;  //EINA_STRINGSHARE if NULL just str
452      char *tag_str;
453      char *str;
454      char *pos_in_ori_str;
455      PTagNode matchTag;
456      void *tagData;
457      unsigned char tagPosType;
458 };
459
460 typedef struct _FontTagData FontTagData, *PFontTagData;
461 struct _FontTagData {
462      char *name;
463      char *color;
464      char *size;
465      char *bg_color;
466 };
467
468
469 typedef struct _ItemTagData ItemTagData, *PItemTagData;
470 struct _ItemTagData {
471      char *href;
472      char *width;
473      char *height;
474 };
475
476 #define SAFEFREE(ptr) \
477    do\
478 {\
479    if (ptr)\
480    free(ptr);\
481    ptr = NULL;\
482 } while(0);\
483
484 #define freeAndAssign(dst, value) \
485    do\
486 {\
487    if (value)\
488      {\
489         SAFEFREE(dst);\
490         dst = value;\
491      }\
492 } while(0);
493
494
495 static PTagNode _new_tag_node(char *tag, char *tag_str, char* str, char *pos_in_ori_str);
496 static PTagNode _get_start_node(char *str);
497 static PTagNode _get_next_node(PTagNode prev);
498 static void _delete_node(PTagNode node);
499 static void _link_match_tags(Eina_List *nodes);
500 static char *_get_tag_value(const char *tag_str, const char *tag_name);
501 static char *_convert_to_html(Eina_List* nodes);
502 static void _set_EFL_tag_data(Eina_List* nodes);
503 static char *_convert_to_edje(Eina_List* nodes);
504 static void _set_HTML_tag_data(Eina_List* nodes);
505 static PFontTagData _set_EFL_font_data(PFontTagData data, const char *tag_str);
506 static PItemTagData _set_EFL_item_data(PItemTagData data, const char *tag_str);
507 static PFontTagData _set_HTML_font_data(PFontTagData data, const char *tag_str);
508 static PItemTagData _set_HTML_img_data(PItemTagData data, const char *tag_str);
509
510 #ifdef DEBUGON
511 static void _dumpNode(Eina_List* nodes);
512 #endif
513
514 static PTagNode
515 _new_tag_node(char *tag, char *tag_str, char* str, char *pos_in_ori_str)
516 {
517    PTagNode newNode = calloc(1, sizeof(TagNode));
518    newNode->tag = tag;
519    newNode->tag_str = tag_str;
520    newNode->str = str;
521    newNode->pos_in_ori_str = pos_in_ori_str;
522    return newNode;
523 }
524
525 static PTagNode
526 _get_start_node(char *str)
527 {
528    char *startStr = NULL;
529    if (!str || str[0] == '\0')
530      return NULL;
531
532    if (str[0] != '<')
533      {
534         char *tagStart = strchr(str, '<');
535         if (!tagStart)
536           startStr = strdup(str);
537         else
538           {
539              int strLength = tagStart - str;
540              startStr = malloc(sizeof(char) * (strLength + 1));
541              strncpy(startStr, str, strLength);
542              startStr[strLength] = '\0';
543           }
544      }
545
546    return _new_tag_node(NULL, NULL, startStr, str);
547 }
548
549 static PTagNode
550 _get_next_node(PTagNode prev)
551 {
552    PTagNode retTag = NULL;
553    char *tagStart;
554    char *tagEnd;
555    char *tagNameEnd = NULL;
556    char *nextTagStart;
557
558    if (prev->tag == NULL)
559      tagStart = strchr(prev->pos_in_ori_str, '<');
560    else
561      tagStart = strchr(prev->pos_in_ori_str + 1, '<');
562
563    if (!tagStart)
564      return retTag;
565
566    tagEnd = strchr(tagStart, '>');
567    nextTagStart = strchr(tagStart + 1, '<');
568
569    if (!tagEnd || (nextTagStart && (nextTagStart < tagEnd)))
570         return _get_start_node(tagStart + 1);
571
572    int spCnt = 5;
573    char *spArray[spCnt];
574    spArray[0] = strchr(tagStart, '=');
575    spArray[1] = strchr(tagStart, '_');
576    spArray[2] = strchr(tagStart, ' ');
577    spArray[3] = strchr(tagStart, '\t');
578    spArray[4] = strchr(tagStart, '\n');
579    tagNameEnd = tagEnd;
580
581    int i;
582    for (i = 0; i < spCnt; i++)
583      {
584         if (spArray[i] && spArray[i] < tagNameEnd)
585           tagNameEnd = spArray[i];
586      }
587
588    int tagLength = tagNameEnd - tagStart - 1;
589    char *tagName = NULL;
590    if (!strncmp(&tagStart[1], "color", tagLength))
591      tagName = strndup("font", 4);
592    else if (!strncmp(&tagStart[1], "/color", tagLength))
593      tagName = strndup("/font", 5);
594    else if (!strncmp(&tagStart[1], "/item", tagLength))
595      tagName = strdup("");
596    else
597      tagName = strndup(&tagStart[1], tagLength);
598
599    int tagStrLength = 0;
600    char *tagStr = NULL;
601    if (tagName)
602      {
603         tagStrLength = tagEnd - tagStart + 1;
604         tagStr = strndup(tagStart, tagStrLength);
605      }
606
607    unsigned int strLength = nextTagStart ? (unsigned int)(nextTagStart - tagEnd - 1) : strlen(&tagEnd[1]);
608    char *str = strndup(&tagEnd[1], strLength);
609
610    retTag = _new_tag_node(tagName, tagStr, str, tagStart);
611    return retTag;
612 }
613
614
615 static void
616 _delete_node(PTagNode node)
617 {
618    if (node)
619      {
620         SAFEFREE(node->tag_str);
621         SAFEFREE(node->str);
622
623         if (node->tagData)
624           {
625              if (node->tag)
626                {
627                   if (!strcmp("font", node->tag))
628                     {
629                        PFontTagData data = node->tagData;
630                        SAFEFREE(data->name);
631                        SAFEFREE(data->color);
632                        SAFEFREE(data->size);
633                        SAFEFREE(data->bg_color);
634                     }
635                   if (!strcmp("item", node->tag))
636                     {
637                        PItemTagData data = node->tagData;
638                        SAFEFREE(data->href);
639                        SAFEFREE(data->width);
640                        SAFEFREE(data->height);
641                     }
642
643                }
644              SAFEFREE(node->tagData);
645           }
646         SAFEFREE(node->tag);
647         SAFEFREE(node);
648      }
649 }
650
651 static void
652 _link_match_tags(Eina_List *nodes)
653 {
654    Eina_List *stack = NULL;
655
656    PTagNode trail, popData;
657    Eina_List *l, *r;
658
659    EINA_LIST_FOREACH(nodes, l, trail)
660      {
661         if (!trail->tag || trail->tag[0] == '\0')
662           continue;
663         if (!strcmp("br", trail->tag))
664           {
665              trail->tagPosType = TAGPOS_ALONE;
666              continue;
667           }
668         else if (!strcmp("item", trail->tag) || !strcmp("img", trail->tag))
669           {
670              trail->tagPosType = TAGPOS_ALONE;
671              continue;
672           }
673
674         if (trail->tag[0] != '/') // PUSH
675           {
676              stack = eina_list_append(stack, trail);
677 /*             eina_array_push(stack, trail);
678              cnp_debug("stack: %d, tag %s\n", eina_array_count_get(stack), trail->tag);*/
679              cnp_debug("stack: %d, tag %s\n", eina_list_count(stack), trail->tag);
680           }
681         else // POP
682           {
683              if (!eina_list_count(stack))
684                {
685                   cnp_debug("tag not matched %s\n", trail->tag);
686                   continue;
687                }
688
689              EINA_LIST_REVERSE_FOREACH(stack, r, popData)
690                {
691                   if (popData->tag && !strcmp(popData->tag, &trail->tag[1]))
692                     {
693                        popData->tagPosType = TAGPOS_START;
694                        trail->tagPosType = TAGPOS_END;
695                        popData->matchTag = trail;
696                        trail->matchTag = popData;
697                        stack = eina_list_remove_list(stack, r);
698                        break;
699                     }
700                }
701 /*             popData = eina_array_pop(stack);
702
703              popData->tagPosType = TAGPOS_START;
704              trail->tagPosType = TAGPOS_END;
705              popData->matchTag = trail;
706              trail->matchTag = popData;
707              cnp_debug("pop stack: %d, tag %s\n", eina_array_count_get(stack), trail->tag);
708              */
709           }
710      }
711
712 /*   if (eina_array_count_get(stack))
713      cnp_debug("stack state: %d, tag %s\n", eina_array_count_get(stack), trail->tag);*/
714
715    /* Make Dummy close tag */
716 /*   while ((popData = eina_array_pop(stack)))  */
717
718    EINA_LIST_REVERSE_FOREACH(stack, r, popData)
719      {
720         PTagNode newData;
721         int tagLength = strlen(popData->tag);
722         char *tagName = malloc(sizeof(char) * (tagLength + 2));
723
724         tagName[0] = '/';
725         tagName[1] = '\0';
726         strcat(tagName, popData->tag);
727
728         newData = _new_tag_node(tagName, NULL, NULL, NULL);
729         popData->tagPosType = TAGPOS_START;
730         newData->tagPosType = TAGPOS_END;
731         popData->matchTag = newData;
732         newData->matchTag = popData;
733         nodes = eina_list_append(nodes, newData);
734 /*        cnp_debug("stack: %d, tag %s\n", eina_array_count_get(stack), popData->tag);*/
735      }
736 /*   cnp_debug("stack_top: %d\n", eina_array_count_get(stack));
737    eina_array_free(stack);*/
738    eina_list_free(stack);
739 }
740
741 static char *
742 _get_tag_value(const char *tag_str, const char *tag_name)
743 {
744    if (!tag_name || !tag_str)
745      return NULL;
746
747    char *tag;
748    if ((tag = strstr(tag_str, tag_name)))
749      {
750         if (tag[strlen(tag_name)] == '_')
751           return NULL;
752         char *value = strchr(tag, '=');
753         if (value)
754           {
755              do
756                {
757                   value++;
758                } while (!isalnum(*value) && *value != '#');
759
760              int spCnt = 6;
761              char *spArray[spCnt];
762              spArray[0] = strchr(value, ' ');
763              spArray[1] = strchr(value, '>');
764              spArray[2] = strchr(value, '\"');
765              spArray[3] = strchr(value, '\'');
766              spArray[4] = strchr(value, '\t');
767              spArray[5] = strchr(value, '\n');
768              char *valueEnd = strchr(value, '\0');
769
770              int i;
771              for (i = 0; i < spCnt; i++)
772                {
773                   if (spArray[i] && spArray[i] < valueEnd)
774                     valueEnd = spArray[i];
775                }
776
777              int valueLength = valueEnd - value;
778              return strndup(value, valueLength);
779           }
780      }
781    return NULL;
782 }
783
784 static PFontTagData
785 _set_EFL_font_data(PFontTagData data, const char *tag_str)
786 {
787    char *value;
788
789    if (!data)
790      data = calloc(1, sizeof(FontTagData));
791    value = _get_tag_value(tag_str, "font_size");
792    freeAndAssign(data->size, value);
793    value = _get_tag_value(tag_str, "color");
794    freeAndAssign(data->color, value);
795    value = _get_tag_value(tag_str, "bgcolor");
796    freeAndAssign(data->bg_color, value);
797    value = _get_tag_value(tag_str, "font");
798    freeAndAssign(data->name, value);
799
800    return data;
801 }
802
803 static PItemTagData
804 _set_EFL_item_data(PItemTagData data, const char *tag_str)
805 {
806    char *value;
807
808    if (!data)
809      data = calloc(1, sizeof(ItemTagData));
810    value = _get_tag_value(tag_str, "href");
811    if (value)
812      {
813         char *path = strstr(value, "file://");
814         if (path)
815           {
816              char *modify = malloc(sizeof(char) * (strlen(value) + 1));
817              strncpy(modify, "file://", 7);
818              modify[7] = '\0';
819              path += 7;
820              while (path[1] && path[0] && path[1] == '/' && path[0] == '/')
821                {
822                   path++;
823                }
824              strcat(modify, path);
825              data->href = modify;
826              cnp_debug("image href ---%s---\n", data->href);
827           }
828         else
829           freeAndAssign(data->href, value);
830         free(value);
831      }
832
833    value = _get_tag_value(tag_str, "absize");
834    if (value)
835      {
836         char *xpos = strchr(value, 'x');
837         if (xpos)
838           {
839              int absizeLen = strlen(value);
840              freeAndAssign(data->width, strndup(value, xpos - value));
841              freeAndAssign(data->height, strndup(xpos + 1, absizeLen - (xpos - value) - 1));
842              cnp_debug("image width: -%s-, height: -%s-\n", data->width, data->height);
843           }
844         free(value);
845      }
846    return data;
847 }
848
849 static void
850 _set_EFL_tag_data(Eina_List* nodes)
851 {
852    PTagNode trail;
853    Eina_List *l;
854
855    EINA_LIST_FOREACH(nodes, l, trail)
856      {
857         if (!trail->tag)
858           continue;
859         if (!strcmp("font", trail->tag))
860              trail->tagData = _set_EFL_font_data(trail->tagData, trail->tag_str);
861         else if (!strcmp("item", trail->tag))
862              trail->tagData = _set_EFL_item_data(trail->tagData, trail->tag_str);
863      }
864 }
865
866 static PFontTagData
867 _set_HTML_font_data(PFontTagData data, const char *tag_str)
868 {
869    char *value;
870
871    if (!data)
872      data = calloc(1, sizeof(FontTagData));
873    value = _get_tag_value(tag_str, "size");
874    freeAndAssign(data->size, value);
875    value = _get_tag_value(tag_str, "color");
876    freeAndAssign(data->color, value);
877    value = _get_tag_value(tag_str, "bgcolor");
878    freeAndAssign(data->bg_color, value);
879    value = _get_tag_value(tag_str, "face");
880    freeAndAssign(data->name, value);
881
882    return data;
883 }
884
885 static PItemTagData
886 _set_HTML_img_data(PItemTagData data, const char *tag_str)
887 {
888    char *value;
889
890    if (!data)
891      data = calloc(1, sizeof(ItemTagData));
892    value = _get_tag_value(tag_str, "src");
893    if (value)
894      {
895         char *path = strstr(value, "file://");
896         if (path)
897           {
898              char *modify = malloc(sizeof(char) * (strlen(value) + 1));
899              strncpy(modify, "file://", 7);
900              modify[7] = '\0';
901              path += 7;
902              while (path[1] && path[0] && path[1] == '/' && path[0] == '/')
903                {
904                   path++;
905                }
906              strcat(modify, path);
907              data->href = modify;
908              cnp_debug("image src ---%s---\n", data->href);
909           }
910         else
911           freeAndAssign(data->href, value);
912         free(value);
913      }
914
915    value = _get_tag_value(tag_str, "width");
916    freeAndAssign(data->width, value);
917    value = _get_tag_value(tag_str, "height");
918    freeAndAssign(data->height, value);
919    return data;
920 }
921
922 static void
923 _set_HTML_tag_data(Eina_List* nodes)
924 {
925    PTagNode trail;
926    Eina_List *l;
927
928    EINA_LIST_FOREACH(nodes, l, trail)
929      {
930         if (!trail->tag)
931           continue;
932         if (!strcmp("font", trail->tag))
933              trail->tagData = _set_HTML_font_data(trail->tagData, trail->tag_str);
934         else if (!strcmp("img", trail->tag))
935              trail->tagData = _set_HTML_img_data(trail->tagData, trail->tag_str);
936      }
937 }
938
939 #ifdef DEBUGON
940 static void
941 _dumpNode(Eina_List* nodes)
942 {
943    PTagNode trail;
944    Eina_List *l;
945
946    EINA_LIST_FOREACH(nodes, l, trail)
947      {
948         cnp_debug("tag: %s, tag_str: %s, str: %s, tagPosType: %d\n",
949                trail->tag, trail->tag_str, trail->str, trail->tagPosType);
950         cnp_debug("matchTag: %x ", (unsigned int)trail->matchTag);
951         if (trail->matchTag)
952           cnp_debug("matchTag->tag_str: %s", trail->matchTag->tag_str);
953         if (trail->tagData)
954           {
955              if (!strcmp(trail->tag, "font"))
956                {
957                   PFontTagData data = trail->tagData;
958                   cnp_debug(" tagData->name: %s, tagData->color: %s, tagData->size: %s, tagData->bg_color: %s",
959                          data->name, data->color, data->size, data->bg_color);
960                }
961              else if (!strcmp(trail->tag, "item") || !strcmp(trail->tag, "img"))
962                {
963                   PItemTagData data = trail->tagData;
964                   cnp_debug(" tagData->href: %s, tagData->width: %s, tagData->height: %s",
965                          data->href, data->width, data->height);
966                }
967              else
968                cnp_debug("\nERROR!!!! not need tagData");
969           }
970         cnp_debug("\n");
971      }
972 }
973 #endif
974
975 static char *
976 _convert_to_html(Eina_List* nodes)
977 {
978    PTagNode trail;
979    Eina_List *l;
980
981    Eina_Strbuf *html = eina_strbuf_new();
982
983    int tableCnt = sizeof(_EFLtoHTMLConvertTable) / sizeof(TagTable);
984
985    EINA_LIST_FOREACH(nodes, l, trail)
986      {
987         if (trail->tag)
988           {
989              char *tagName = trail->tagPosType == TAGPOS_END ?
990                 trail->matchTag->tag : trail->tag;
991              int j;
992              for(j = 0; j < tableCnt; j++)
993                {
994                   if (!strcmp(_EFLtoHTMLConvertTable[j].src, tagName))
995                     {
996                        switch(trail->tagPosType)
997                          {
998                           case TAGPOS_END:
999                              eina_strbuf_append(html, "</");
1000                              break;
1001                           default:
1002                              eina_strbuf_append(html, "<");
1003                              break;
1004                          }
1005
1006                        eina_strbuf_append(html, _EFLtoHTMLConvertTable[j].dst);
1007                        if (trail->tagPosType != TAGPOS_END)
1008                          {
1009                             if (!strcmp(_EFLtoHTMLConvertTable[j].src, "font"))
1010                               {
1011                                  PFontTagData data = trail->tagData;
1012                                  if (data->name)
1013                                    {
1014                                    }
1015                                  if (data->color)
1016                                    eina_strbuf_append_printf(html, " color=\"%s\"", data->color);
1017                                  if (data->size)
1018                                    eina_strbuf_append_printf(html, " size=\"%s\"", data->size);
1019                                  if (data->bg_color)
1020                                    {
1021                                    }
1022                               }
1023                             else if (!strcmp(_EFLtoHTMLConvertTable[j].src, "item"))
1024                               {
1025                                  PItemTagData data = trail->tagData;
1026                                  if (data->href)
1027                                    eina_strbuf_append_printf(html, " src=\"%s\"", data->href);
1028                                  if (data->width)
1029                                    eina_strbuf_append_printf(html, " width=\"%s\"", data->width);
1030                                  if (data->height)
1031                                    eina_strbuf_append_printf(html, " height=\"%s\"", data->height);
1032                               }
1033                          }
1034                        switch(trail->tagPosType)
1035                          {
1036                           case TAGPOS_ALONE:
1037                              eina_strbuf_append(html, " />");
1038                              break;
1039                           default:
1040                              eina_strbuf_append(html, ">");
1041                              break;
1042                          }
1043                        break;
1044                     }
1045                }
1046           }
1047         if (trail->str)
1048           eina_strbuf_append(html, trail->str);
1049      }
1050
1051    char *ret = eina_strbuf_string_steal(html);
1052    eina_strbuf_free(html);
1053    return ret;
1054 }
1055
1056 #define IMAGE_DEFAULT_WIDTH "240"
1057 #define IMAGE_DEFAULT_HEIGHT "180"
1058
1059
1060 static char *
1061 _convert_to_edje(Eina_List* nodes)
1062 {
1063    PTagNode trail;
1064    Eina_List *l;
1065
1066    Eina_Strbuf *html = eina_strbuf_new();
1067
1068    int tableCnt = sizeof(_HTMLtoEFLConvertTable) / sizeof(TagTable);
1069
1070    EINA_LIST_FOREACH(nodes, l, trail)
1071      {
1072         if (trail->tag)
1073           {
1074              char *tagName = trail->tagPosType == TAGPOS_END ?
1075                 trail->matchTag->tag : trail->tag;
1076              int j;
1077              for(j = 0; j < tableCnt; j++)
1078                {
1079                   if (!strcmp(_HTMLtoEFLConvertTable[j].src, tagName))
1080                     {
1081                        if (_HTMLtoEFLConvertTable[j].dst[0] != '\0')
1082                          {
1083                             switch(trail->tagPosType)
1084                               {
1085                                case TAGPOS_END:
1086                                   eina_strbuf_append(html, "</");
1087                                   break;
1088                                default:
1089                                   eina_strbuf_append(html, "<");
1090                                   break;
1091                               }
1092
1093                             eina_strbuf_append(html, _HTMLtoEFLConvertTable[j].dst);
1094                          }
1095                        if (trail->tagPosType != TAGPOS_END)
1096                          {
1097                             if (!strcmp(_HTMLtoEFLConvertTable[j].src, "font"))
1098                               {
1099                                  PFontTagData data = trail->tagData;
1100                                  if (data->name)
1101                                    {
1102                                    }
1103                                  if (data->color)
1104                                    eina_strbuf_append_printf(html, "<color=%s>", data->color);
1105                                  if (data->size)
1106                                    eina_strbuf_append_printf(html, "<font_size=%s>", data->size);
1107                                  if (data->bg_color)
1108                                    {
1109                                    }
1110                                  break;
1111                               }
1112                             else if (!strcmp(_HTMLtoEFLConvertTable[j].src, "img"))
1113                               {
1114                                  PItemTagData data = trail->tagData;
1115                                  char *width = IMAGE_DEFAULT_WIDTH, *height = IMAGE_DEFAULT_HEIGHT;                                 if (data->width)
1116                                    width = data->width;
1117                                  if (data->height)
1118                                    height = data->height;
1119                                  eina_strbuf_append_printf(html, " absize=%sx%s", width, height);
1120                                  if (data->href)
1121                                    eina_strbuf_append_printf(html, " href=%s></item>", data->href);
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 static int
1675 notify_handler_edje(Cnp_Selection *sel, Ecore_X_Event_Selection_Notify *notify)
1676 {
1677    Ecore_X_Selection_Data *data;
1678
1679    data = notify->data;
1680
1681    char *stripstr = NULL;
1682    stripstr = malloc(sizeof(char) * (data->length + 1));
1683    strncpy(stripstr, (char *)data->data, data->length);
1684    stripstr[data->length] = '\0';
1685
1686    if (sel->datacb)
1687      {
1688         Elm_Selection_Data ddata;
1689         ddata.x = ddata.y = 0;
1690         ddata.format = ELM_SEL_FORMAT_MARKUP;
1691         ddata.data = stripstr;
1692         ddata.len = data->length;
1693         sel->datacb(sel->udata, sel->widget, &ddata);
1694      }
1695    else
1696      elm_entry_entry_insert(sel->requestwidget, stripstr);
1697
1698    cnp_debug("String is %s (%d bytes)\n", stripstr, data->length);
1699    free(stripstr);
1700    return 0;
1701 }
1702 /**
1703  *    Warning: Generic text/html can';t handle it sanely.
1704  *    Firefox sends ucs2 (i think).
1705  *       chrome sends utf8... blerg
1706  */
1707 static int
1708 notify_handler_html(Cnp_Selection *sel, Ecore_X_Event_Selection_Notify *notify)
1709 {
1710    Ecore_X_Selection_Data *data;
1711
1712    cnp_debug("Got some HTML: Checking encoding is useful\n");
1713    data = notify->data;
1714
1715    char *stripstr = NULL;
1716    stripstr = malloc(sizeof(char) * (data->length + 1));
1717    strncpy(stripstr, (char *)data->data, data->length);
1718    stripstr[data->length] = '\0';
1719
1720    if (sel->datacb)
1721      {
1722         Elm_Selection_Data ddata;
1723         ddata.x = ddata.y = 0;
1724         ddata.format = ELM_SEL_FORMAT_HTML;
1725         ddata.data = stripstr;
1726         ddata.len = data->length;
1727         sel->datacb(sel->udata, sel->widget, &ddata);
1728      }
1729    else
1730      elm_entry_entry_insert(sel->requestwidget, stripstr);
1731
1732    cnp_debug("String is %s (%d bytes)\n", stripstr, data->length);
1733    free(stripstr);
1734    return 0;
1735 }
1736
1737
1738 static Eina_Bool
1739 text_converter(char *target __UNUSED__, void *data, int size __UNUSED__, void **data_ret, int *size_ret, Ecore_X_Atom *ttype __UNUSED__, int *typesize __UNUSED__)
1740 {
1741    Cnp_Selection *sel;
1742
1743    cnp_debug("text converter\n");
1744    sel = selections + *((int *)data);
1745    if (!sel->active) return EINA_TRUE;
1746
1747    if ((sel->format & ELM_SEL_FORMAT_MARKUP) ||
1748        (sel->format & ELM_SEL_FORMAT_HTML))
1749      {
1750         *data_ret = remove_tags(sel->selbuf, size_ret);
1751      }
1752    else if (sel->format & ELM_SEL_FORMAT_TEXT)
1753      {
1754         *data_ret = strdup(sel->selbuf);
1755         *size_ret = strlen(sel->selbuf);
1756      }
1757    else if (sel->format & ELM_SEL_FORMAT_IMAGE)
1758      {
1759         cnp_debug("Image %s\n", evas_object_type_get(sel->widget));
1760         cnp_debug("Elm type: %s\n", elm_object_widget_type_get(sel->widget));
1761         evas_object_image_file_get(elm_photocam_internal_image_get(sel->widget), (const char **)data_ret, NULL);
1762         if (!*data_ret) *data_ret = strdup("No file");
1763         else *data_ret = strdup(*data_ret);
1764         *size_ret = strlen(*data_ret);
1765      }
1766    return EINA_TRUE;
1767 }
1768
1769 static Eina_Bool
1770 edje_converter(char *target __UNUSED__, void *data, int size __UNUSED__, void **data_ret, int *size_ret, Ecore_X_Atom *ttype __UNUSED__, int *typesize __UNUSED__)
1771 {
1772    Cnp_Selection *sel;
1773    sel = selections + *((int *)data);
1774 /*   if (data_ret) *data_ret = strdup(sel->selbuf);
1775    if (size_ret) *size_ret = strlen(sel->selbuf);*/
1776    char *edje = NULL;
1777
1778    if (data_ret && (sel->format & ELM_SEL_FORMAT_HTML))
1779      {
1780         Eina_List *nodeList = NULL;
1781         Eina_List *trail;
1782         PTagNode nodeData;
1783
1784         nodeData = _get_start_node(sel->selbuf);
1785
1786         while (nodeData)
1787           {
1788              nodeList = eina_list_append(nodeList, nodeData);
1789              nodeData = _get_next_node(nodeData);
1790           }
1791
1792         _link_match_tags(nodeList);
1793
1794         _set_HTML_tag_data(nodeList);
1795
1796 #ifdef DEBUGON
1797         _dumpNode(nodeList);
1798 #endif
1799         edje = _convert_to_edje(nodeList);
1800
1801         cnp_debug("convert edje: %s\n", edje);
1802
1803         EINA_LIST_FOREACH(nodeList, trail, nodeData)
1804            _delete_node(nodeData);
1805         eina_list_free(nodeList);
1806
1807      }
1808    if (data_ret)
1809      {
1810         if (edje)
1811           *data_ret = edje;
1812         else
1813           *data_ret = strdup(sel->selbuf);
1814      }
1815    if (size_ret)
1816      {
1817         if (edje)
1818           *size_ret = strlen(edje);
1819         else
1820           *size_ret = strlen(sel->selbuf);
1821      }
1822
1823    return EINA_TRUE;
1824 }
1825
1826 static Eina_Bool
1827 html_converter(char *target __UNUSED__, void *data, int size __UNUSED__, void **data_ret, int *size_ret, Ecore_X_Atom *ttype __UNUSED__, int *typesize __UNUSED__)
1828 {
1829    Cnp_Selection *sel;
1830
1831    sel = selections + *(int *)data;
1832
1833    char *html = NULL;
1834    if (data_ret && (sel->format & ELM_SEL_FORMAT_MARKUP))
1835      {
1836         Eina_List *nodeList = NULL;
1837         Eina_List *trail;
1838         PTagNode nodeData;
1839
1840         nodeData = _get_start_node(sel->selbuf);
1841
1842         while (nodeData)
1843           {
1844              nodeList = eina_list_append(nodeList, nodeData);
1845              nodeData = _get_next_node(nodeData);
1846           }
1847
1848         _link_match_tags(nodeList);
1849
1850         _set_EFL_tag_data(nodeList);
1851
1852 #ifdef DEBUGON
1853         _dumpNode(nodeList);
1854 #endif
1855         html = _convert_to_html(nodeList);
1856
1857         cnp_debug("convert html: %s\n", html);
1858
1859         EINA_LIST_FOREACH(nodeList, trail, nodeData)
1860            _delete_node(nodeData);
1861         eina_list_free(nodeList);
1862      }
1863    if (data_ret)
1864      {
1865         if (html)
1866           *data_ret = html;
1867         else
1868           *data_ret = strdup(sel->selbuf);
1869      }
1870
1871    if (size_ret)
1872      {
1873         if (html)
1874           *size_ret = strlen(html);
1875         else
1876           *size_ret = strlen(sel->selbuf);
1877      }
1878
1879    return EINA_TRUE;
1880 }
1881
1882 static Eina_Bool
1883 uri_converter(char *target __UNUSED__, void *data, int size __UNUSED__, void **data_ret, int *size_ret, Ecore_X_Atom *ttype __UNUSED__, int *typesize __UNUSED__)
1884 {
1885    Cnp_Selection *sel;
1886    sel = selections + *((int *)data);
1887    cnp_debug("Uri converter\n");
1888    if (data_ret) *data_ret = strdup(sel->selbuf);
1889    if (size_ret) *size_ret = strlen(sel->selbuf);
1890    return EINA_TRUE;
1891 }
1892
1893 /*
1894  * Image paste provide
1895  */
1896
1897 /* FIXME: Should add provider for each pasted item: Use data to store it
1898  * much easier */
1899 static Evas_Object *
1900 image_provider(void *images __UNUSED__, Evas_Object *entry, const char *item)
1901 {
1902    Paste_Image *pi;
1903    Eina_List *l;
1904
1905    cnp_debug("image provider for %s called\n", item);
1906    EINA_LIST_FOREACH(pastedimages, l, pi)
1907      {
1908         cnp_debug("is it %s?\n",pi->tag);
1909         if (!strcmp(pi->tag, item))
1910           {
1911              /* Found it */
1912              Evas_Object *o;
1913              o = evas_object_image_filled_add(evas_object_evas_get(entry));
1914              /* FIXME: Handle eets */
1915              cnp_debug("file is %s (object is %p)\n", pi->file, o);
1916              evas_object_image_file_set(o, pi->file, NULL);
1917              evas_object_show(o);
1918              return o;
1919           }
1920      }
1921    return NULL;
1922 }
1923
1924
1925 static Paste_Image *
1926 pasteimage_alloc(const char *file, int pathlen)
1927 {
1928    Paste_Image *pi;
1929    int len;
1930    char *buf, *filebuf;
1931    int prefixlen = strlen("file://");
1932
1933    pi = calloc(1, sizeof(Paste_Image));
1934    if (!pi) return NULL;
1935
1936    len = snprintf(NULL, 0, "pasteimage-%p", pi);
1937    len++;
1938    buf = malloc(len);
1939    if (!buf)
1940      {
1941         free(pi);
1942         return NULL;
1943      }
1944    snprintf(buf, len, "pasteimage-%p", pi);
1945    pi->tag = buf;
1946
1947    if (file)
1948      {
1949         if (strstr(file,"file://")) file += prefixlen;
1950         filebuf = alloca(pathlen + 1);
1951         strncpy(filebuf, file, pathlen);
1952         filebuf[pathlen] = 0;
1953         pi->file = strdup(filebuf);
1954      }
1955
1956    return pi;
1957 }
1958
1959 static void
1960 pasteimage_free(Paste_Image *pi)
1961 {
1962    if (!pi) return;
1963    if (pi->file) free((void*)pi->file);
1964    if (pi->tag) free((void*)pi->tag);
1965    free(pi);
1966 }
1967
1968 static Eina_Bool
1969 pasteimage_provider_set(Evas_Object *entry)
1970 {
1971    void *v;
1972    const char *type;
1973
1974    if (!entry) return EINA_FALSE;
1975    type = elm_widget_type_get(entry);
1976    cnp_debug("type is %s\n", type);
1977    if ((!type) || (strcmp(type, "entry"))) return EINA_FALSE;
1978
1979    v = evas_object_data_get(entry, PROVIDER_SET);
1980    if (!v)
1981      {
1982         evas_object_data_set(entry, PROVIDER_SET, pasteimage_provider_set);
1983         elm_entry_item_provider_append(entry, image_provider, NULL);
1984         evas_object_event_callback_add(entry, EVAS_CALLBACK_FREE,
1985                                        entry_deleted, NULL);
1986      }
1987    return EINA_TRUE;
1988 }
1989
1990
1991 static Eina_Bool
1992 pasteimage_append(Paste_Image *pi, Evas_Object *entry)
1993 {
1994    char *entrytag;
1995    int len;
1996    static const char *tagstring = "<item absize=240x180 href=file://%s></item>";
1997
1998    if (!pi) return EINA_FALSE;
1999    if (!entry) return EINA_FALSE;
2000
2001    pasteimage_provider_set(entry);
2002
2003    len = strlen(tagstring)+strlen(pi->file);
2004
2005    pastedimages = eina_list_append(pastedimages, pi);
2006    entrytag = alloca(len + 1);
2007    snprintf(entrytag, len + 1, tagstring, pi->file);
2008    elm_entry_entry_insert(entry, entrytag);
2009
2010    return EINA_TRUE;
2011 }
2012
2013 static void
2014 entry_deleted(void *images __UNUSED__, Evas *e __UNUSED__, Evas_Object *entry, void *unused __UNUSED__)
2015 {
2016    Paste_Image *pi;
2017    Eina_List *l,*next;
2018
2019    EINA_LIST_FOREACH_SAFE(pastedimages, l, next, pi)
2020      {
2021         if (pi->entry == entry)
2022           pastedimages = eina_list_remove_list(pastedimages, l);
2023      }
2024 }
2025
2026
2027 static char *
2028 remove_tags(const char *p, int *len)
2029 {
2030    char *q,*ret;
2031    int i;
2032    if (!p) return NULL;
2033
2034    q = malloc(strlen(p) + 1);
2035    if (!q) return NULL;
2036    ret = q;
2037
2038    while (*p)
2039      {
2040         if ((*p != '<') && (*p != '&')) *q++ = *p++;
2041         else if (*p == '<')
2042           {
2043              if ((p[1] == 'b') && (p[2] == 'r') &&
2044                  ((p[3] == ' ') || (p[3] == '/') || (p[3] == '>')))
2045                *q++ = '\n';
2046              while ((*p) && (*p != '>')) p++;
2047              p++;
2048           }
2049         else if (*p == '&')
2050           {
2051              p++;
2052              for (i = 0 ; i < N_ESCAPES ; i++)
2053                {
2054                   if (!strncmp(p,escapes[i].escape, strlen(escapes[i].escape)))
2055                     {
2056                        p += strlen(escapes[i].escape);
2057                        *q = escapes[i].value;
2058                        q++;
2059                        break;
2060                     }
2061                }
2062              if (i == N_ESCAPES) *q ++= '&';
2063           }
2064      }
2065    *q = 0;
2066    if (len) *len = q - ret;
2067    return ret;
2068 }
2069
2070 /* Mark up */
2071 static char *
2072 mark_up(const char *start, int inlen, int *lenp)
2073 {
2074    int l, i;
2075    const char *p;
2076    char *q, *ret;
2077    const char *endp = NULL;
2078
2079    if (!start) return NULL;
2080    if (inlen >= 0) endp = start + inlen;
2081    /* First pass: Count characters */
2082    for (l = 0, p = start; ((!endp) || (p < endp)) && (*p); p++)
2083      {
2084         for (i = 0 ; i < N_ESCAPES ; i ++)
2085           {
2086              if (*p == escapes[i].value)
2087                {
2088                   l += strlen(escapes[i].escape);
2089                   break;
2090                }
2091           }
2092         if (i == N_ESCAPES) l++;
2093      }
2094
2095    q = ret = malloc(l + 1);
2096
2097    /* Second pass: Change characters */
2098    for (p = start; *p; )
2099      {
2100         for (i = 0; i < N_ESCAPES; i++)
2101           {
2102              if (*p == escapes[i].value)
2103                {
2104                   strcpy(q, escapes[i].escape);
2105                   q += strlen(escapes[i].escape);
2106                   p ++;
2107                   break;
2108                }
2109           }
2110         if (i == N_ESCAPES) *q++ = *p++;
2111      }
2112    *q = 0;
2113
2114    if (lenp) *lenp = l;
2115    return ret;
2116 }
2117
2118
2119 static Eina_Bool
2120 _dnd_enter(void *data __UNUSED__, int etype __UNUSED__, void *ev)
2121 {
2122    Ecore_X_Event_Xdnd_Enter *enter = ev;
2123    int i;
2124
2125    /* Skip it */
2126    if ((!enter) || (!enter->num_types) || (!enter->types)) return EINA_TRUE;
2127
2128    cnp_debug("Types\n");
2129    savedtypes.ntypes = enter->num_types;
2130    if (savedtypes.types) free(savedtypes.types);
2131    savedtypes.types = malloc(sizeof(char *) * enter->num_types);
2132    if (!savedtypes.types) return EINA_FALSE;
2133
2134    for (i = 0; i < enter->num_types; i++)
2135      {
2136         savedtypes.types[i] = eina_stringshare_add(enter->types[i]);
2137         cnp_debug("Type is %s %p %p\n", enter->types[i],
2138                   savedtypes.types[i],text_uri);
2139         if (savedtypes.types[i] == text_uri)
2140           {
2141              /* Request it, so we know what it is */
2142              cnp_debug("Sending uri request\n");
2143              savedtypes.textreq = 1;
2144              savedtypes.pi = NULL; /* FIXME: Free? */
2145              ecore_x_selection_xdnd_request(enter->win, text_uri);
2146           }
2147      }
2148
2149    /* FIXME: Find an object and make it current */
2150    return EINA_TRUE;
2151 }
2152
2153 static Eina_Bool
2154 _dnd_drop(void *data __UNUSED__, int etype __UNUSED__, void *ev)
2155 {
2156    struct _Ecore_X_Event_Xdnd_Drop *drop;
2157    Dropable *dropable;
2158    Eina_List *l;
2159    Ecore_Evas *ee;
2160    Ecore_X_Window xwin;
2161    Elm_Selection_Data ddata;
2162    int x, y, w, h;
2163    int i, j;
2164
2165    drop = ev;
2166
2167    // check we still have something to drop
2168    if (!drops) return EINA_TRUE;
2169
2170    /* Find any widget in our window; then work out geometry rel to our window */
2171    for (l = drops; l; l = l->next)
2172      {
2173         dropable = l->data;
2174         xwin = (Ecore_X_Window)ecore_evas_window_get
2175            (ecore_evas_ecore_evas_get(evas_object_evas_get
2176                                       (dropable->obj)));
2177         if (xwin == drop->win) break;
2178      }
2179    /* didn't find a window */
2180    if (!l) return EINA_TRUE;
2181
2182    /* Calculate real (widget relative) position */
2183    // - window position
2184    // - widget position
2185    ee = ecore_evas_ecore_evas_get(evas_object_evas_get(dropable->obj));
2186    ecore_evas_geometry_get(ee, &x, &y, NULL, NULL);
2187    savedtypes.x = drop->position.x - x;
2188    savedtypes.y = drop->position.y - y;
2189
2190    cnp_debug("Drop position is %d,%d\n", savedtypes.x, savedtypes.y);
2191
2192    for (; l; l = l->next)
2193      {
2194         dropable = l->data;
2195         evas_object_geometry_get(dropable->obj, &x, &y, &w, &h);
2196         if ((savedtypes.x >= x) && (savedtypes.y >= y) &&
2197             (savedtypes.x < x + w) && (savedtypes.y < y + h))
2198           break; /* found! */
2199      }
2200
2201    if (!l) return EINA_TRUE; /* didn't find one */
2202
2203    evas_object_geometry_get(dropable->obj, &x, &y, NULL, NULL);
2204    savedtypes.x -= x;
2205    savedtypes.y -= y;
2206
2207    /* Find our type from the previous list */
2208    for (i = 0; i < CNP_N_ATOMS; i++)
2209      {
2210         for (j = 0; j < savedtypes.ntypes; j++)
2211           {
2212              if (!strcmp(savedtypes.types[j], atoms[i].name)) goto found;
2213           }
2214      }
2215
2216    cnp_debug("Didn't find a target\n");
2217    return EINA_TRUE;
2218
2219 found:
2220    cnp_debug("Found a target we'd like: %s\n", atoms[i].name);
2221    cnp_debug("0x%x\n",xwin);
2222
2223    if (i == CNP_ATOM_text_urilist)
2224      {
2225         cnp_debug("We found a URI... (%scached) %s\n",
2226                   savedtypes.pi ? "" : "not ",
2227                   savedtypes.pi->file);
2228         if (savedtypes.pi)
2229           {
2230              char *entrytag;
2231              static const char *tagstring = "<item absize=240x180 href="
2232                 "file://%s></item>";
2233              ddata.x = savedtypes.x;
2234              ddata.y = savedtypes.y;
2235
2236              /* If it's markup that also supports images */
2237              if ((dropable->types & ELM_SEL_FORMAT_MARKUP) &&
2238                  (dropable->types & ELM_SEL_FORMAT_IMAGE))
2239                {
2240                   int len;
2241                   ddata.format = ELM_SEL_FORMAT_MARKUP;
2242                   pasteimage_provider_set(dropable->obj);
2243
2244                   pastedimages = eina_list_append(pastedimages, savedtypes.pi);
2245                   len = strlen(tagstring) + strlen(savedtypes.pi->file);
2246                   entrytag = alloca(len + 1);
2247                   snprintf(entrytag, len + 1, tagstring, savedtypes.pi->file);
2248                   ddata.data = entrytag;
2249                   cnp_debug("Insert %s\n", (char *)ddata.data);
2250                   dropable->dropcb(dropable->cbdata, dropable->obj, &ddata);
2251                   ecore_x_dnd_send_finished();
2252                   return EINA_TRUE;
2253                }
2254              else if (dropable->types & ELM_SEL_FORMAT_IMAGE)
2255                {
2256                   cnp_debug("Doing image insert (%s)\n", savedtypes.pi->file);
2257                   ddata.format = ELM_SEL_FORMAT_IMAGE;
2258                   ddata.data = (char *)savedtypes.pi->file;
2259                   dropable->dropcb(dropable->cbdata, dropable->obj, &ddata);
2260                   ecore_x_dnd_send_finished();
2261
2262                   pasteimage_free(savedtypes.pi);
2263                   savedtypes.pi = NULL;
2264
2265                   return EINA_TRUE;
2266                }
2267              else
2268                {
2269                   cnp_debug("Item doesn't support images... passing\n");
2270                   pasteimage_free(savedtypes.pi);
2271                   return EINA_TRUE;
2272                }
2273           }
2274         else if (savedtypes.textreq)
2275           {
2276              /* Already asked: Pretend we asked now, and paste immediately when
2277               * it comes in */
2278              savedtypes.textreq = 0;
2279              ecore_x_dnd_send_finished();
2280              return EINA_TRUE;
2281           }
2282      }
2283
2284    cnp_debug("doing a request then\n");
2285    selections[ELM_SEL_XDND].requestwidget = dropable->obj;
2286    selections[ELM_SEL_XDND].requestformat = ELM_SEL_FORMAT_MARKUP;
2287    selections[ELM_SEL_XDND].active = EINA_TRUE;
2288
2289    ecore_x_selection_xdnd_request(xwin, atoms[i].name);
2290
2291    return EINA_TRUE;
2292 }
2293 static Eina_Bool
2294 _dnd_position(void *data __UNUSED__, int etype __UNUSED__, void *ev)
2295 {
2296    struct _Ecore_X_Event_Xdnd_Position *pos;
2297    Ecore_X_Rectangle rect;
2298
2299    pos = ev;
2300
2301    /* Need to send a status back */
2302    /* FIXME: Should check I can drop here */
2303    /* FIXME: Should highlight widget */
2304    rect.x = pos->position.x - 5;
2305    rect.y = pos->position.y - 5;
2306    rect.width = 10;
2307    rect.height = 10;
2308    ecore_x_dnd_send_status(EINA_TRUE, EINA_FALSE, rect, pos->action);
2309
2310    return EINA_TRUE;
2311 }
2312
2313 /**
2314  * When dragging this is callback response from the destination.
2315  * The important thing we care about: Can we drop; thus update cursor
2316  * appropriately.
2317  */
2318 static Eina_Bool
2319 _dnd_status(void *data __UNUSED__, int etype __UNUSED__, void *ev)
2320 {
2321    struct _Ecore_X_Event_Xdnd_Status *status = ev;
2322
2323    if (!status) return EINA_TRUE;
2324
2325    /* Only thing we care about: will accept */
2326    if (status->will_accept)
2327      {
2328         cnp_debug("Will accept\n");
2329      }
2330    else
2331      { /* Won't accept */
2332         cnp_debug("Won't accept accept\n");
2333      }
2334    return EINA_TRUE;
2335 }
2336
2337 /**
2338  * Add a widget as drop target.
2339  */
2340 Eina_Bool
2341 elm_drop_target_add(Evas_Object *obj, Elm_Sel_Type format, Elm_Drop_Cb dropcb, void *cbdata)
2342 {
2343    Dropable *drop;
2344    Ecore_X_Window xwin;
2345    Eina_List *item;
2346    int first;
2347
2348    if (!obj) return EINA_FALSE;
2349    if (!_elm_cnp_init_count) _elm_cnp_init();
2350
2351    /* Is this the first? */
2352    first = (!drops) ? 1 : 0;
2353
2354    EINA_LIST_FOREACH(drops, item, drop)
2355      {
2356         if (drop->obj == obj)
2357           {
2358              /* Update: Not a new one */
2359              drop->dropcb = dropcb;
2360              drop->cbdata = cbdata;
2361              drop->types = format;
2362              return EINA_TRUE;
2363           }
2364      }
2365
2366    /* Create new drop */
2367    drop = calloc(1, sizeof(Dropable));
2368    if (!drop) return EINA_FALSE;
2369    /* FIXME: Check for eina's deranged error method */
2370    drops = eina_list_append(drops, drop);
2371
2372    if (!drops/* || or other error */)
2373      {
2374         free(drop);
2375         return EINA_FALSE;
2376      }
2377    drop->dropcb = dropcb;
2378    drop->cbdata = cbdata;
2379    drop->types = format;
2380    drop->obj = obj;
2381
2382    evas_object_event_callback_add(obj, EVAS_CALLBACK_DEL,
2383                                   /* I love C and varargs */
2384                                   (Evas_Object_Event_Cb)elm_drop_target_del,
2385                                   obj);
2386    /* FIXME: Handle resizes */
2387
2388    /* If not the first: We're done */
2389    if (!first) return EINA_TRUE;
2390
2391    xwin = (Ecore_X_Window)ecore_evas_window_get
2392       (ecore_evas_ecore_evas_get(evas_object_evas_get(obj)));
2393
2394    ecore_x_dnd_aware_set(xwin, EINA_TRUE);
2395
2396    cnp_debug("Adding drop target calls\n");
2397    handler_enter = ecore_event_handler_add(ECORE_X_EVENT_XDND_ENTER,
2398                                            _dnd_enter, NULL);
2399    handler_pos = ecore_event_handler_add(ECORE_X_EVENT_XDND_POSITION,
2400                                          _dnd_position, NULL);
2401    handler_drop = ecore_event_handler_add(ECORE_X_EVENT_XDND_DROP,
2402                                           _dnd_drop, NULL);
2403
2404    return EINA_TRUE;
2405 }
2406
2407 Eina_Bool
2408 elm_drop_target_del(Evas_Object *obj)
2409 {
2410    Dropable *drop,*del;
2411    Eina_List *item;
2412    Ecore_X_Window xwin;
2413
2414    del = NULL;
2415    EINA_LIST_FOREACH(drops, item, drop)
2416      {
2417         if (drop->obj == obj)
2418           {
2419              drops = eina_list_remove_list(drops, item);
2420              del = drop;
2421              break;
2422           }
2423      }
2424    if (!del) return EINA_FALSE;
2425
2426    evas_object_event_callback_del(obj, EVAS_CALLBACK_FREE,
2427                                   (Evas_Object_Event_Cb)elm_drop_target_del);
2428    free(drop);
2429    /* If still drops there: All fine.. continue */
2430    if (drops) return EINA_TRUE;
2431
2432    cnp_debug("Disabling DND\n");
2433    xwin = (Ecore_X_Window)ecore_evas_window_get
2434       (ecore_evas_ecore_evas_get(evas_object_evas_get(obj)));
2435    ecore_x_dnd_aware_set(xwin, EINA_FALSE);
2436
2437    ecore_event_handler_del(handler_pos);
2438    ecore_event_handler_del(handler_drop);
2439    ecore_event_handler_del(handler_enter);
2440
2441    if (savedtypes.pi)
2442      {
2443         pasteimage_free(savedtypes.pi);
2444         savedtypes.pi = NULL;
2445      }
2446
2447    return EINA_TRUE;
2448 }
2449
2450
2451 static void
2452 _drag_mouse_up(void *un __UNUSED__, Evas *e __UNUSED__, Evas_Object *obj, void *data __UNUSED__)
2453 {
2454    evas_object_event_callback_del(obj, EVAS_CALLBACK_MOUSE_UP, _drag_mouse_up);
2455    ecore_x_dnd_drop();
2456    if (dragdonecb)
2457      {
2458         dragdonecb(dragdonecb,selections[ELM_SEL_XDND].widget);
2459         dragdonecb = NULL;
2460      }
2461    if (dragwin)
2462      {
2463         evas_object_del(dragwin);
2464         dragwin = NULL;
2465      }
2466 }
2467
2468 static void
2469 _drag_move(void *data __UNUSED__, Ecore_X_Xdnd_Position *pos)
2470 {
2471    evas_object_move(dragwin,
2472                     pos->position.x - _dragx,
2473                     pos->position.y - _dragy);
2474 }
2475
2476
2477 Eina_Bool
2478 elm_drag_start(Evas_Object *obj, Elm_Sel_Format format, const char *data, void (*dragdone) (void *data, Evas_Object *), void *donecbdata)
2479 {
2480    Ecore_X_Window xwin;
2481    Cnp_Selection *sel;
2482    Elm_Sel_Type xdnd = ELM_SEL_XDND;
2483    Ecore_Evas *ee;
2484    int x, y, x2, y2, x3, y3;
2485    Evas_Object *icon;
2486    int w, h;
2487
2488    if (!_elm_cnp_init_count) _elm_cnp_init();
2489
2490    xwin = elm_win_xwindow_get(obj);
2491
2492    cnp_debug("starting drag...\n");
2493
2494    ecore_x_dnd_type_set(xwin, "text/uri-list", 1);
2495    sel = selections + ELM_SEL_XDND;
2496    sel->active = 1;
2497    sel->widget = obj;
2498    sel->format = format;
2499    sel->selbuf = data ? strdup(data) : NULL;
2500    dragdonecb = dragdone;
2501    dragdonedata = donecbdata;
2502
2503    ecore_x_dnd_callback_pos_update_set(_drag_move, NULL);
2504    ecore_x_dnd_begin(xwin, (unsigned char *)&xdnd, sizeof(Elm_Sel_Type));
2505    evas_object_event_callback_add(obj, EVAS_CALLBACK_MOUSE_UP,
2506                                   _drag_mouse_up, NULL);
2507
2508    handler_status = ecore_event_handler_add(ECORE_X_EVENT_XDND_STATUS,
2509                                             _dnd_status, NULL);
2510
2511    dragwin = elm_win_add(NULL, "Elm Drag Object", ELM_WIN_UTILITY);
2512    elm_win_override_set(dragwin, 1);
2513
2514    /* FIXME: Images only */
2515    icon = elm_icon_add(dragwin);
2516    elm_icon_file_set(icon, data + 7, NULL); /* 7!? "file://" */
2517    elm_win_resize_object_add(dragwin,icon);
2518    evas_object_size_hint_weight_set(icon, EVAS_HINT_EXPAND, EVAS_HINT_EXPAND);
2519    evas_object_size_hint_align_set(icon, EVAS_HINT_FILL, EVAS_HINT_FILL);
2520
2521    /* Position subwindow appropriately */
2522    ee = ecore_evas_ecore_evas_get(evas_object_evas_get(obj));
2523    ecore_evas_geometry_get(ee, &x, &y, NULL, NULL);
2524    evas_object_geometry_get(obj, &x2, &y2, &w, &h);
2525    x += x2;
2526    y += y2;
2527    evas_object_move(dragwin, x, y);
2528    evas_object_resize(icon, w, h);
2529    evas_object_resize(dragwin, w, h);
2530
2531    evas_object_show(icon);
2532    evas_object_show(dragwin);
2533
2534    evas_pointer_canvas_xy_get(evas_object_evas_get(obj), &x3, &y3);
2535    _dragx = x3 - x2;
2536    _dragy = y3 - y2;
2537
2538    return EINA_TRUE;
2539 }
2540
2541 static Tmp_Info *
2542 elm_cnp_tempfile_create(int size)
2543 {
2544    Tmp_Info *info;
2545    const char *tmppath;
2546    int len;
2547
2548    info = malloc(sizeof(Tmp_Info));
2549    if (!info) return NULL;
2550
2551    tmppath = getenv("TMP");
2552    if (!tmppath) tmppath = P_tmpdir;
2553    if (!tmppath) tmppath = "/tmp";
2554    len = snprintf(NULL, 0, "%s/%sXXXXXX", tmppath, "elmcnpitem-");
2555    if (len < 0)
2556      {
2557         free(info);
2558         return NULL;
2559      }
2560    len++;
2561    info->filename = malloc(len);
2562    if (!info->filename)
2563      {
2564         free(info);
2565         return NULL;
2566      }
2567    snprintf(info->filename,len,"%s/%sXXXXXX", tmppath, "elmcnpitem-");
2568
2569    info->fd = mkstemp(info->filename);
2570
2571 # ifdef __linux__
2572      {
2573         char *tmp;
2574         /* And before someone says anything see POSIX 1003.1-2008 page 400 */
2575         long pid;
2576
2577         pid = (long)getpid();
2578         /* Use pid instead of /proc/self: That way if can be passed around */
2579         len = snprintf(NULL,0,"/proc/%li/fd/%i", pid, info->fd);
2580         len++;
2581         tmp = malloc(len);
2582         if (tmp)
2583           {
2584              snprintf(tmp,len, "/proc/%li/fd/%i", pid, info->fd);
2585              unlink(info->filename);
2586              free(info->filename);
2587              info->filename = tmp;
2588           }
2589      }
2590 # endif
2591
2592    cnp_debug("filename is %s\n", info->filename);
2593    if (size < 1)
2594      {
2595         /* Set map to NULL and return */
2596         info->map = NULL;
2597         info->len = 0;
2598         return info;
2599      }
2600
2601    /* Map it in */
2602    if (ftruncate(info->fd, size))
2603      {
2604         perror("ftruncate");
2605         info->map = NULL;
2606         info->len = 0;
2607         return info;
2608      }
2609
2610    info->map = mmap(NULL, size, PROT_READ|PROT_WRITE, MAP_SHARED, info->fd, 0);
2611    if (info->map == MAP_FAILED)
2612      {
2613         perror("mmap");
2614         info->map = NULL;
2615         info->len = 0;
2616      }
2617
2618    return info;
2619 }
2620
2621
2622 static int
2623 tmpinfo_free(Tmp_Info *info)
2624 {
2625    if (!info) return 0;
2626    free(info->filename);
2627    free(info);
2628    return 0;
2629 }
2630
2631 #else
2632 /* Stubs for windows */
2633 Eina_Bool
2634 elm_drag_start(Evas_Object *o, Elm_Sel_Format f, const char *d, void (*donecb)(void *, Evas_Object *),void *cbdata)
2635 {
2636    return EINA_FALSE;
2637 }
2638
2639 Eina_Bool
2640 elm_drop_target_add(Evas_Object *obj, Elm_Sel_Type format, Elm_Drop_Cb dropcb, void *cbdata)
2641 {
2642    return EINA_FALSE;
2643 }
2644
2645 Eina_Bool
2646 elm_drop_target_del(Evas_Object *o)
2647 {
2648    return EINA_TRUE;
2649 }
2650 #endif
2651
2652 /* vim:set ts=8 sw=3 sts=3 expandtab cino=>5n-2f0^-2{2(0W1st0 :*/