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