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