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