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