fix for toggle drag not working in popups (move layers for eg)
[blender-staging.git] / source / blender / editors / interface / interface_handlers.c
1 /*
2  * ***** BEGIN GPL LICENSE BLOCK *****
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version. 
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  *
18  * The Original Code is Copyright (C) 2008 Blender Foundation.
19  * All rights reserved.
20  * 
21  * Contributor(s): Blender Foundation
22  *
23  * ***** END GPL LICENSE BLOCK *****
24  */
25
26 /** \file blender/editors/interface/interface_handlers.c
27  *  \ingroup edinterface
28  */
29
30
31 #include <float.h>
32 #include <limits.h>
33 #include <math.h>
34 #include <stdlib.h>
35 #include <string.h>
36 #include <ctype.h>
37 #include <assert.h>
38
39 #include "MEM_guardedalloc.h"
40
41 #include "DNA_sensor_types.h"
42 #include "DNA_controller_types.h"
43 #include "DNA_actuator_types.h"
44
45 #include "DNA_object_types.h"
46 #include "DNA_scene_types.h"
47 #include "DNA_screen_types.h"
48
49 #include "BLI_math.h"
50 #include "BLI_blenlib.h"
51 #include "BLI_utildefines.h"
52 #include "BLI_string_cursor_utf8.h"
53
54 #include "BLF_translation.h"
55
56 #include "PIL_time.h"
57
58 #include "BKE_blender.h"
59 #include "BKE_colortools.h"
60 #include "BKE_context.h"
61 #include "BKE_idprop.h"
62 #include "BKE_report.h"
63 #include "BKE_texture.h"
64 #include "BKE_tracking.h"
65 #include "BKE_unit.h"
66 #include "BKE_paint.h"
67
68 #include "ED_screen.h"
69 #include "ED_util.h"
70 #include "ED_keyframing.h"
71
72 #include "UI_interface.h"
73
74 #include "BLF_api.h"
75
76 #include "interface_intern.h"
77
78 #include "RNA_access.h"
79
80 #include "WM_api.h"
81 #include "WM_types.h"
82
83 /* place the mouse at the scaled down location when un-grabbing */
84 #define USE_CONT_MOUSE_CORRECT
85 /* support dragging toggle buttons */
86 #define USE_DRAG_TOGGLE
87
88 /* so we can avoid very small mouse-moves from jumping away from keyboard navigation [#34936] */
89 #define USE_KEYNAV_LIMIT
90
91 /* proto */
92 static void ui_add_smart_controller(bContext *C, uiBut *from, uiBut *to);
93 static void ui_add_link(bContext *C, uiBut *from, uiBut *to);
94 static int ui_do_but_EXIT(bContext *C, uiBut *but, struct uiHandleButtonData *data, const wmEvent *event);
95
96 #ifdef USE_KEYNAV_LIMIT
97 static void ui_mouse_motion_keynav_init(struct uiKeyNavLock *keynav, const wmEvent *event);
98 static bool ui_mouse_motion_keynav_test(struct uiKeyNavLock *keynav, const wmEvent *event);
99 #endif
100
101 /***************** structs and defines ****************/
102
103 #define BUTTON_TOOLTIP_DELAY        0.500
104 #define BUTTON_FLASH_DELAY          0.020
105 #define MENU_SCROLL_INTERVAL        0.1
106 #define BUTTON_AUTO_OPEN_THRESH     0.3
107 #define BUTTON_MOUSE_TOWARDS_THRESH 1.0
108 /* pixels to move the cursor to get out of keyboard navigation */
109 #define BUTTON_KEYNAV_PX_LIMIT      4
110
111 typedef enum uiButtonActivateType {
112         BUTTON_ACTIVATE_OVER,
113         BUTTON_ACTIVATE,
114         BUTTON_ACTIVATE_APPLY,
115         BUTTON_ACTIVATE_TEXT_EDITING,
116         BUTTON_ACTIVATE_OPEN
117 } uiButtonActivateType;
118
119 typedef enum uiHandleButtonState {
120         BUTTON_STATE_INIT,
121         BUTTON_STATE_HIGHLIGHT,
122         BUTTON_STATE_WAIT_FLASH,
123         BUTTON_STATE_WAIT_RELEASE,
124         BUTTON_STATE_WAIT_KEY_EVENT,
125         BUTTON_STATE_NUM_EDITING,
126         BUTTON_STATE_TEXT_EDITING,
127         BUTTON_STATE_TEXT_SELECTING,
128         BUTTON_STATE_MENU_OPEN,
129         BUTTON_STATE_WAIT_DRAG,
130         BUTTON_STATE_EXIT
131 } uiHandleButtonState;
132
133 typedef struct uiHandleButtonData {
134         wmWindowManager *wm;
135         wmWindow *window;
136         ARegion *region;
137
138         bool interactive;
139
140         /* overall state */
141         uiHandleButtonState state;
142         int retval;
143         /* booleans (could be made into flags) */
144         bool cancel, escapecancel;
145         bool applied, applied_interactive;
146         wmTimer *flashtimer;
147
148         /* edited value */
149         char *str, *origstr;
150         double value, origvalue, startvalue;
151         float vec[3], origvec[3];
152         int togdual, togonly;
153         ColorBand *coba;
154
155         /* tooltip */
156         ARegion *tooltip;
157         wmTimer *tooltiptimer;
158         
159         /* auto open */
160         bool used_mouse;
161         wmTimer *autoopentimer;
162
163         /* text selection/editing */
164         int maxlen, selextend, selstartx;
165
166         /* number editing / dragging */
167         /* coords are Window/uiBlock relative (depends on the button) */
168         int draglastx, draglasty;
169         int dragstartx, dragstarty;
170         bool dragchange, draglock;
171         int dragsel;
172         float dragf, dragfstart;
173         CBData *dragcbd;
174
175 #ifdef USE_CONT_MOUSE_CORRECT
176         /* when ungrabbing buttons which are #ui_is_a_warp_but(), we may want to position them
177          * FLT_MAX signifies do-nothing, use #ui_block_to_window_fl() to get this into a usable space  */
178         float ungrab_mval[2];
179 #endif
180
181         /* menu open (watch uiFreeActiveButtons) */
182         uiPopupBlockHandle *menu;
183         int menuretval;
184         
185         /* search box (watch uiFreeActiveButtons) */
186         ARegion *searchbox;
187 #ifdef USE_KEYNAV_LIMIT
188         struct uiKeyNavLock searchbox_keynav_state;
189 #endif
190
191         /* post activate */
192         uiButtonActivateType posttype;
193         uiBut *postbut;
194 } uiHandleButtonData;
195
196 typedef struct uiAfterFunc {
197         struct uiAfterFunc *next, *prev;
198
199         uiButHandleFunc func;
200         void *func_arg1;
201         void *func_arg2;
202         
203         uiButHandleNFunc funcN;
204         void *func_argN;
205
206         uiButHandleRenameFunc rename_func;
207         void *rename_arg1;
208         void *rename_orig;
209         
210         uiBlockHandleFunc handle_func;
211         void *handle_func_arg;
212         int retval;
213
214         uiMenuHandleFunc butm_func;
215         void *butm_func_arg;
216         int a2;
217
218         wmOperatorType *optype;
219         int opcontext;
220         PointerRNA *opptr;
221
222         PointerRNA rnapoin;
223         PropertyRNA *rnaprop;
224
225         bContextStore *context;
226
227         char undostr[BKE_UNDO_STR_MAX];
228
229         int autokey;
230 } uiAfterFunc;
231
232 static bool ui_but_contains_pt(uiBut *but, int mx, int my);
233 static bool ui_mouse_inside_button(ARegion *ar, uiBut *but, int x, int y);
234 static void button_activate_state(bContext *C, uiBut *but, uiHandleButtonState state);
235 static int ui_handler_region_menu(bContext *C, const wmEvent *event, void *userdata);
236 static void ui_handle_button_activate(bContext *C, ARegion *ar, uiBut *but, uiButtonActivateType type);
237 static void button_timers_tooltip_remove(bContext *C, uiBut *but);
238
239 /* ******************** menu navigation helpers ************** */
240
241 /* assumes event type is MOUSEPAN */
242 void ui_pan_to_scroll(const wmEvent *event, int *type, int *val)
243 {
244         static int lastdy = 0;
245         int dy = event->prevy - event->y;
246
247         /* This event should be originally from event->type,
248          * converting wrong event into wheel is bad, see [#33803] */
249         BLI_assert(*type == MOUSEPAN);
250
251         /* sign differs, reset */
252         if ((dy > 0 && lastdy < 0) || (dy < 0 && lastdy > 0)) {
253                 lastdy = dy;
254         }
255         else {
256                 lastdy += dy;
257                 
258                 if (ABS(lastdy) > (int)UI_UNIT_Y) {
259                         if (U.uiflag2 & USER_TRACKPAD_NATURAL)
260                                 dy = -dy;
261                         
262                         *val = KM_PRESS;
263                         
264                         if (dy > 0)
265                                 *type = WHEELUPMOUSE;
266                         else
267                                 *type = WHEELDOWNMOUSE;
268                         
269                         lastdy = 0;
270                 }
271         }
272 }
273
274 static bool ui_but_editable(uiBut *but)
275 {
276         return ELEM5(but->type, LABEL, SEPR, ROUNDBOX, LISTBOX, PROGRESSBAR);
277 }
278
279 static uiBut *ui_but_prev(uiBut *but)
280 {
281         while (but->prev) {
282                 but = but->prev;
283                 if (!ui_but_editable(but)) return but;
284         }
285         return NULL;
286 }
287
288 static uiBut *ui_but_next(uiBut *but)
289 {
290         while (but->next) {
291                 but = but->next;
292                 if (!ui_but_editable(but)) return but;
293         }
294         return NULL;
295 }
296
297 static uiBut *ui_but_first(uiBlock *block)
298 {
299         uiBut *but;
300         
301         but = block->buttons.first;
302         while (but) {
303                 if (!ui_but_editable(but)) return but;
304                 but = but->next;
305         }
306         return NULL;
307 }
308
309 static uiBut *ui_but_last(uiBlock *block)
310 {
311         uiBut *but;
312         
313         but = block->buttons.last;
314         while (but) {
315                 if (!ui_but_editable(but)) return but;
316                 but = but->prev;
317         }
318         return NULL;
319 }
320
321 static bool ui_is_a_warp_but(uiBut *but)
322 {
323         if (U.uiflag & USER_CONTINUOUS_MOUSE) {
324                 if (ELEM7(but->type, NUM, NUMSLI, NUMABS, HSVCIRCLE, TRACKPREVIEW, HSVCUBE, BUT_CURVE)) {
325                         return true;
326                 }
327         }
328
329         return false;
330 }
331
332 static float ui_mouse_scale_warp_factor(const short shift)
333 {
334         return shift ? 0.05f : 1.0f;
335 }
336
337 static void ui_mouse_scale_warp(uiHandleButtonData *data,
338                                 const float mx, const float my,
339                                 float *r_mx, float *r_my,
340                                 const short shift)
341 {
342         const float fac = ui_mouse_scale_warp_factor(shift);
343         
344         /* slow down the mouse, this is fairly picky */
345         *r_mx = (data->dragstartx * (1.0f - fac) + mx * fac);
346         *r_my = (data->dragstarty * (1.0f - fac) + my * fac);
347 }
348
349 /* file selectors are exempt from utf-8 checks */
350 bool ui_is_but_utf8(uiBut *but)
351 {
352         if (but->rnaprop) {
353                 const int subtype = RNA_property_subtype(but->rnaprop);
354                 return !(ELEM4(subtype, PROP_FILEPATH, PROP_DIRPATH, PROP_FILENAME, PROP_BYTESTRING));
355         }
356         else {
357                 return !(but->flag & UI_BUT_NO_UTF8);
358         }
359 }
360
361 /* ********************** button apply/revert ************************/
362
363 static ListBase UIAfterFuncs = {NULL, NULL};
364
365 static void ui_apply_but_func(bContext *C, uiBut *but)
366 {
367         uiAfterFunc *after;
368         uiBlock *block = but->block;
369
370         /* these functions are postponed and only executed after all other
371          * handling is done, i.e. menus are closed, in order to avoid conflicts
372          * with these functions removing the buttons we are working with */
373
374         if (but->func || but->funcN || block->handle_func || but->rename_func ||
375             (but->type == BUTM && block->butm_func) || but->optype || but->rnaprop)
376         {
377                 after = MEM_callocN(sizeof(uiAfterFunc), "uiAfterFunc");
378
379                 if (but->func && ELEM(but, but->func_arg1, but->func_arg2)) {
380                         /* exception, this will crash due to removed button otherwise */
381                         but->func(C, but->func_arg1, but->func_arg2);
382                 }
383                 else
384                         after->func = but->func;
385
386                 after->func_arg1 = but->func_arg1;
387                 after->func_arg2 = but->func_arg2;
388
389                 after->funcN = but->funcN;
390                 after->func_argN = MEM_dupallocN(but->func_argN);
391
392                 after->rename_func = but->rename_func;
393                 after->rename_arg1 = but->rename_arg1;
394                 after->rename_orig = but->rename_orig; /* needs free! */
395
396                 after->handle_func = block->handle_func;
397                 after->handle_func_arg = block->handle_func_arg;
398                 after->retval = but->retval;
399
400                 if (but->type == BUTM) {
401                         after->butm_func = block->butm_func;
402                         after->butm_func_arg = block->butm_func_arg;
403                         after->a2 = but->a2;
404                 }
405
406                 after->optype = but->optype;
407                 after->opcontext = but->opcontext;
408                 after->opptr = but->opptr;
409
410                 after->rnapoin = but->rnapoin;
411                 after->rnaprop = but->rnaprop;
412
413                 if (but->context)
414                         after->context = CTX_store_copy(but->context);
415
416                 but->optype = NULL;
417                 but->opcontext = 0;
418                 but->opptr = NULL;
419
420                 BLI_addtail(&UIAfterFuncs, after);
421         }
422 }
423
424 /* typically call ui_apply_undo(), ui_apply_autokey() */
425 static void ui_apply_undo(uiBut *but)
426 {
427         uiAfterFunc *after;
428
429         if (but->flag & UI_BUT_UNDO) {
430                 const char *str = NULL;
431
432                 /* define which string to use for undo */
433                 if (ELEM(but->type, LINK, INLINK)) str = "Add button link";
434                 else if (ELEM(but->type, MENU, ICONTEXTROW)) str = but->drawstr;
435                 else if (but->drawstr[0]) str = but->drawstr;
436                 else str = but->tip;
437
438                 /* fallback, else we don't get an undo! */
439                 if (str == NULL || str[0] == '\0') {
440                         str = "Unknown Action";
441                 }
442
443                 /* delayed, after all other funcs run, popups are closed, etc */
444                 after = MEM_callocN(sizeof(uiAfterFunc), "uiAfterFunc");
445                 BLI_strncpy(after->undostr, str, sizeof(after->undostr));
446                 BLI_addtail(&UIAfterFuncs, after);
447         }
448 }
449
450 static void ui_apply_autokey(bContext *C, uiBut *but)
451 {
452         Scene *scene = CTX_data_scene(C);
453
454         /* try autokey */
455         ui_but_anim_autokey(C, but, scene, scene->r.cfra);
456
457         /* make a little report about what we've done! */
458         if (but->rnaprop) {
459                 char *buf = WM_prop_pystring_assign(C, &but->rnapoin, but->rnaprop, but->rnaindex);
460                 if (buf) {
461                         BKE_report(CTX_wm_reports(C), RPT_PROPERTY, buf);
462                         MEM_freeN(buf);
463
464                         WM_event_add_notifier(C, NC_SPACE | ND_SPACE_INFO_REPORT, NULL);
465                 }
466         }
467 }
468
469 static void ui_apply_but_funcs_after(bContext *C)
470 {
471         uiAfterFunc *afterf, after;
472         PointerRNA opptr;
473         ListBase funcs;
474
475         /* copy to avoid recursive calls */
476         funcs = UIAfterFuncs;
477         UIAfterFuncs.first = UIAfterFuncs.last = NULL;
478
479         for (afterf = funcs.first; afterf; afterf = after.next) {
480                 after = *afterf; /* copy to avoid memleak on exit() */
481                 BLI_freelinkN(&funcs, afterf);
482
483                 if (after.context)
484                         CTX_store_set(C, after.context);
485
486                 if (after.opptr) {
487                         /* free in advance to avoid leak on exit */
488                         opptr = *after.opptr,
489                         MEM_freeN(after.opptr);
490                 }
491
492                 if (after.optype)
493                         WM_operator_name_call(C, after.optype->idname, after.opcontext, (after.opptr) ? &opptr : NULL);
494
495                 if (after.opptr)
496                         WM_operator_properties_free(&opptr);
497
498                 if (after.rnapoin.data)
499                         RNA_property_update(C, &after.rnapoin, after.rnaprop);
500
501                 if (after.context) {
502                         CTX_store_set(C, NULL);
503                         CTX_store_free(after.context);
504                 }
505
506                 if (after.func)
507                         after.func(C, after.func_arg1, after.func_arg2);
508                 if (after.funcN)
509                         after.funcN(C, after.func_argN, after.func_arg2);
510                 if (after.func_argN)
511                         MEM_freeN(after.func_argN);
512                 
513                 if (after.handle_func)
514                         after.handle_func(C, after.handle_func_arg, after.retval);
515                 if (after.butm_func)
516                         after.butm_func(C, after.butm_func_arg, after.a2);
517                 
518                 if (after.rename_func)
519                         after.rename_func(C, after.rename_arg1, after.rename_orig);
520                 if (after.rename_orig)
521                         MEM_freeN(after.rename_orig);
522                 
523                 if (after.undostr[0])
524                         ED_undo_push(C, after.undostr);
525         }
526 }
527
528 static void ui_apply_but_BUT(bContext *C, uiBut *but, uiHandleButtonData *data)
529 {
530         ui_apply_but_func(C, but);
531
532         data->retval = but->retval;
533         data->applied = true;
534 }
535
536 static void ui_apply_but_BUTM(bContext *C, uiBut *but, uiHandleButtonData *data)
537 {
538         ui_set_but_val(but, but->hardmin);
539         ui_apply_but_func(C, but);
540
541         data->retval = but->retval;
542         data->applied = true;
543 }
544
545 static void ui_apply_but_BLOCK(bContext *C, uiBut *but, uiHandleButtonData *data)
546 {
547         if (ELEM3(but->type, MENU, ICONROW, ICONTEXTROW))
548                 ui_set_but_val(but, data->value);
549
550         ui_check_but(but);
551         ui_apply_but_func(C, but);
552         data->retval = but->retval;
553         data->applied = true;
554 }
555
556 static void ui_apply_but_TOG(bContext *C, uiBut *but, uiHandleButtonData *data)
557 {
558         double value;
559         int w, lvalue, push;
560         
561         /* local hack... */
562         if (but->type == BUT_TOGDUAL && data->togdual) {
563                 if (but->pointype == UI_BUT_POIN_SHORT) {
564                         but->poin += 2;
565                 }
566                 else if (but->pointype == UI_BUT_POIN_INT) {
567                         but->poin += 4;
568                 }
569         }
570         
571         value = ui_get_but_val(but);
572         lvalue = (int)value;
573         
574         if (but->bit) {
575                 w = UI_BITBUT_TEST(lvalue, but->bitnr);
576                 if (w) lvalue = UI_BITBUT_CLR(lvalue, but->bitnr);
577                 else   lvalue = UI_BITBUT_SET(lvalue, but->bitnr);
578                 
579                 if (but->type == TOGR) {
580                         if (!data->togonly) {
581                                 lvalue = 1 << (but->bitnr);
582         
583                                 ui_set_but_val(but, (double)lvalue);
584                         }
585                         else {
586                                 if (lvalue == 0) lvalue = 1 << (but->bitnr);
587                         }
588                 }
589                 
590                 ui_set_but_val(but, (double)lvalue);
591                 if (but->type == ICONTOG || but->type == ICONTOGN) ui_check_but(but);
592         }
593         else {
594                 
595                 if (value == 0.0) push = 1;
596                 else push = 0;
597                 
598                 if (ELEM3(but->type, TOGN, ICONTOGN, OPTIONN)) push = !push;
599                 ui_set_but_val(but, (double)push);
600                 if (but->type == ICONTOG || but->type == ICONTOGN) ui_check_but(but);
601         }
602         
603         /* end local hack... */
604         if (but->type == BUT_TOGDUAL && data->togdual) {
605                 if (but->pointype == UI_BUT_POIN_SHORT) {
606                         but->poin -= 2;
607                 }
608                 else if (but->pointype == UI_BUT_POIN_INT) {
609                         but->poin -= 4;
610                 }
611         }
612         
613         ui_apply_but_func(C, but);
614
615         data->retval = but->retval;
616         data->applied = true;
617 }
618
619 static void ui_apply_but_ROW(bContext *C, uiBlock *block, uiBut *but, uiHandleButtonData *data)
620 {
621         uiBut *bt;
622         
623         ui_set_but_val(but, but->hardmax);
624         
625         /* states of other row buttons */
626         for (bt = block->buttons.first; bt; bt = bt->next)
627                 if (bt != but && bt->poin == but->poin && ELEM(bt->type, ROW, LISTROW))
628                         ui_check_but(bt);
629         
630         ui_apply_but_func(C, but);
631
632         data->retval = but->retval;
633         data->applied = true;
634 }
635
636 static void ui_apply_but_TEX(bContext *C, uiBut *but, uiHandleButtonData *data)
637 {
638         if (!data->str)
639                 return;
640
641         ui_set_but_string(C, but, data->str);
642         ui_check_but(but);
643
644         /* give butfunc the original text too */
645         /* feature used for bone renaming, channels, etc */
646         /* afterfunc frees origstr */
647         but->rename_orig = data->origstr;
648         data->origstr = NULL;
649         ui_apply_but_func(C, but);
650
651         data->retval = but->retval;
652         data->applied = true;
653 }
654
655 static void ui_apply_but_NUM(bContext *C, uiBut *but, uiHandleButtonData *data)
656 {
657         if (data->str) {
658                 if (ui_set_but_string(C, but, data->str)) {
659                         data->value = ui_get_but_val(but);
660                 }
661                 else {
662                         data->cancel = true;
663                         return;
664                 }
665         }
666         else
667                 ui_set_but_val(but, data->value);
668
669         ui_check_but(but);
670         ui_apply_but_func(C, but);
671
672         data->retval = but->retval;
673         data->applied = true;
674 }
675
676 static void ui_apply_but_TOG3(bContext *C, uiBut *but, uiHandleButtonData *data)
677
678         if (but->pointype == UI_BUT_POIN_SHORT) {
679                 short *sp = (short *)but->poin;
680                 
681                 if (UI_BITBUT_TEST(sp[1], but->bitnr)) {
682                         sp[1] = UI_BITBUT_CLR(sp[1], but->bitnr);
683                         sp[0] = UI_BITBUT_CLR(sp[0], but->bitnr);
684                 }
685                 else if (UI_BITBUT_TEST(sp[0], but->bitnr)) {
686                         sp[1] = UI_BITBUT_SET(sp[1], but->bitnr);
687                 }
688                 else {
689                         sp[0] = UI_BITBUT_SET(sp[0], but->bitnr);
690                 }
691         }
692         else {
693                 if (UI_BITBUT_TEST(*(but->poin + 2), but->bitnr)) {
694                         *(but->poin + 2) = UI_BITBUT_CLR(*(but->poin + 2), but->bitnr);
695                         *(but->poin)     = UI_BITBUT_CLR(*(but->poin),     but->bitnr);
696                 }
697                 else if (UI_BITBUT_TEST(*(but->poin), but->bitnr)) {
698                         *(but->poin + 2) = UI_BITBUT_SET(*(but->poin + 2), but->bitnr);
699                 }
700                 else {
701                         *(but->poin) = UI_BITBUT_SET(*(but->poin), but->bitnr);
702                 }
703         }
704         
705         ui_check_but(but);
706         ui_apply_but_func(C, but);
707         data->retval = but->retval;
708         data->applied = true;
709 }
710
711 static void ui_apply_but_VEC(bContext *C, uiBut *but, uiHandleButtonData *data)
712 {
713         ui_set_but_vectorf(but, data->vec);
714         ui_check_but(but);
715         ui_apply_but_func(C, but);
716
717         data->retval = but->retval;
718         data->applied = true;
719 }
720
721 static void ui_apply_but_COLORBAND(bContext *C, uiBut *but, uiHandleButtonData *data)
722 {
723         ui_apply_but_func(C, but);
724         data->retval = but->retval;
725         data->applied = true;
726 }
727
728 static void ui_apply_but_CURVE(bContext *C, uiBut *but, uiHandleButtonData *data)
729 {
730         ui_apply_but_func(C, but);
731         data->retval = but->retval;
732         data->applied = true;
733 }
734
735 static void ui_apply_but_IDPOIN(bContext *C, uiBut *but, uiHandleButtonData *data)
736 {
737         ui_set_but_string(C, but, data->str);
738         ui_check_but(but);
739         ui_apply_but_func(C, but);
740         data->retval = but->retval;
741         data->applied = true;
742 }
743
744 #ifdef WITH_INTERNATIONAL
745 static void ui_apply_but_CHARTAB(bContext *C, uiBut *but, uiHandleButtonData *data)
746 {
747         ui_apply_but_func(C, but);
748         data->retval = but->retval;
749         data->applied = true;
750 }
751 #endif
752
753 /* ****************** drag drop code *********************** */
754
755 #ifdef USE_DRAG_TOGGLE
756
757 typedef struct uiDragToggleHandle {
758         /* init */
759         bool is_set;
760         float but_cent_start[2];
761         eButType but_type_start;
762
763         bool xy_lock[2];
764         int  xy_last[2];
765 } uiDragToggleHandle;
766
767 static bool ui_drag_toggle_set_xy_xy(bContext *C, ARegion *ar, const bool is_set, const eButType but_type_start,
768                                      const int xy_src[2], const int xy_dst[2])
769 {
770         /* popups such as layers won't re-evaluate on redraw */
771         const bool do_check = (ar->regiontype == RGN_TYPE_TEMPORARY);
772         bool change = false;
773         uiBlock *block;
774
775         for (block = ar->uiblocks.first; block; block = block->next) {
776                 uiBut *but;
777
778                 float xy_a_block[2] = {UNPACK2(xy_src)};
779                 float xy_b_block[2] = {UNPACK2(xy_dst)};
780
781                 ui_window_to_block_fl(ar, block, &xy_a_block[0], &xy_a_block[1]);
782                 ui_window_to_block_fl(ar, block, &xy_b_block[0], &xy_b_block[1]);
783
784                 for (but = block->buttons.first; but; but = but->next) {
785                         if (ui_is_but_interactive(but)) {
786                                 if (BLI_rctf_isect_segment(&but->rect, xy_a_block, xy_b_block)) {
787
788                                         /* execute the button */
789                                         if (ui_is_but_bool(but) && but->type == but_type_start) {
790                                                 /* is it pressed? */
791                                                 bool is_set_but = ui_is_but_push(but);
792                                                 BLI_assert(ui_is_but_bool(but) == true);
793                                                 if (is_set_but != is_set) {
794                                                         uiButExecute(C, but);
795                                                         if (do_check) {
796                                                                 ui_check_but(but);
797                                                         }
798                                                         change = true;
799                                                 }
800                                         }
801                                         /* done */
802
803                                 }
804                         }
805                 }
806         }
807
808         return change;
809 }
810
811 static void ui_drag_toggle_set(bContext *C, uiDragToggleHandle *drag_info, const int xy_input[2])
812 {
813         ARegion *ar = CTX_wm_region(C);
814         bool do_draw = false;
815         int xy[2];
816
817         /**
818          * Initialize Locking:
819          *
820          * Check if we need to initialize the lock axis by finding if the first
821          * button we mouse over is X or Y aligned, then lock the mouse to that axis after.
822          */
823         if (drag_info->xy_lock[0] == false && drag_info->xy_lock[1] == false) {
824                 /* first store the buttons original coords */
825                 uiBut *but = ui_but_find_mouse_over(ar, xy_input[0], xy_input[1]);
826                 if (but) {
827                         const float but_cent_new[2] = {BLI_rctf_cent_x(&but->rect),
828                                                        BLI_rctf_cent_y(&but->rect)};
829
830                         /* check if this is a different button, chances are high the button wont move about :) */
831                         if (len_manhattan_v2v2(drag_info->but_cent_start, but_cent_new) > 1.0f) {
832                                 if (fabsf(drag_info->but_cent_start[0] - but_cent_new[0]) <
833                                     fabsf(drag_info->but_cent_start[1] - but_cent_new[1]))
834                                 {
835                                         drag_info->xy_lock[0] = true;
836                                 }
837                                 else {
838                                         drag_info->xy_lock[1] = true;
839                                 }
840                         }
841                 }
842         }
843         /* done with axis locking */
844
845
846         xy[0] = (drag_info->xy_lock[0] == false) ? xy_input[0] : drag_info->xy_last[0];
847         xy[1] = (drag_info->xy_lock[1] == false) ? xy_input[1] : drag_info->xy_last[1];
848
849
850         /* touch all buttons between last mouse coord and this one */
851         do_draw = ui_drag_toggle_set_xy_xy(C, ar, drag_info->is_set, drag_info->but_type_start, drag_info->xy_last, xy);
852
853         if (do_draw) {
854                 ED_region_tag_redraw(ar);
855         }
856
857         copy_v2_v2_int(drag_info->xy_last, xy);
858 }
859
860 static void ui_handler_region_drag_toggle_remove(bContext *UNUSED(C), void *userdata)
861 {
862         uiDragToggleHandle *drag_info = userdata;
863         MEM_freeN(drag_info);
864 }
865
866 static int ui_handler_region_drag_toggle(bContext *C, const wmEvent *event, void *userdata)
867 {
868         uiDragToggleHandle *drag_info = userdata;
869         bool done = false;
870
871         switch (event->type) {
872                 case LEFTMOUSE:
873                 {
874                         if (event->val != KM_PRESS) {
875                                 done = true;
876                         }
877                         break;
878                 }
879                 case MOUSEMOVE:
880                 {
881                         ui_drag_toggle_set(C, drag_info, &event->x);
882                         break;
883                 }
884         }
885
886         if (done) {
887                 wmWindow *win = CTX_wm_window(C);
888                 WM_event_remove_ui_handler(&win->modalhandlers,
889                                            ui_handler_region_drag_toggle,
890                                            ui_handler_region_drag_toggle_remove,
891                                            drag_info, false);
892                 ui_handler_region_drag_toggle_remove(C, drag_info);
893
894                 WM_event_add_mousemove(C);
895                 return WM_UI_HANDLER_BREAK;
896         }
897         else {
898                 return WM_UI_HANDLER_CONTINUE;
899         }
900 }
901
902 #endif  /* USE_DRAG_TOGGLE */
903
904
905 static bool ui_but_mouse_inside_icon(uiBut *but, ARegion *ar, const wmEvent *event)
906 {
907         rcti rect;
908         int x = event->x, y = event->y;
909         
910         ui_window_to_block(ar, but->block, &x, &y);
911         
912         BLI_rcti_rctf_copy(&rect, &but->rect);
913         
914         if (but->imb) {
915                 /* use button size itself */
916         }
917         else if (but->flag & UI_ICON_LEFT) {
918                 rect.xmax = rect.xmin + (BLI_rcti_size_y(&rect));
919         }
920         else {
921                 int delta = BLI_rcti_size_x(&rect) - BLI_rcti_size_y(&rect);
922                 rect.xmin += delta / 2;
923                 rect.xmax -= delta / 2;
924         }
925         
926         return BLI_rcti_isect_pt(&rect, x, y);
927 }
928
929 static bool ui_but_start_drag(bContext *C, uiBut *but, uiHandleButtonData *data, const wmEvent *event)
930 {
931         /* prevent other WM gestures to start while we try to drag */
932         WM_gestures_remove(C);
933
934         if (ABS(data->dragstartx - event->x) + ABS(data->dragstarty - event->y) > U.dragthreshold) {
935
936                 button_activate_state(C, but, BUTTON_STATE_EXIT);
937                 data->cancel = true;
938 #ifdef USE_DRAG_TOGGLE
939                 if (ui_is_but_bool(but)) {
940                         uiDragToggleHandle *drag_info = MEM_callocN(sizeof(*drag_info), __func__);
941                         ARegion *ar_prev;
942
943                         drag_info->is_set = ui_is_but_push(but);
944                         drag_info->but_cent_start[0] = BLI_rctf_cent_x(&but->rect);
945                         drag_info->but_cent_start[1] = BLI_rctf_cent_y(&but->rect);
946                         drag_info->but_type_start = but->type;
947                         copy_v2_v2_int(drag_info->xy_last, &event->x);
948
949                         /* needed for toggle drag on popups */
950                         ar_prev = CTX_wm_region(C);
951                         CTX_wm_region_set(C, data->region);
952
953                         WM_event_add_ui_handler(C, &data->window->modalhandlers,
954                                                 ui_handler_region_drag_toggle,
955                                                 ui_handler_region_drag_toggle_remove,
956                                                 drag_info);
957
958                         CTX_wm_region_set(C, ar_prev);
959                 }
960                 else
961 #endif
962                 {
963                         wmDrag *drag;
964
965                         drag = WM_event_start_drag(C, but->icon, but->dragtype, but->dragpoin, ui_get_but_val(but));
966                         if (but->imb)
967                                 WM_event_drag_image(drag, but->imb, but->imb_scale, BLI_rctf_size_x(&but->rect), BLI_rctf_size_y(&but->rect));
968                 }
969                 return true;
970         }
971         
972         return false;
973 }
974
975 /* ********************** linklines *********************** */
976
977 static void ui_delete_active_linkline(uiBlock *block)
978 {
979         uiBut *but;
980         uiLink *link;
981         uiLinkLine *line, *nline;
982         int a, b;
983
984         for (but = block->buttons.first; but; but = but->next) {
985                 if (but->type == LINK && but->link) {
986                         for (line = but->link->lines.first; line; line = nline) {
987                                 nline = line->next;
988                                 
989                                 if (line->flag & UI_SELECT) {
990                                         BLI_remlink(&but->link->lines, line);
991                                         
992                                         link = line->from->link;
993                                         
994                                         /* are there more pointers allowed? */
995                                         if (link->ppoin) {
996                                                 
997                                                 if (*(link->totlink) == 1) {
998                                                         *(link->totlink) = 0;
999                                                         MEM_freeN(*(link->ppoin));
1000                                                         *(link->ppoin) = NULL;
1001                                                 }
1002                                                 else {
1003                                                         b = 0;
1004                                                         for (a = 0; a < (*(link->totlink)); a++) {
1005                                                                 
1006                                                                 if ((*(link->ppoin))[a] != line->to->poin) {
1007                                                                         (*(link->ppoin))[b] = (*(link->ppoin))[a];
1008                                                                         b++;
1009                                                                 }
1010                                                         }
1011                                                         (*(link->totlink))--;
1012                                                 }
1013                                         }
1014                                         else {
1015                                                 *(link->poin) = NULL;
1016                                         }
1017                                         
1018                                         MEM_freeN(line);
1019                                 }
1020                         }
1021                 }
1022         }
1023 }
1024
1025
1026 static uiLinkLine *ui_is_a_link(uiBut *from, uiBut *to)
1027 {
1028         uiLinkLine *line;
1029         uiLink *link;
1030         
1031         link = from->link;
1032         if (link) {
1033                 for (line = link->lines.first; line; line = line->next) {
1034                         if (line->from == from && line->to == to) {
1035                                 return line;
1036                         }
1037                 }
1038         }
1039         return NULL;
1040 }
1041
1042 /* XXX BAD BAD HACK, fixme later **************** */
1043 /* Try to add an AND Controller between the sensor and the actuator logic bricks and to connect them all */
1044 static void ui_add_smart_controller(bContext *C, uiBut *from, uiBut *to)
1045 {
1046         Object *ob = NULL;
1047         bSensor *sens_iter;
1048         bActuator *act_to, *act_iter;
1049         bController *cont;
1050         bController ***sens_from_links;
1051         uiBut *tmp_but;
1052
1053         uiLink *link = from->link;
1054
1055         PointerRNA props_ptr, object_ptr;
1056         
1057         if (link->ppoin)
1058                 sens_from_links = (bController ***)(link->ppoin);
1059         else return;
1060
1061         act_to = (bActuator *)(to->poin);
1062
1063         /* (1) get the object */
1064         CTX_DATA_BEGIN (C, Object *, ob_iter, selected_editable_objects)
1065         {
1066                 for (sens_iter = ob_iter->sensors.first; sens_iter; sens_iter = sens_iter->next) {
1067                         if (&(sens_iter->links) == sens_from_links) {
1068                                 ob = ob_iter;
1069                                 break;
1070                         }
1071                 }
1072                 if (ob) break;
1073         } CTX_DATA_END;
1074
1075         if (!ob) return;
1076
1077         /* (2) check if the sensor and the actuator are from the same object */
1078         for (act_iter = ob->actuators.first; act_iter; act_iter = (bActuator *)act_iter->next) {
1079                 if (act_iter == act_to)
1080                         break;
1081         }
1082
1083         /* only works if the sensor and the actuator are from the same object */
1084         if (!act_iter) return;
1085         
1086         /* in case the linked controller is not the active one */
1087         RNA_pointer_create((ID *)ob, &RNA_Object, ob, &object_ptr);
1088         
1089         WM_operator_properties_create(&props_ptr, "LOGIC_OT_controller_add");
1090         RNA_string_set(&props_ptr, "object", ob->id.name + 2);
1091
1092         /* (3) add a new controller */
1093         if (WM_operator_name_call(C, "LOGIC_OT_controller_add", WM_OP_EXEC_DEFAULT, &props_ptr) & OPERATOR_FINISHED) {
1094                 cont = (bController *)ob->controllers.last;
1095                 cont->type = CONT_LOGIC_AND; /* Quick fix to make sure we always have an AND controller. It might be nicer to make sure the operator gives us the right one though... */
1096
1097                 /* (4) link the sensor->controller->actuator */
1098                 tmp_but = MEM_callocN(sizeof(uiBut), "uiBut");
1099                 uiSetButLink(tmp_but, (void **)&cont, (void ***)&(cont->links), &(cont->totlinks), from->link->tocode, (int)to->hardmin);
1100                 tmp_but->hardmin = from->link->tocode;
1101                 tmp_but->poin = (char *)cont;
1102
1103                 tmp_but->type = INLINK;
1104                 ui_add_link(C, from, tmp_but);
1105
1106                 tmp_but->type = LINK;
1107                 ui_add_link(C, tmp_but, to);
1108
1109                 /* (5) garbage collection */
1110                 MEM_freeN(tmp_but->link);
1111                 MEM_freeN(tmp_but);
1112         }
1113         WM_operator_properties_free(&props_ptr);
1114 }
1115
1116 static void ui_add_link(bContext *C, uiBut *from, uiBut *to)
1117 {
1118         /* in 'from' we have to add a link to 'to' */
1119         uiLink *link;
1120         uiLinkLine *line;
1121         void **oldppoin;
1122         int a;
1123         
1124         if ((line = ui_is_a_link(from, to))) {
1125                 line->flag |= UI_SELECT;
1126                 ui_delete_active_linkline(from->block);
1127                 return;
1128         }
1129
1130         if (from->type == INLINK && to->type == INLINK) {
1131                 return;
1132         }
1133         else if (from->type == LINK && to->type == INLINK) {
1134                 if (from->link->tocode != (int)to->hardmin) {
1135                         ui_add_smart_controller(C, from, to);
1136                         return;
1137                 }
1138         }
1139         else if (from->type == INLINK && to->type == LINK) {
1140                 if (to->link->tocode == (int)from->hardmin) {
1141                         return;
1142                 }
1143         }
1144         
1145         link = from->link;
1146         
1147         /* are there more pointers allowed? */
1148         if (link->ppoin) {
1149                 oldppoin = *(link->ppoin);
1150                 
1151                 (*(link->totlink))++;
1152                 *(link->ppoin) = MEM_callocN(*(link->totlink) * sizeof(void *), "new link");
1153                 
1154                 for (a = 0; a < (*(link->totlink)) - 1; a++) {
1155                         (*(link->ppoin))[a] = oldppoin[a];
1156                 }
1157                 (*(link->ppoin))[a] = to->poin;
1158                 
1159                 if (oldppoin) MEM_freeN(oldppoin);
1160         }
1161         else {
1162                 *(link->poin) = to->poin;
1163         }
1164         
1165 }
1166
1167
1168 static void ui_apply_but_LINK(bContext *C, uiBut *but, uiHandleButtonData *data)
1169 {
1170         ARegion *ar = CTX_wm_region(C);
1171         uiBut *bt;
1172         
1173         for (bt = but->block->buttons.first; bt; bt = bt->next) {
1174                 if (ui_mouse_inside_button(ar, bt, but->linkto[0] + ar->winrct.xmin, but->linkto[1] + ar->winrct.ymin) )
1175                         break;
1176         }
1177         if (bt && bt != but) {
1178                 if (!ELEM(bt->type, LINK, INLINK) || !ELEM(but->type, LINK, INLINK))
1179                         return;
1180                 
1181                 if (but->type == LINK) ui_add_link(C, but, bt);
1182                 else ui_add_link(C, bt, but);
1183
1184                 ui_apply_but_func(C, but);
1185                 data->retval = but->retval;
1186         }
1187         data->applied = true;
1188 }
1189
1190 static void ui_apply_but_IMAGE(bContext *C, uiBut *but, uiHandleButtonData *data)
1191 {
1192         ui_apply_but_func(C, but);
1193         data->retval = but->retval;
1194         data->applied = true;
1195 }
1196
1197 static void ui_apply_but_HISTOGRAM(bContext *C, uiBut *but, uiHandleButtonData *data)
1198 {
1199         ui_apply_but_func(C, but);
1200         data->retval = but->retval;
1201         data->applied = true;
1202 }
1203
1204 static void ui_apply_but_WAVEFORM(bContext *C, uiBut *but, uiHandleButtonData *data)
1205 {
1206         ui_apply_but_func(C, but);
1207         data->retval = but->retval;
1208         data->applied = true;
1209 }
1210
1211 static void ui_apply_but_TRACKPREVIEW(bContext *C, uiBut *but, uiHandleButtonData *data)
1212 {
1213         ui_apply_but_func(C, but);
1214         data->retval = but->retval;
1215         data->applied = true;
1216 }
1217
1218
1219 static void ui_apply_button(bContext *C, uiBlock *block, uiBut *but, uiHandleButtonData *data, const bool interactive)
1220 {
1221         char *editstr;
1222         double *editval;
1223         float *editvec;
1224         ColorBand *editcoba;
1225         CurveMapping *editcumap;
1226
1227         data->retval = 0;
1228
1229         /* if we cancel and have not applied yet, there is nothing to do,
1230          * otherwise we have to restore the original value again */
1231         if (data->cancel) {
1232                 if (!data->applied)
1233                         return;
1234
1235                 if (data->str) MEM_freeN(data->str);
1236                 data->str = data->origstr;
1237                 data->origstr = NULL;
1238                 data->value = data->origvalue;
1239                 data->origvalue = 0.0;
1240                 copy_v3_v3(data->vec, data->origvec);
1241                 data->origvec[0] = data->origvec[1] = data->origvec[2] = 0.0f;
1242         }
1243         else {
1244                 /* we avoid applying interactive edits a second time
1245                  * at the end with the appliedinteractive flag */
1246                 if (interactive) {
1247                         data->applied_interactive = true;
1248                 }
1249                 else if (data->applied_interactive) {
1250                         return;
1251                 }
1252         }
1253
1254         /* ensures we are writing actual values */
1255         editstr = but->editstr;
1256         editval = but->editval;
1257         editvec = but->editvec;
1258         editcoba = but->editcoba;
1259         editcumap = but->editcumap;
1260         but->editstr = NULL;
1261         but->editval = NULL;
1262         but->editvec = NULL;
1263         but->editcoba = NULL;
1264         but->editcumap = NULL;
1265
1266         /* handle different types */
1267         switch (but->type) {
1268                 case BUT:
1269                         ui_apply_but_BUT(C, but, data);
1270                         break;
1271                 case TEX:
1272                 case SEARCH_MENU_UNLINK:
1273                 case SEARCH_MENU:
1274                         ui_apply_but_TEX(C, but, data);
1275                         break;
1276                 case TOGBUT: 
1277                 case TOG: 
1278                 case TOGR: 
1279                 case ICONTOG:
1280                 case ICONTOGN:
1281                 case TOGN:
1282                 case BUT_TOGDUAL:
1283                 case OPTION:
1284                 case OPTIONN:
1285                         ui_apply_but_TOG(C, but, data);
1286                         break;
1287                 case ROW:
1288                 case LISTROW:
1289                         ui_apply_but_ROW(C, block, but, data);
1290                         break;
1291                 case SCROLL:
1292                 case NUM:
1293                 case NUMABS:
1294                 case SLI:
1295                 case NUMSLI:
1296                         ui_apply_but_NUM(C, but, data);
1297                         break;
1298                 case TOG3:
1299                         ui_apply_but_TOG3(C, but, data);
1300                         break;
1301                 case MENU:
1302                 case ICONROW:
1303                 case ICONTEXTROW:
1304                 case BLOCK:
1305                 case PULLDOWN:
1306                         ui_apply_but_BLOCK(C, but, data);
1307                         break;
1308                 case COLOR:
1309                         if (data->cancel)
1310                                 ui_apply_but_VEC(C, but, data);
1311                         else
1312                                 ui_apply_but_BLOCK(C, but, data);
1313                         break;
1314                 case BUTM:
1315                         ui_apply_but_BUTM(C, but, data);
1316                         break;
1317                 case BUT_NORMAL:
1318                 case HSVCUBE:
1319                 case HSVCIRCLE:
1320                         ui_apply_but_VEC(C, but, data);
1321                         break;
1322                 case BUT_COLORBAND:
1323                         ui_apply_but_COLORBAND(C, but, data);
1324                         break;
1325                 case BUT_CURVE:
1326                         ui_apply_but_CURVE(C, but, data);
1327                         break;
1328                 case IDPOIN:
1329                         ui_apply_but_IDPOIN(C, but, data);
1330                         break;
1331 #ifdef WITH_INTERNATIONAL
1332                 case CHARTAB:
1333                         ui_apply_but_CHARTAB(C, but, data);
1334                         break;
1335 #endif
1336                 case KEYEVT:
1337                 case HOTKEYEVT:
1338                         ui_apply_but_BUT(C, but, data);
1339                         break;
1340                 case LINK:
1341                 case INLINK:
1342                         ui_apply_but_LINK(C, but, data);
1343                         break;
1344                 case BUT_IMAGE:
1345                         ui_apply_but_IMAGE(C, but, data);
1346                         break;
1347                 case HISTOGRAM:
1348                         ui_apply_but_HISTOGRAM(C, but, data);
1349                         break;
1350                 case WAVEFORM:
1351                         ui_apply_but_WAVEFORM(C, but, data);
1352                         break;
1353                 case TRACKPREVIEW:
1354                         ui_apply_but_TRACKPREVIEW(C, but, data);
1355                         break;
1356                 default:
1357                         break;
1358         }
1359
1360         but->editstr = editstr;
1361         but->editval = editval;
1362         but->editvec = editvec;
1363         but->editcoba = editcoba;
1364         but->editcumap = editcumap;
1365 }
1366
1367 /* ******************* drop event ********************  */
1368
1369 /* only call if event type is EVT_DROP */
1370 static void ui_but_drop(bContext *C, const wmEvent *event, uiBut *but, uiHandleButtonData *data)
1371 {
1372         wmDrag *wmd;
1373         ListBase *drags = event->customdata; /* drop event type has listbase customdata by default */
1374         
1375         for (wmd = drags->first; wmd; wmd = wmd->next) {
1376                 if (wmd->type == WM_DRAG_ID) {
1377                         /* align these types with UI_but_active_drop_name */
1378                         if (ELEM4(but->type, TEX, IDPOIN, SEARCH_MENU, SEARCH_MENU_UNLINK)) {
1379                                 ID *id = (ID *)wmd->poin;
1380                                 
1381                                 if (but->poin == NULL && but->rnapoin.data == NULL) {}
1382                                 button_activate_state(C, but, BUTTON_STATE_TEXT_EDITING);
1383                                 BLI_strncpy(data->str, id->name + 2, data->maxlen);
1384                                 button_activate_state(C, but, BUTTON_STATE_EXIT);
1385                         }
1386                 }
1387         }
1388         
1389 }
1390
1391 /* ******************* copy and paste ********************  */
1392
1393 /* c = copy, v = paste */
1394 static void ui_but_copy_paste(bContext *C, uiBut *but, uiHandleButtonData *data, char mode)
1395 {
1396         static ColorBand but_copypaste_coba = {0};
1397         char buf[UI_MAX_DRAW_STR + 1] = {0};
1398
1399         if (mode == 'v' && but->lock  == TRUE) {
1400                 return;
1401         }
1402
1403         if (mode == 'v') {
1404                 /* extract first line from clipboard in case of multi-line copies */
1405                 char *p, *pbuf = WM_clipboard_text_get(0);
1406                 p = pbuf;
1407                 if (p) {
1408                         int i = 0;
1409                         while (*p && *p != '\r' && *p != '\n' && i < UI_MAX_DRAW_STR) {
1410                                 buf[i++] = *p;
1411                                 p++;
1412                         }
1413                         buf[i] = 0;
1414                         MEM_freeN(pbuf);
1415                 }
1416         }
1417         
1418         /* numeric value */
1419         if (ELEM3(but->type, NUM, NUMABS, NUMSLI)) {
1420                 
1421                 if (but->poin == NULL && but->rnapoin.data == NULL) {
1422                         /* pass */
1423                 }
1424                 else if (mode == 'c') {
1425                         /* Get many decimal places, then strip trailing zeros.
1426                          * note: too high values start to give strange results (6 or so is ok) */
1427                         ui_get_but_string_ex(but, buf, sizeof(buf), 6);
1428                         BLI_str_rstrip_float_zero(buf, '\0');
1429
1430                         WM_clipboard_text_set(buf, 0);
1431                 }
1432                 else {
1433                         double val;
1434
1435                         if (ui_set_but_string_eval_num(C, but, buf, &val)) {
1436                                 button_activate_state(C, but, BUTTON_STATE_NUM_EDITING);
1437                                 data->value = val;
1438                                 ui_set_but_string(C, but, buf);
1439                                 button_activate_state(C, but, BUTTON_STATE_EXIT);
1440                         }
1441                 }
1442         }
1443
1444         /* RGB triple */
1445         else if (but->type == COLOR) {
1446                 float rgba[4];
1447                 
1448                 if (but->poin == NULL && but->rnapoin.data == NULL) {
1449                         /* pass */
1450                 }
1451                 else if (mode == 'c') {
1452                         if (RNA_property_array_length(&but->rnapoin, but->rnaprop) == 4)
1453                                 rgba[3] = RNA_property_float_get_index(&but->rnapoin, but->rnaprop, 3);
1454                         else
1455                                 rgba[3] = 1.0f;
1456                         
1457                         ui_get_but_vectorf(but, rgba);
1458                         /* convert to linear color to do compatible copy between gamma and non-gamma */
1459                         if (but->rnaprop && RNA_property_subtype(but->rnaprop) == PROP_COLOR_GAMMA)
1460                                 srgb_to_linearrgb_v3_v3(rgba, rgba);
1461
1462                         BLI_snprintf(buf, sizeof(buf), "[%f, %f, %f, %f]", rgba[0], rgba[1], rgba[2], rgba[3]);
1463                         WM_clipboard_text_set(buf, 0);
1464                         
1465                 }
1466                 else {
1467                         if (sscanf(buf, "[%f, %f, %f, %f]", &rgba[0], &rgba[1], &rgba[2], &rgba[3]) == 4) {
1468                                 /* assume linear colors in buffer */
1469                                 if (but->rnaprop && RNA_property_subtype(but->rnaprop) == PROP_COLOR_GAMMA)
1470                                         linearrgb_to_srgb_v3_v3(rgba, rgba);
1471
1472                                 button_activate_state(C, but, BUTTON_STATE_NUM_EDITING);
1473                                 ui_set_but_vectorf(but, rgba);
1474                                 if (RNA_property_array_length(&but->rnapoin, but->rnaprop) == 4)
1475                                         RNA_property_float_set_index(&but->rnapoin, but->rnaprop, 3, rgba[3]);
1476
1477                                 button_activate_state(C, but, BUTTON_STATE_EXIT);
1478                         }
1479                 }
1480         }
1481
1482         /* text/string and ID data */
1483         else if (ELEM4(but->type, TEX, IDPOIN, SEARCH_MENU, SEARCH_MENU_UNLINK)) {
1484                 uiHandleButtonData *active_data = but->active;
1485
1486                 if (but->poin == NULL && but->rnapoin.data == NULL) {
1487                         /* pass */
1488                 }
1489                 else if (mode == 'c') {
1490                         button_activate_state(C, but, BUTTON_STATE_TEXT_EDITING);
1491                         BLI_strncpy(buf, active_data->str, UI_MAX_DRAW_STR);
1492                         WM_clipboard_text_set(active_data->str, 0);
1493                         active_data->cancel = true;
1494                         button_activate_state(C, but, BUTTON_STATE_EXIT);
1495                 }
1496                 else {
1497                         button_activate_state(C, but, BUTTON_STATE_TEXT_EDITING);
1498
1499                         if (ui_is_but_utf8(but)) BLI_strncpy_utf8(active_data->str, buf, active_data->maxlen);
1500                         else BLI_strncpy(active_data->str, buf, active_data->maxlen);
1501
1502                         if (ELEM(but->type, SEARCH_MENU, SEARCH_MENU_UNLINK)) {
1503                                 /* else uiSearchboxData.active member is not updated [#26856] */
1504                                 ui_searchbox_update(C, data->searchbox, but, true);
1505                         }
1506                         button_activate_state(C, but, BUTTON_STATE_EXIT);
1507                 }
1508         }
1509         /* colorband (not supported by system clipboard) */
1510         else if (but->type == BUT_COLORBAND) {
1511                 if (mode == 'c') {
1512                         if (but->poin == NULL)
1513                                 return;
1514
1515                         memcpy(&but_copypaste_coba, but->poin, sizeof(ColorBand));
1516                 }
1517                 else {
1518                         if (but_copypaste_coba.tot == 0)
1519                                 return;
1520
1521                         if (!but->poin)
1522                                 but->poin = MEM_callocN(sizeof(ColorBand), "colorband");
1523
1524                         button_activate_state(C, but, BUTTON_STATE_NUM_EDITING);
1525                         memcpy(data->coba, &but_copypaste_coba, sizeof(ColorBand));
1526                         button_activate_state(C, but, BUTTON_STATE_EXIT);
1527                 }
1528         }
1529         /* operator button (any type) */
1530         else if (but->optype) {
1531                 if (mode == 'c') {
1532                         PointerRNA *opptr;
1533                         char *str;
1534                         opptr = uiButGetOperatorPtrRNA(but); /* allocated when needed, the button owns it */
1535
1536                         str = WM_operator_pystring(C, but->optype, opptr, 0);
1537
1538                         WM_clipboard_text_set(str, 0);
1539
1540                         MEM_freeN(str);
1541                 }
1542         }
1543 }
1544
1545 /* ************************ password text ******************************
1546  *
1547  * Functions to convert password strings that should not be displayed
1548  * to asterisk representation (e.g. mysecretpasswd -> *************)
1549  *
1550  * It converts every UTF-8 character to an asterisk, and also remaps
1551  * the cursor position and selection start/end.
1552  *
1553  * Note: remaping is used, because password could contain UTF-8 characters.
1554  *
1555  */
1556
1557 static int ui_text_position_from_hidden(uiBut *but, int pos)
1558 {
1559         const char *strpos;
1560         int i;
1561
1562         for (i = 0, strpos = but->drawstr; i < pos; i++)
1563                 strpos = BLI_str_find_next_char_utf8(strpos, NULL);
1564         
1565         return (strpos - but->drawstr);
1566 }
1567
1568 static int ui_text_position_to_hidden(uiBut *but, int pos)
1569 {
1570         return BLI_strnlen_utf8(but->drawstr, pos);
1571 }
1572
1573 void ui_button_text_password_hide(char password_str[UI_MAX_DRAW_STR], uiBut *but, int restore)
1574 {
1575         if (!(but->rnaprop && RNA_property_subtype(but->rnaprop) == PROP_PASSWORD))
1576                 return;
1577
1578         if (restore) {
1579                 /* restore original string */
1580                 BLI_strncpy(but->drawstr, password_str, UI_MAX_DRAW_STR);
1581
1582                 /* remap cursor positions */
1583                 if (but->pos >= 0) {
1584                         but->pos = ui_text_position_from_hidden(but, but->pos);
1585                         but->selsta = ui_text_position_from_hidden(but, but->selsta);
1586                         but->selend = ui_text_position_from_hidden(but, but->selend);
1587                 }
1588         }
1589         else {
1590                 /* convert text to hidden test using asterisks (e.g. pass -> ****) */
1591                 int i, len = BLI_strlen_utf8(but->drawstr);
1592
1593                 /* remap cursor positions */
1594                 if (but->pos >= 0) {
1595                         but->pos = ui_text_position_to_hidden(but, but->pos);
1596                         but->selsta = ui_text_position_to_hidden(but, but->selsta);
1597                         but->selend = ui_text_position_to_hidden(but, but->selend);
1598                 }
1599
1600                 /* save original string */
1601                 BLI_strncpy(password_str, but->drawstr, UI_MAX_DRAW_STR);
1602
1603                 for (i = 0; i < len; i++)
1604                         but->drawstr[i] = '*';
1605                 but->drawstr[i] = '\0';
1606         }
1607 }
1608
1609
1610 /* ************* in-button text selection/editing ************* */
1611
1612
1613 static bool ui_textedit_delete_selection(uiBut *but, uiHandleButtonData *data)
1614 {
1615         char *str = data->str;
1616         const int len = strlen(str);
1617         bool change = false;
1618         if (but->selsta != but->selend && len) {
1619                 memmove(str + but->selsta, str + but->selend, (len - but->selend) + 1);
1620                 change = true;
1621         }
1622         
1623         but->pos = but->selend = but->selsta;
1624         return change;
1625 }
1626
1627 /* note, but->block->aspect is used here, when drawing button style is getting scaled too */
1628 static void ui_textedit_set_cursor_pos(uiBut *but, uiHandleButtonData *data, const float x)
1629 {
1630         uiStyle *style = UI_GetStyle();  // XXX pass on as arg
1631         uiFontStyle *fstyle = &style->widget;
1632         float startx = but->rect.xmin;
1633         char *origstr, password_str[UI_MAX_DRAW_STR];
1634
1635         uiStyleFontSet(fstyle);
1636
1637         if (fstyle->kerning == 1) /* for BLF_width */
1638                 BLF_enable(fstyle->uifont_id, BLF_KERNING_DEFAULT);
1639         
1640         ui_button_text_password_hide(password_str, but, FALSE);
1641
1642         origstr = MEM_mallocN(sizeof(char) * data->maxlen, "ui_textedit origstr");
1643         
1644         BLI_strncpy(origstr, but->drawstr, data->maxlen);
1645         
1646         /* XXX solve generic, see: #widget_draw_text_icon */
1647         if (but->type == NUM || but->type == NUMSLI) {
1648                 startx += (int)(0.5f * (BLI_rctf_size_y(&but->rect)));
1649         }
1650         else if (ELEM3(but->type, TEX, SEARCH_MENU, SEARCH_MENU_UNLINK)) {
1651                 if (but->flag & UI_HAS_ICON) {
1652                         startx += UI_DPI_ICON_SIZE;
1653                 }
1654                 /* but this extra .05 makes clicks inbetween characters feel nicer */
1655                 startx += ((UI_TEXT_MARGIN_X + 0.05f) * U.widget_unit);
1656         }
1657         
1658         /* mouse dragged outside the widget to the left */
1659         if (x < startx) {
1660                 int i = but->ofs;
1661
1662                 origstr[but->ofs] = '\0';
1663                 
1664                 while (i > 0) {
1665                         if (BLI_str_cursor_step_prev_utf8(origstr, but->ofs, &i)) {
1666                                 /* 0.25 == scale factor for less sensitivity */
1667                                 if (BLF_width(fstyle->uifont_id, origstr + i) > (startx - x) * 0.25f) {
1668                                         break;
1669                                 }
1670                         }
1671                         else {
1672                                 break; /* unlikely but possible */
1673                         }
1674                 }
1675                 but->ofs = i;
1676                 but->pos = but->ofs;
1677         }
1678         /* mouse inside the widget, mouse coords mapped in widget space */
1679         else {  /* (x >= startx) */
1680                 int pos_i;
1681
1682                 /* keep track of previous distance from the cursor to the char */
1683                 float cdist, cdist_prev = 0.0f;
1684                 short pos_prev;
1685                 
1686                 but->pos = pos_prev = strlen(origstr) - but->ofs;
1687
1688                 while (true) {
1689                         cdist = startx + BLF_width(fstyle->uifont_id, origstr + but->ofs);
1690
1691                         /* check if position is found */
1692                         if (cdist < x) {
1693                                 /* check is previous location was in fact closer */
1694                                 if (((float)x - cdist) > (cdist_prev - (float)x)) {
1695                                         but->pos = pos_prev;
1696                                 }
1697                                 break;
1698                         }
1699                         cdist_prev = cdist;
1700                         pos_prev   = but->pos;
1701                         /* done with tricky distance checks */
1702
1703                         pos_i = but->pos;
1704                         if (but->pos <= 0) break;
1705                         if (BLI_str_cursor_step_prev_utf8(origstr, but->ofs, &pos_i)) {
1706                                 but->pos = pos_i;
1707                                 origstr[but->pos + but->ofs] = 0;
1708                         }
1709                         else {
1710                                 break; /* unlikely but possible */
1711                         }
1712                 }
1713                 but->pos += but->ofs;
1714                 if (but->pos < 0) but->pos = 0;
1715         }
1716         
1717         if (fstyle->kerning == 1)
1718                 BLF_disable(fstyle->uifont_id, BLF_KERNING_DEFAULT);
1719         
1720         ui_button_text_password_hide(password_str, but, TRUE);
1721
1722         MEM_freeN(origstr);
1723 }
1724
1725 static void ui_textedit_set_cursor_select(uiBut *but, uiHandleButtonData *data, const float x)
1726 {
1727         if      (x > data->selstartx) data->selextend = EXTEND_RIGHT;
1728         else if (x < data->selstartx) data->selextend = EXTEND_LEFT;
1729
1730         ui_textedit_set_cursor_pos(but, data, x);
1731
1732         if      (data->selextend == EXTEND_RIGHT) but->selend = but->pos;
1733         else if (data->selextend == EXTEND_LEFT)  but->selsta = but->pos;
1734
1735         ui_check_but(but);
1736 }
1737
1738 /* this is used for both utf8 and ascii, its meant to be used for single keys,
1739  * notice the buffer is either copied or not, so its not suitable for pasting in
1740  * - campbell */
1741 static bool ui_textedit_type_buf(uiBut *but, uiHandleButtonData *data,
1742                                  const char *utf8_buf, int utf8_buf_len)
1743 {
1744         char *str;
1745         int len;
1746         bool changed = false;
1747
1748         str = data->str;
1749         len = strlen(str);
1750
1751         if (len - (but->selend - but->selsta) + 1 <= data->maxlen) {
1752                 int step = utf8_buf_len;
1753
1754                 /* type over the current selection */
1755                 if ((but->selend - but->selsta) > 0) {
1756                         changed = ui_textedit_delete_selection(but, data);
1757                         len = strlen(str);
1758                 }
1759
1760                 if (len + step < data->maxlen) {
1761                         memmove(&str[but->pos + step], &str[but->pos], (len + 1) - but->pos);
1762                         memcpy(&str[but->pos], utf8_buf, step * sizeof(char));
1763                         but->pos += step;
1764                         changed = true;
1765                 }
1766         }
1767
1768         return changed;
1769 }
1770
1771 static bool ui_textedit_type_ascii(uiBut *but, uiHandleButtonData *data, char ascii)
1772 {
1773         char buf[2] = {ascii, '\0'};
1774
1775         if (ui_is_but_utf8(but) && (BLI_str_utf8_size(buf) == -1)) {
1776                 printf("%s: entering invalid ascii char into an ascii key (%d)\n",
1777                        __func__, (int)(unsigned char)ascii);
1778
1779                 return false;
1780         }
1781
1782         /* in some cases we want to allow invalid utf8 chars */
1783         return ui_textedit_type_buf(but, data, buf, 1);
1784 }
1785
1786 static void ui_textedit_move(uiBut *but, uiHandleButtonData *data, strCursorJumpDirection direction,
1787                              int select, strCursorJumpType jump)
1788 {
1789         const char *str = data->str;
1790         const int len = strlen(str);
1791         const int pos_prev = but->pos;
1792         const int has_sel = (but->selend - but->selsta) > 0;
1793
1794         ui_check_but(but);
1795
1796         /* special case, quit selection and set cursor */
1797         if (has_sel && !select) {
1798                 if (jump == STRCUR_JUMP_ALL) {
1799                         but->selsta = but->selend = but->pos = direction ? len : 0;
1800                 }
1801                 else {
1802                         if (direction) {
1803                                 but->selsta = but->pos = but->selend;
1804                         }
1805                         else {
1806                                 but->pos = but->selend = but->selsta;
1807                         }
1808                 }
1809                 data->selextend = 0;
1810         }
1811         else {
1812                 int pos_i = but->pos;
1813                 BLI_str_cursor_step_utf8(str, len, &pos_i, direction, jump, true);
1814                 but->pos = pos_i;
1815
1816                 if (select) {
1817                         /* existing selection */
1818                         if (has_sel) {
1819
1820                                 if (data->selextend == 0) {
1821                                         data->selextend = EXTEND_RIGHT;
1822                                 }
1823
1824                                 if (direction) {
1825                                         if (data->selextend == EXTEND_RIGHT) {
1826                                                 but->selend = but->pos;
1827                                         }
1828                                         else {
1829                                                 but->selsta = but->pos;
1830                                         }
1831                                 }
1832                                 else {
1833                                         if (data->selextend == EXTEND_LEFT) {
1834                                                 but->selsta = but->pos;
1835                                         }
1836                                         else {
1837                                                 but->selend = but->pos;
1838                                         }
1839                                 }
1840
1841                                 if (but->selend < but->selsta) {
1842                                         SWAP(short, but->selsta, but->selend);
1843                                         data->selextend = (data->selextend == EXTEND_RIGHT) ? EXTEND_LEFT : EXTEND_RIGHT;
1844                                 }
1845
1846                         } /* new selection */
1847                         else {
1848                                 if (direction) {
1849                                         data->selextend = EXTEND_RIGHT;
1850                                         but->selend = but->pos;
1851                                         but->selsta = pos_prev;
1852                                 }
1853                                 else {
1854                                         data->selextend = EXTEND_LEFT;
1855                                         but->selend = pos_prev;
1856                                         but->selsta = but->pos;
1857                                 }
1858                         }
1859                 }
1860         }
1861 }
1862
1863 static bool ui_textedit_delete(uiBut *but, uiHandleButtonData *data, int direction, strCursorJumpType jump)
1864 {
1865         char *str = data->str;
1866         const int len = strlen(str);
1867
1868         bool changed = false;
1869
1870         if (jump == STRCUR_JUMP_ALL) {
1871                 if (len) changed = true;
1872                 str[0] = '\0';
1873                 but->pos = 0;
1874         }
1875         else if (direction) { /* delete */
1876                 if ((but->selend - but->selsta) > 0) {
1877                         changed = ui_textedit_delete_selection(but, data);
1878                 }
1879                 else if (but->pos >= 0 && but->pos < len) {
1880                         int pos = but->pos;
1881                         int step;
1882                         BLI_str_cursor_step_utf8(str, len, &pos, direction, jump, true);
1883                         step = pos - but->pos;
1884                         memmove(&str[but->pos], &str[but->pos + step], (len + 1) - but->pos);
1885                         changed = true;
1886                 }
1887         }
1888         else { /* backspace */
1889                 if (len != 0) {
1890                         if ((but->selend - but->selsta) > 0) {
1891                                 changed = ui_textedit_delete_selection(but, data);
1892                         }
1893                         else if (but->pos > 0) {
1894                                 int pos = but->pos;
1895                                 int step;
1896
1897                                 BLI_str_cursor_step_utf8(str, len, &pos, direction, jump, true);
1898                                 step = but->pos - pos;
1899                                 memmove(&str[but->pos - step], &str[but->pos], (len + 1) - but->pos);
1900                                 but->pos -= step;
1901                                 changed = true;
1902                         }
1903                 }
1904         }
1905
1906         return changed;
1907 }
1908
1909 static bool ui_textedit_autocomplete(bContext *C, uiBut *but, uiHandleButtonData *data)
1910 {
1911         char *str;
1912         /* TODO, should return false if it cant autocomp. */
1913         bool changed = true;
1914
1915         str = data->str;
1916
1917         if (data->searchbox)
1918                 ui_searchbox_autocomplete(C, data->searchbox, but, data->str);
1919         else
1920                 but->autocomplete_func(C, str, but->autofunc_arg);
1921
1922         but->pos = strlen(str);
1923         but->selsta = but->selend = but->pos;
1924
1925         return changed;
1926 }
1927
1928 /* mode for ui_textedit_copypaste() */
1929 enum {
1930         UI_TEXTEDIT_PASTE = 1,
1931         UI_TEXTEDIT_COPY,
1932         UI_TEXTEDIT_CUT
1933 };
1934
1935 static bool ui_textedit_copypaste(uiBut *but, uiHandleButtonData *data, const int mode)
1936 {
1937         char buf[UI_MAX_DRAW_STR] = {0};
1938         char *str, *p, *pbuf;
1939         int x;
1940         bool changed = false;
1941         int str_len, buf_len;
1942
1943         str = data->str;
1944         str_len = strlen(str);
1945         
1946         /* paste */
1947         if (mode == UI_TEXTEDIT_PASTE) {
1948                 /* TODO, ensure UTF8 ui_is_but_utf8() - campbell */
1949                 /* extract the first line from the clipboard */
1950                 p = pbuf = WM_clipboard_text_get(0);
1951
1952                 if (p && p[0]) {
1953                         unsigned int y;
1954                         buf_len = 0;
1955                         while (*p && *p != '\r' && *p != '\n' && buf_len < UI_MAX_DRAW_STR - 1) {
1956                                 buf[buf_len++] = *p;
1957                                 p++;
1958                         }
1959                         buf[buf_len] = 0;
1960
1961                         /* paste over the current selection */
1962                         if ((but->selend - but->selsta) > 0) {
1963                                 ui_textedit_delete_selection(but, data);
1964                                 str_len = strlen(str);
1965                         }
1966                         
1967                         for (y = 0; y < buf_len; y++) {
1968                                 /* add contents of buffer */
1969                                 if (str_len + 1 < data->maxlen) {
1970                                         for (x = data->maxlen; x > but->pos; x--)
1971                                                 str[x] = str[x - 1];
1972                                         str[but->pos] = buf[y];
1973                                         but->pos++; 
1974                                         str_len++;
1975                                         str[str_len] = '\0';
1976                                 }
1977                         }
1978
1979                         changed = true;
1980                 }
1981
1982                 if (pbuf) {
1983                         MEM_freeN(pbuf);
1984                 }
1985         }
1986         /* cut & copy */
1987         else if (ELEM(mode, UI_TEXTEDIT_COPY, UI_TEXTEDIT_CUT)) {
1988                 /* copy the contents to the copypaste buffer */
1989                 for (x = but->selsta; x <= but->selend; x++) {
1990                         if (x == but->selend)
1991                                 buf[x] = '\0';
1992                         else
1993                                 buf[(x - but->selsta)] = str[x];
1994                 }
1995
1996                 WM_clipboard_text_set(buf, 0);
1997                 
1998                 /* for cut only, delete the selection afterwards */
1999                 if (mode == UI_TEXTEDIT_CUT) {
2000                         if ((but->selend - but->selsta) > 0) {
2001                                 changed = ui_textedit_delete_selection(but, data);
2002                         }
2003                 }
2004         }
2005
2006         return changed;
2007 }
2008
2009 static void ui_textedit_begin(bContext *C, uiBut *but, uiHandleButtonData *data)
2010 {
2011         int len;
2012
2013         if (data->str) {
2014                 MEM_freeN(data->str);
2015                 data->str = NULL;
2016         }
2017
2018         /* retrieve string */
2019         data->maxlen = ui_get_but_string_max_length(but);
2020         data->str = MEM_callocN(sizeof(char) * data->maxlen + 1, "textedit str");
2021         ui_get_but_string(but, data->str, data->maxlen);
2022
2023         if (ui_is_but_float(but) && !ui_is_but_unit(but)) {
2024                 BLI_str_rstrip_float_zero(data->str, '\0');
2025         }
2026
2027         if (ELEM3(but->type, NUM, NUMABS, NUMSLI)) {
2028                 ui_convert_to_unit_alt_name(but, data->str, data->maxlen);
2029         }
2030
2031         /* won't change from now on */
2032         len = strlen(data->str);
2033
2034         data->origstr = BLI_strdupn(data->str, len);
2035         data->selextend = 0;
2036         data->selstartx = 0;
2037
2038         /* set cursor pos to the end of the text */
2039         but->editstr = data->str;
2040         but->pos = len;
2041         but->selsta = 0;
2042         but->selend = len;
2043
2044         /* optional searchbox */
2045         if (ELEM(but->type, SEARCH_MENU, SEARCH_MENU_UNLINK)) {
2046                 data->searchbox = ui_searchbox_create(C, data->region, but);
2047                 ui_searchbox_update(C, data->searchbox, but, true); /* true = reset */
2048         }
2049
2050         /* reset alert flag (avoid confusion, will refresh on exit) */
2051         but->flag &= ~UI_BUT_REDALERT;
2052
2053         ui_check_but(but);
2054         
2055         WM_cursor_modal(CTX_wm_window(C), BC_TEXTEDITCURSOR);
2056 }
2057
2058 static void ui_textedit_end(bContext *C, uiBut *but, uiHandleButtonData *data)
2059 {
2060         if (but) {
2061                 if (ui_is_but_utf8(but)) {
2062                         int strip = BLI_utf8_invalid_strip(but->editstr, strlen(but->editstr));
2063                         /* not a file?, strip non utf-8 chars */
2064                         if (strip) {
2065                                 /* wont happen often so isn't that annoying to keep it here for a while */
2066                                 printf("%s: invalid utf8 - stripped chars %d\n", __func__, strip);
2067                         }
2068                 }
2069                 
2070                 if (data->searchbox) {
2071                         if (data->cancel == false) {
2072                                 if ((ui_searchbox_apply(but, data->searchbox) == false) &&
2073                                     (ui_searchbox_find_index(data->searchbox, but->editstr) == -1))
2074                                 {
2075                                         data->cancel = true;
2076                                 }
2077                         }
2078
2079                         ui_searchbox_free(C, data->searchbox);
2080                         data->searchbox = NULL;
2081                 }
2082                 
2083                 but->editstr = NULL;
2084                 but->pos = -1;
2085         }
2086         
2087         WM_cursor_restore(CTX_wm_window(C));
2088 }
2089
2090 static void ui_textedit_next_but(uiBlock *block, uiBut *actbut, uiHandleButtonData *data)
2091 {
2092         uiBut *but;
2093
2094         /* label and roundbox can overlap real buttons (backdrops...) */
2095         if (ELEM4(actbut->type, LABEL, SEPR, ROUNDBOX, LISTBOX))
2096                 return;
2097
2098         for (but = actbut->next; but; but = but->next) {
2099                 if (ELEM7(but->type, TEX, NUM, NUMABS, NUMSLI, IDPOIN, SEARCH_MENU, SEARCH_MENU_UNLINK)) {
2100                         if (!(but->flag & UI_BUT_DISABLED)) {
2101                                 data->postbut = but;
2102                                 data->posttype = BUTTON_ACTIVATE_TEXT_EDITING;
2103                                 return;
2104                         }
2105                 }
2106         }
2107         for (but = block->buttons.first; but != actbut; but = but->next) {
2108                 if (ELEM7(but->type, TEX, NUM, NUMABS, NUMSLI, IDPOIN, SEARCH_MENU, SEARCH_MENU_UNLINK)) {
2109                         if (!(but->flag & UI_BUT_DISABLED)) {
2110                                 data->postbut = but;
2111                                 data->posttype = BUTTON_ACTIVATE_TEXT_EDITING;
2112                                 return;
2113                         }
2114                 }
2115         }
2116 }
2117
2118 static void ui_textedit_prev_but(uiBlock *block, uiBut *actbut, uiHandleButtonData *data)
2119 {
2120         uiBut *but;
2121
2122         /* label and roundbox can overlap real buttons (backdrops...) */
2123         if (ELEM4(actbut->type, LABEL, SEPR, ROUNDBOX, LISTBOX))
2124                 return;
2125
2126         for (but = actbut->prev; but; but = but->prev) {
2127                 if (ELEM7(but->type, TEX, NUM, NUMABS, NUMSLI, IDPOIN, SEARCH_MENU, SEARCH_MENU_UNLINK)) {
2128                         if (!(but->flag & UI_BUT_DISABLED)) {
2129                                 data->postbut = but;
2130                                 data->posttype = BUTTON_ACTIVATE_TEXT_EDITING;
2131                                 return;
2132                         }
2133                 }
2134         }
2135         for (but = block->buttons.last; but != actbut; but = but->prev) {
2136                 if (ELEM7(but->type, TEX, NUM, NUMABS, NUMSLI, IDPOIN, SEARCH_MENU, SEARCH_MENU_UNLINK)) {
2137                         if (!(but->flag & UI_BUT_DISABLED)) {
2138                                 data->postbut = but;
2139                                 data->posttype = BUTTON_ACTIVATE_TEXT_EDITING;
2140                                 return;
2141                         }
2142                 }
2143         }
2144 }
2145
2146
2147 static void ui_do_but_textedit(bContext *C, uiBlock *block, uiBut *but, uiHandleButtonData *data, const wmEvent *event)
2148 {
2149         int mx, my, retval = WM_UI_HANDLER_CONTINUE;
2150         bool changed = false, inbox = false, update = false;
2151
2152         switch (event->type) {
2153                 case MOUSEMOVE:
2154                 case MOUSEPAN:
2155                         if (data->searchbox) {
2156 #ifdef USE_KEYNAV_LIMIT
2157                                 if ((event->type == MOUSEMOVE) && ui_mouse_motion_keynav_test(&data->searchbox_keynav_state, event)) {
2158                                         /* pass */
2159                                 }
2160                                 else {
2161                                         ui_searchbox_event(C, data->searchbox, but, event);
2162                                 }
2163 #else
2164                                 ui_searchbox_event(C, data->searchbox, but, event);
2165 #endif
2166                         }
2167                         
2168                         break;
2169                 case RIGHTMOUSE:
2170                 case ESCKEY:
2171                         data->cancel = true;
2172                         data->escapecancel = true;
2173                         button_activate_state(C, but, BUTTON_STATE_EXIT);
2174                         retval = WM_UI_HANDLER_BREAK;
2175                         break;
2176                 case LEFTMOUSE:
2177                 {
2178                         /* exit on LMB only on RELEASE for searchbox, to mimic other popups, and allow multiple menu levels */
2179                         if (data->searchbox)
2180                                 inbox = ui_searchbox_inside(data->searchbox, event->x, event->y);
2181
2182                         if (event->val == KM_PRESS) {
2183                                 mx = event->x;
2184                                 my = event->y;
2185                                 ui_window_to_block(data->region, block, &mx, &my);
2186
2187                                 if (ui_but_contains_pt(but, mx, my)) {
2188                                         ui_textedit_set_cursor_pos(but, data, mx);
2189                                         but->selsta = but->selend = but->pos;
2190                                         data->selstartx = mx;
2191
2192                                         button_activate_state(C, but, BUTTON_STATE_TEXT_SELECTING);
2193                                         retval = WM_UI_HANDLER_BREAK;
2194                                 }
2195                                 else if (inbox == false) {
2196                                         /* if searchbox, click outside will cancel */
2197                                         if (data->searchbox)
2198                                                 data->cancel = data->escapecancel = true;
2199                                         button_activate_state(C, but, BUTTON_STATE_EXIT);
2200                                         retval = WM_UI_HANDLER_BREAK;
2201                                 }
2202                         }
2203                         else if (inbox) {
2204                                 button_activate_state(C, but, BUTTON_STATE_EXIT);
2205                                 retval = WM_UI_HANDLER_BREAK;
2206                         }
2207                         break;
2208                 }
2209         }
2210
2211         if (event->val == KM_PRESS) {
2212                 switch (event->type) {
2213                         case VKEY:
2214                         case XKEY:
2215                         case CKEY:
2216                                 if (event->ctrl || event->oskey) {
2217                                         if (event->type == VKEY)
2218                                                 changed = ui_textedit_copypaste(but, data, UI_TEXTEDIT_PASTE);
2219                                         else if (event->type == CKEY)
2220                                                 changed = ui_textedit_copypaste(but, data, UI_TEXTEDIT_COPY);
2221                                         else if (event->type == XKEY)
2222                                                 changed = ui_textedit_copypaste(but, data, UI_TEXTEDIT_CUT);
2223
2224                                         retval = WM_UI_HANDLER_BREAK;
2225                                 }
2226                                 break;
2227                         case RIGHTARROWKEY:
2228                                 ui_textedit_move(but, data, STRCUR_DIR_NEXT,
2229                                                  event->shift, event->ctrl ? STRCUR_JUMP_DELIM : STRCUR_JUMP_NONE);
2230                                 retval = WM_UI_HANDLER_BREAK;
2231                                 break;
2232                         case LEFTARROWKEY:
2233                                 ui_textedit_move(but, data, STRCUR_DIR_PREV,
2234                                                  event->shift, event->ctrl ? STRCUR_JUMP_DELIM : STRCUR_JUMP_NONE);
2235                                 retval = WM_UI_HANDLER_BREAK;
2236                                 break;
2237                         case WHEELDOWNMOUSE:
2238                         case DOWNARROWKEY:
2239                                 if (data->searchbox) {
2240 #ifdef USE_KEYNAV_LIMIT
2241                                         ui_mouse_motion_keynav_init(&data->searchbox_keynav_state, event);
2242 #endif
2243                                         ui_searchbox_event(C, data->searchbox, but, event);
2244                                         break;
2245                                 }
2246                         /* pass on purposedly */
2247                         case ENDKEY:
2248                                 ui_textedit_move(but, data, STRCUR_DIR_NEXT,
2249                                                  event->shift, STRCUR_JUMP_ALL);
2250                                 retval = WM_UI_HANDLER_BREAK;
2251                                 break;
2252                         case WHEELUPMOUSE:
2253                         case UPARROWKEY:
2254                                 if (data->searchbox) {
2255 #ifdef USE_KEYNAV_LIMIT
2256                                         ui_mouse_motion_keynav_init(&data->searchbox_keynav_state, event);
2257 #endif
2258                                         ui_searchbox_event(C, data->searchbox, but, event);
2259                                         break;
2260                                 }
2261                         /* pass on purposedly */
2262                         case HOMEKEY:
2263                                 ui_textedit_move(but, data, STRCUR_DIR_PREV,
2264                                                  event->shift, STRCUR_JUMP_ALL);
2265                                 retval = WM_UI_HANDLER_BREAK;
2266                                 break;
2267                         case PADENTER:
2268                         case RETKEY:
2269                                 button_activate_state(C, but, BUTTON_STATE_EXIT);
2270                                 retval = WM_UI_HANDLER_BREAK;
2271                                 break;
2272                         case DELKEY:
2273                                 changed = ui_textedit_delete(but, data, 1,
2274                                                              event->ctrl ? STRCUR_JUMP_DELIM : STRCUR_JUMP_NONE);
2275                                 retval = WM_UI_HANDLER_BREAK;
2276                                 break;
2277
2278                         case BACKSPACEKEY:
2279                                 changed = ui_textedit_delete(but, data, 0,
2280                                                              event->shift ? STRCUR_JUMP_ALL : (event->ctrl ? STRCUR_JUMP_DELIM : STRCUR_JUMP_NONE));
2281                                 retval = WM_UI_HANDLER_BREAK;
2282                                 break;
2283                                 
2284                         case AKEY:
2285                                 /* Ctrl + A: Select all */
2286                                 if (event->ctrl && !(event->alt || event->shift || event->oskey)) {
2287                                         ui_textedit_move(but, data, STRCUR_DIR_PREV,
2288                                                          false, STRCUR_JUMP_ALL);
2289                                         ui_textedit_move(but, data, STRCUR_DIR_NEXT,
2290                                                          true, STRCUR_JUMP_ALL);
2291                                         retval = WM_UI_HANDLER_BREAK;
2292                                 }
2293                                 break;
2294
2295                         case TABKEY:
2296                                 /* there is a key conflict here, we can't tab with autocomplete */
2297                                 if (but->autocomplete_func || data->searchbox) {
2298                                         changed = ui_textedit_autocomplete(C, but, data);
2299                                         update = true;  /* do live update for tab key */
2300                                 }
2301                                 /* the hotkey here is not well defined, was G.qual so we check all */
2302                                 else if (event->shift || event->ctrl || event->alt || event->oskey) {
2303                                         ui_textedit_prev_but(block, but, data);
2304                                         button_activate_state(C, but, BUTTON_STATE_EXIT);
2305                                 }
2306                                 else {
2307                                         ui_textedit_next_but(block, but, data);
2308                                         button_activate_state(C, but, BUTTON_STATE_EXIT);
2309                                 }
2310                                 retval = WM_UI_HANDLER_BREAK;
2311                                 break;
2312                 }
2313
2314                 if ((event->ascii || event->utf8_buf[0]) && (retval == WM_UI_HANDLER_CONTINUE)) {
2315                         char ascii = event->ascii;
2316                         const char *utf8_buf = event->utf8_buf;
2317
2318                         /* exception that's useful for number buttons, some keyboard
2319                          * numpads have a comma instead of a period */
2320                         if (ELEM3(but->type, NUM, NUMABS, NUMSLI)) { /* could use data->min*/
2321                                 if (event->type == PADPERIOD && ascii == ',') {
2322                                         ascii = '.';
2323                                         utf8_buf = NULL; /* force ascii fallback */
2324                                 }
2325                         }
2326
2327                         if (utf8_buf && utf8_buf[0]) {
2328                                 int utf8_buf_len = BLI_str_utf8_size(utf8_buf);
2329                                 /* keep this printf until utf8 is well tested */
2330                                 if (utf8_buf_len != 1) {
2331                                         printf("%s: utf8 char '%.*s'\n", __func__, utf8_buf_len, utf8_buf);
2332                                 }
2333
2334                                 // strcpy(utf8_buf, "12345");
2335                                 changed = ui_textedit_type_buf(but, data, event->utf8_buf, utf8_buf_len);
2336                         }
2337                         else {
2338                                 changed = ui_textedit_type_ascii(but, data, ascii);
2339                         }
2340
2341                         retval = WM_UI_HANDLER_BREAK;
2342                         
2343                 }
2344                 /* textbutton with magnifier icon: do live update for search button */
2345                 if (but->icon == ICON_VIEWZOOM)
2346                         update = true;
2347         }
2348
2349         if (changed) {
2350                 /* only update when typing for TAB key */
2351                 if (update && data->interactive) {
2352                         ui_apply_button(C, block, but, data, true);
2353                 }
2354                 else {
2355                         ui_check_but(but);
2356                 }
2357                 but->changed = true;
2358                 
2359                 if (data->searchbox)
2360                         ui_searchbox_update(C, data->searchbox, but, true);  /* true = reset */
2361         }
2362
2363         if (changed || (retval == WM_UI_HANDLER_BREAK))
2364                 ED_region_tag_redraw(data->region);
2365 }
2366
2367 static void ui_do_but_textedit_select(bContext *C, uiBlock *block, uiBut *but, uiHandleButtonData *data, const wmEvent *event)
2368 {
2369         int mx, my, retval = WM_UI_HANDLER_CONTINUE;
2370
2371         switch (event->type) {
2372                 case MOUSEMOVE:
2373                 {
2374                         mx = event->x;
2375                         my = event->y;
2376                         ui_window_to_block(data->region, block, &mx, &my);
2377
2378                         ui_textedit_set_cursor_select(but, data, mx);
2379                         retval = WM_UI_HANDLER_BREAK;
2380                         break;
2381                 }
2382                 case LEFTMOUSE:
2383                         if (event->val == KM_RELEASE)
2384                                 button_activate_state(C, but, BUTTON_STATE_TEXT_EDITING);
2385                         retval = WM_UI_HANDLER_BREAK;
2386                         break;
2387         }
2388
2389         if (retval == WM_UI_HANDLER_BREAK) {
2390                 ui_check_but(but);
2391                 ED_region_tag_redraw(data->region);
2392         }
2393 }
2394
2395 /* ************* number editing for various types ************* */
2396
2397 static void ui_numedit_begin(uiBut *but, uiHandleButtonData *data)
2398 {
2399         if (but->type == BUT_CURVE) {
2400                 but->editcumap = (CurveMapping *)but->poin;
2401         }
2402         else if (but->type == BUT_COLORBAND) {
2403                 data->coba = (ColorBand *)but->poin;
2404                 but->editcoba = data->coba;
2405         }
2406         else if (ELEM4(but->type, BUT_NORMAL, HSVCUBE, HSVCIRCLE, COLOR)) {
2407                 ui_get_but_vectorf(but, data->origvec);
2408                 copy_v3_v3(data->vec, data->origvec);
2409                 but->editvec = data->vec;
2410         }
2411         else {
2412                 float softrange, softmin, softmax;
2413
2414                 data->startvalue = ui_get_but_val(but);
2415                 data->origvalue = data->startvalue;
2416                 data->value = data->origvalue;
2417                 but->editval = &data->value;
2418
2419                 softmin = but->softmin;
2420                 softmax = but->softmax;
2421                 softrange = softmax - softmin;
2422
2423                 data->dragfstart = (softrange == 0.0f) ? 0.0f : ((float)data->value - softmin) / softrange;
2424                 data->dragf = data->dragfstart;
2425         }
2426
2427         data->dragchange = false;
2428         data->draglock = true;
2429 }
2430
2431 static void ui_numedit_end(uiBut *but, uiHandleButtonData *data)
2432 {
2433         but->editval = NULL;
2434         but->editvec = NULL;
2435         but->editcoba = NULL;
2436         but->editcumap = NULL;
2437
2438         data->dragstartx = 0;
2439         data->draglastx = 0;
2440         data->dragchange = false;
2441         data->dragcbd = NULL;
2442         data->dragsel = 0;
2443 }
2444
2445 static void ui_numedit_apply(bContext *C, uiBlock *block, uiBut *but, uiHandleButtonData *data)
2446 {
2447         if (data->interactive) {
2448                 ui_apply_button(C, block, but, data, true);
2449         }
2450         else {
2451                 ui_check_but(but);
2452         }
2453
2454         ED_region_tag_redraw(data->region);
2455 }
2456
2457 /* ****************** menu opening for various types **************** */
2458
2459 static void ui_blockopen_begin(bContext *C, uiBut *but, uiHandleButtonData *data)
2460 {
2461         uiBlockCreateFunc func = NULL;
2462         uiBlockHandleCreateFunc handlefunc = NULL;
2463         uiMenuCreateFunc menufunc = NULL;
2464         char *menustr = NULL;
2465         void *arg = NULL;
2466
2467         switch (but->type) {
2468                 case BLOCK:
2469                 case PULLDOWN:
2470                         if (but->menu_create_func) {
2471                                 menufunc = but->menu_create_func;
2472                                 arg = but->poin;
2473                         }
2474                         else {
2475                                 func = but->block_create_func;
2476                                 arg = but->poin ? but->poin : but->func_argN;
2477                         }
2478                         break;
2479                 case MENU:
2480                         if (but->menu_create_func) {
2481                                 menufunc = but->menu_create_func;
2482                                 arg = but->poin;
2483                         }
2484                         else {
2485                                 data->origvalue = ui_get_but_val(but);
2486                                 data->value = data->origvalue;
2487                                 but->editval = &data->value;
2488
2489                                 menustr = but->str;
2490                         }
2491                         break;
2492                 case ICONROW:
2493                         menufunc = ui_block_func_ICONROW;
2494                         arg = but;
2495                         break;
2496                 case ICONTEXTROW:
2497                         menufunc = ui_block_func_ICONTEXTROW;
2498                         arg = but;
2499                         break;
2500                 case COLOR:
2501                         ui_get_but_vectorf(but, data->origvec);
2502                         copy_v3_v3(data->vec, data->origvec);
2503                         but->editvec = data->vec;
2504
2505                         handlefunc = ui_block_func_COLOR;
2506                         arg = but;
2507                         break;
2508
2509                         /* quiet warnings for unhandled types */
2510                 default:
2511                         break;
2512         }
2513
2514         if (func || handlefunc) {
2515                 data->menu = ui_popup_block_create(C, data->region, but, func, handlefunc, arg);
2516                 if (but->block->handle)
2517                         data->menu->popup = but->block->handle->popup;
2518         }
2519         else if (menufunc || menustr) {
2520                 data->menu = ui_popup_menu_create(C, data->region, but, menufunc, arg, menustr);
2521                 if (but->block->handle)
2522                         data->menu->popup = but->block->handle->popup;
2523         }
2524
2525         /* this makes adjacent blocks auto open from now on */
2526         //if (but->block->auto_open == 0) but->block->auto_open = 1;
2527 }
2528
2529 static void ui_blockopen_end(bContext *C, uiBut *but, uiHandleButtonData *data)
2530 {
2531         if (but) {
2532                 but->editval = NULL;
2533                 but->editvec = NULL;
2534
2535                 but->block->auto_open_last = PIL_check_seconds_timer();
2536         }
2537
2538         if (data->menu) {
2539                 ui_popup_block_free(C, data->menu);
2540                 data->menu = NULL;
2541         }
2542 }
2543
2544 int ui_button_open_menu_direction(uiBut *but)
2545 {
2546         uiHandleButtonData *data = but->active;
2547
2548         if (data && data->menu)
2549                 return data->menu->direction;
2550         
2551         return 0;
2552 }
2553
2554 /* ***************** events for different button types *************** */
2555
2556 static int ui_do_but_BUT(bContext *C, uiBut *but, uiHandleButtonData *data, const wmEvent *event)
2557 {
2558         if (data->state == BUTTON_STATE_HIGHLIGHT) {
2559                 if (event->type == LEFTMOUSE && event->val == KM_PRESS) {
2560                         button_activate_state(C, but, BUTTON_STATE_WAIT_RELEASE);
2561                         return WM_UI_HANDLER_BREAK;
2562                 }
2563                 else if (event->type == LEFTMOUSE && but->block->handle) {
2564                         /* regular buttons will be 'UI_SELECT', menu items 'UI_ACTIVE' */
2565                         if (!(but->flag & (UI_SELECT | UI_ACTIVE)))
2566                                 data->cancel = true;
2567                         button_activate_state(C, but, BUTTON_STATE_EXIT);
2568                         return WM_UI_HANDLER_BREAK;
2569                 }
2570                 else if (ELEM(event->type, PADENTER, RETKEY) && event->val == KM_PRESS) {
2571                         button_activate_state(C, but, BUTTON_STATE_WAIT_FLASH);
2572                         return WM_UI_HANDLER_BREAK;
2573                 }
2574         }
2575         else if (data->state == BUTTON_STATE_WAIT_RELEASE) {
2576                 if (event->type == LEFTMOUSE && event->val != KM_PRESS) {
2577                         if (!(but->flag & UI_SELECT))
2578                                 data->cancel = true;
2579                         button_activate_state(C, but, BUTTON_STATE_EXIT);
2580                         return WM_UI_HANDLER_BREAK;
2581                 }
2582         }
2583
2584         return WM_UI_HANDLER_CONTINUE;
2585 }
2586
2587 static int ui_do_but_HOTKEYEVT(bContext *C, uiBut *but, uiHandleButtonData *data, const wmEvent *event)
2588 {
2589         if (data->state == BUTTON_STATE_HIGHLIGHT) {
2590                 if (ELEM3(event->type, LEFTMOUSE, PADENTER, RETKEY) && event->val == KM_PRESS) {
2591                         but->drawstr[0] = 0;
2592                         but->modifier_key = 0;
2593                         button_activate_state(C, but, BUTTON_STATE_WAIT_KEY_EVENT);
2594                         return WM_UI_HANDLER_BREAK;
2595                 }
2596         }
2597         else if (data->state == BUTTON_STATE_WAIT_KEY_EVENT) {
2598                 
2599                 if (event->type == MOUSEMOVE)
2600                         return WM_UI_HANDLER_CONTINUE;
2601                 
2602                 if (event->type == LEFTMOUSE && event->val == KM_PRESS) {
2603                         /* only cancel if click outside the button */
2604                         if (ui_mouse_inside_button(but->active->region, but, event->x, event->y) == 0) {
2605                                 /* data->cancel doesnt work, this button opens immediate */
2606                                 if (but->flag & UI_BUT_IMMEDIATE)
2607                                         ui_set_but_val(but, 0);
2608                                 else
2609                                         data->cancel = true;
2610                                 button_activate_state(C, but, BUTTON_STATE_EXIT);
2611                                 return WM_UI_HANDLER_BREAK;
2612                         }
2613                 }
2614                 
2615                 /* always set */
2616                 but->modifier_key = 0;
2617                 if (event->shift) but->modifier_key |= KM_SHIFT;
2618                 if (event->alt) but->modifier_key |= KM_ALT;
2619                 if (event->ctrl) but->modifier_key |= KM_CTRL;
2620                 if (event->oskey) but->modifier_key |= KM_OSKEY;
2621
2622                 ui_check_but(but);
2623                 ED_region_tag_redraw(data->region);
2624                         
2625                 if (event->val == KM_PRESS) {
2626                         if (ISHOTKEY(event->type)) {
2627                                 
2628                                 if (WM_key_event_string(event->type)[0])
2629                                         ui_set_but_val(but, event->type);
2630                                 else
2631                                         data->cancel = true;
2632                                 
2633                                 button_activate_state(C, but, BUTTON_STATE_EXIT);
2634                                 return WM_UI_HANDLER_BREAK;
2635                         }
2636                         else if (event->type == ESCKEY) {
2637                                 data->cancel = true;
2638                                 data->escapecancel = true;
2639                                 button_activate_state(C, but, BUTTON_STATE_EXIT);
2640                         }
2641                         
2642                 }
2643         }
2644         
2645         return WM_UI_HANDLER_CONTINUE;
2646 }
2647
2648 static int ui_do_but_KEYEVT(bContext *C, uiBut *but, uiHandleButtonData *data, const wmEvent *event)
2649 {
2650         if (data->state == BUTTON_STATE_HIGHLIGHT) {
2651                 if (ELEM3(event->type, LEFTMOUSE, PADENTER, RETKEY) && event->val == KM_PRESS) {
2652                         button_activate_state(C, but, BUTTON_STATE_WAIT_KEY_EVENT);
2653                         return WM_UI_HANDLER_BREAK;
2654                 }
2655         }
2656         else if (data->state == BUTTON_STATE_WAIT_KEY_EVENT) {
2657                 if (event->type == MOUSEMOVE)
2658                         return WM_UI_HANDLER_CONTINUE;
2659
2660                 if (event->val == KM_PRESS) {
2661                         if (WM_key_event_string(event->type)[0])
2662                                 ui_set_but_val(but, event->type);
2663                         else
2664                                 data->cancel = true;
2665
2666                         button_activate_state(C, but, BUTTON_STATE_EXIT);
2667                 }
2668         }
2669
2670         return WM_UI_HANDLER_CONTINUE;
2671 }
2672
2673 static int ui_do_but_TEX(bContext *C, uiBlock *block, uiBut *but, uiHandleButtonData *data, const wmEvent *event)
2674 {
2675         if (data->state == BUTTON_STATE_HIGHLIGHT) {
2676                 if (ELEM(event->type, LEFTMOUSE, EVT_BUT_OPEN) && event->val == KM_PRESS) {
2677                         if (but->dt == UI_EMBOSSN && !event->ctrl) {
2678                                 /* pass */
2679                         }
2680                         else {
2681                                 button_activate_state(C, but, BUTTON_STATE_TEXT_EDITING);
2682                                 return WM_UI_HANDLER_BREAK;
2683                         }
2684                 }
2685         }
2686         else if (data->state == BUTTON_STATE_TEXT_EDITING) {
2687                 ui_do_but_textedit(C, block, but, data, event);
2688                 return WM_UI_HANDLER_BREAK;
2689         }
2690         else if (data->state == BUTTON_STATE_TEXT_SELECTING) {
2691                 ui_do_but_textedit_select(C, block, but, data, event);
2692                 return WM_UI_HANDLER_BREAK;
2693         }
2694
2695         return WM_UI_HANDLER_CONTINUE;
2696 }
2697
2698 static int ui_do_but_SEARCH_UNLINK(bContext *C, uiBlock *block, uiBut *but, uiHandleButtonData *data, const wmEvent *event)
2699 {
2700         /* unlink icon is on right */
2701         if (ELEM(event->type, LEFTMOUSE, EVT_BUT_OPEN) && event->val == KM_PRESS) {
2702                 ARegion *ar = data->region;
2703                 rcti rect;
2704                 int x = event->x, y = event->y;
2705                 
2706                 ui_window_to_block(ar, but->block, &x, &y);
2707                 
2708                 BLI_rcti_rctf_copy(&rect, &but->rect);
2709                 
2710                 rect.xmin = rect.xmax - (BLI_rcti_size_y(&rect));
2711                 if ( BLI_rcti_isect_pt(&rect, x, y) ) {
2712                         /* most likely NULL, but let's check, and give it temp zero string */
2713                         if (data->str == NULL)
2714                                 data->str = MEM_callocN(16, "temp str");
2715                         data->str[0] = 0;
2716                         
2717                         ui_apply_but_TEX(C, but, data);
2718                         button_activate_state(C, but, BUTTON_STATE_EXIT);
2719                         
2720                         return WM_UI_HANDLER_BREAK;
2721                 }
2722         }
2723         return ui_do_but_TEX(C, block, but, data, event);
2724 }
2725
2726 static int ui_do_but_TOG(bContext *C, uiBut *but, uiHandleButtonData *data, const wmEvent *event)
2727 {
2728 #ifdef USE_DRAG_TOGGLE
2729         if (data->state == BUTTON_STATE_HIGHLIGHT) {
2730                 if (event->type == LEFTMOUSE && event->val == KM_PRESS && ui_is_but_bool(but)) {
2731                         data->togdual = event->ctrl;
2732                         data->togonly = !event->shift;
2733                         ui_apply_button(C, but->block, but, data, true);
2734                         button_activate_state(C, but, BUTTON_STATE_WAIT_DRAG);
2735                         data->dragstartx = event->x;
2736                         data->dragstarty = event->y;
2737                         return WM_UI_HANDLER_BREAK;
2738                 }
2739         }
2740         else if (data->state == BUTTON_STATE_WAIT_DRAG) {
2741                 /* note: the 'BUTTON_STATE_WAIT_DRAG' part of 'ui_do_but_EXIT' could be refactored into its own function */
2742                 data->applied = false;
2743                 return ui_do_but_EXIT(C, but, data, event);
2744         }
2745 #endif
2746         if (data->state == BUTTON_STATE_HIGHLIGHT) {
2747                 if (ELEM3(event->type, LEFTMOUSE, PADENTER, RETKEY) && event->val == KM_PRESS) {
2748                         data->togdual = event->ctrl;
2749                         data->togonly = !event->shift;
2750                         button_activate_state(C, but, BUTTON_STATE_EXIT);
2751                         return WM_UI_HANDLER_BREAK;
2752                 }
2753         }
2754         return WM_UI_HANDLER_CONTINUE;
2755 }
2756
2757 static int ui_do_but_EXIT(bContext *C, uiBut *but, uiHandleButtonData *data, const wmEvent *event)
2758 {
2759         
2760         if (data->state == BUTTON_STATE_HIGHLIGHT) {
2761
2762                 /* first handle click on icondrag type button */
2763                 if (event->type == LEFTMOUSE && but->dragpoin) {
2764                         if (ui_but_mouse_inside_icon(but, data->region, event)) {
2765                                 
2766                                 /* tell the button to wait and keep checking further events to
2767                                  * see if it should start dragging */
2768                                 button_activate_state(C, but, BUTTON_STATE_WAIT_DRAG);
2769                                 data->dragstartx = event->x;
2770                                 data->dragstarty = event->y;
2771                                 return WM_UI_HANDLER_CONTINUE;
2772                         }
2773                 }
2774 #ifdef USE_DRAG_TOGGLE
2775                 if (event->type == LEFTMOUSE && ui_is_but_bool(but)) {
2776                         button_activate_state(C, but, BUTTON_STATE_WAIT_DRAG);
2777                         data->dragstartx = event->x;
2778                         data->dragstarty = event->y;
2779                         return WM_UI_HANDLER_CONTINUE;
2780                 }
2781 #endif
2782
2783                 if (ELEM3(event->type, LEFTMOUSE, PADENTER, RETKEY) && event->val == KM_PRESS) {
2784                         int ret = WM_UI_HANDLER_BREAK;
2785                         /* XXX (a bit ugly) Special case handling for filebrowser drag button */
2786                         if (but->dragpoin && but->imb && ui_but_mouse_inside_icon(but, data->region, event)) {
2787                                 ret = WM_UI_HANDLER_CONTINUE;
2788                         }
2789                         button_activate_state(C, but, BUTTON_STATE_EXIT);
2790                         return ret;
2791                 }
2792         }
2793         else if (data->state == BUTTON_STATE_WAIT_DRAG) {
2794                 
2795                 /* this function also ends state */
2796                 if (ui_but_start_drag(C, but, data, event)) {
2797                         return WM_UI_HANDLER_BREAK;
2798                 }
2799                 
2800                 /* If the mouse has been pressed and released, getting to 
2801                  * this point without triggering a drag, then clear the 
2802                  * drag state for this button and continue to pass on the event */
2803                 if (event->type == LEFTMOUSE && event->val == KM_RELEASE) {
2804                         button_activate_state(C, but, BUTTON_STATE_EXIT);
2805                         return WM_UI_HANDLER_CONTINUE;
2806                 }
2807                 
2808                 /* while waiting for a drag to be triggered, always block 
2809                  * other events from getting handled */
2810                 return WM_UI_HANDLER_BREAK;
2811         }
2812         
2813         return WM_UI_HANDLER_CONTINUE;
2814 }
2815
2816 /* var names match ui_numedit_but_NUM */
2817 static float ui_numedit_apply_snapf(uiBut *but, float tempf, float softmin, float softmax, float softrange, int snap)
2818 {
2819         if (tempf == softmin || tempf == softmax || snap == 0) {
2820                 /* pass */
2821         }
2822         else {
2823                 float fac = 1.0f;
2824                 
2825                 if (ui_is_but_unit(but)) {
2826                         UnitSettings *unit = but->block->unit;
2827                         int unit_type = RNA_SUBTYPE_UNIT_VALUE(uiButGetUnitType(but));
2828
2829                         if (bUnit_IsValid(unit->system, unit_type)) {
2830                                 fac = (float)bUnit_BaseScalar(unit->system, unit_type);
2831                                 if (ELEM3(unit_type, B_UNIT_LENGTH, B_UNIT_AREA, B_UNIT_VOLUME)) {
2832                                         fac /= unit->scale_length;
2833                                 }
2834                         }
2835                 }
2836
2837                 if (fac != 1.0f) {
2838                         /* snap in unit-space */
2839                         tempf /= fac;
2840                         /* softmin /= fac; */ /* UNUSED */
2841                         /* softmax /= fac; */ /* UNUSED */
2842                         softrange /= fac;
2843                 }
2844
2845                 if (snap == 1) {
2846                         if      (softrange < 2.10f) tempf = 0.1f  * floorf(10.0f * tempf);
2847                         else if (softrange < 21.0f) tempf = floorf(tempf);
2848                         else                        tempf = 10.0f * floorf(tempf / 10.0f);
2849                 }
2850                 else if (snap == 2) {
2851                         if      (softrange < 2.10f) tempf = 0.01f * floorf(100.0f * tempf);
2852                         else if (softrange < 21.0f) tempf = 0.1f  * floorf(10.0f * tempf);
2853                         else                        tempf = floor(tempf);
2854                 }
2855                 
2856                 if (fac != 1.0f)
2857                         tempf *= fac;
2858         }
2859
2860         return tempf;
2861 }
2862
2863 static float ui_numedit_apply_snap(int temp, float softmin, float softmax, int snap)
2864 {
2865         if (temp == softmin || temp == softmax)
2866                 return temp;
2867
2868         switch (snap) {
2869                 case 0:
2870                         break;
2871                 case 1:
2872                         temp = 10 * (temp / 10);
2873                         break;
2874                 case 2:
2875                         temp = 100 * (temp / 100);
2876                         break;
2877         }
2878
2879         return temp;
2880 }
2881
2882 static bool ui_numedit_but_NUM(uiBut *but, uiHandleButtonData *data, float fac, int snap, int mx)
2883 {
2884         float deler, tempf, softmin, softmax, softrange;
2885         int lvalue, temp;
2886         bool changed = false;
2887         const bool is_float = ui_is_but_float(but);
2888         
2889         if (mx == data->draglastx)
2890                 return changed;
2891         
2892         /* drag-lock - prevent unwanted scroll adjustments */
2893         /* change value (now 3) to adjust threshold in pixels */
2894         if (data->draglock) {
2895                 if (abs(mx - data->dragstartx) <= 3)
2896                         return changed;
2897
2898                 data->draglock = false;
2899                 data->dragstartx = mx;  /* ignore mouse movement within drag-lock */
2900         }
2901
2902         softmin = but->softmin;
2903         softmax = but->softmax;
2904         softrange = softmax - softmin;
2905
2906         if (ui_is_a_warp_but(but)) {
2907                 /* Mouse location isn't screen clamped to the screen so use a linear mapping
2908                  * 2px == 1-int, or 1px == 1-ClickStep */
2909                 if (is_float) {
2910                         fac *= 0.01f * but->a1;
2911                         tempf = (float)data->startvalue + ((float)(mx - data->dragstartx) * fac);
2912                         tempf = ui_numedit_apply_snapf(but, tempf, softmin, softmax, softrange, snap);
2913
2914 #if 1       /* fake moving the click start, nicer for dragging back after passing the limit */
2915                         if (tempf < softmin) {
2916                                 data->dragstartx -= (softmin - tempf) / fac;
2917                                 tempf = softmin;
2918                         }
2919                         else if (tempf > softmax) {
2920                                 data->dragstartx += (tempf - softmax) / fac;
2921                                 tempf = softmax;
2922                         }
2923 #else
2924                         CLAMP(tempf, softmin, softmax);
2925 #endif
2926
2927                         if (tempf != (float)data->value) {
2928                                 data->dragchange = true;
2929                                 data->value = tempf;
2930                                 changed = true;
2931                         }
2932                 }
2933                 else {