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