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