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