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