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