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