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