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