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