Fix T58870: submenus don't open for some specific mouse positions.
[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         unsigned int 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         uiBut *but;
1129
1130         BLI_assert(data->multi_data.init == BUTTON_MULTI_INIT_SETUP);
1131         BLI_assert(data->multi_data.has_mbuts);
1132
1133         data->multi_data.bs_mbuts = UI_butstore_create(but_active->block);
1134
1135         for (but = but_active->block->buttons.first; but; but = but->next) {
1136                 if (but->flag & UI_BUT_DRAG_MULTI) {
1137                         ui_multibut_add(data, but);
1138                 }
1139         }
1140
1141         /* edit buttons proportionally to eachother
1142          * note: if we mix buttons which are proportional and others which are not,
1143          * this may work a bit strangely */
1144         if (but_active->rnaprop) {
1145                 if ((data->origvalue != 0.0) && (RNA_property_flag(but_active->rnaprop) & PROP_PROPORTIONAL)) {
1146                         data->multi_data.is_proportional = true;
1147                 }
1148         }
1149 }
1150
1151 static void ui_multibut_states_apply(bContext *C, uiHandleButtonData *data, uiBlock *block)
1152 {
1153         ARegion *ar = data->region;
1154         const double value_delta = data->value - data->origvalue;
1155         const double value_scale = data->multi_data.is_proportional ? (data->value / data->origvalue) : 0.0;
1156         uiBut *but;
1157
1158         BLI_assert(data->multi_data.init == BUTTON_MULTI_INIT_ENABLE);
1159         BLI_assert(data->multi_data.skip == false);
1160
1161         for (but = block->buttons.first; but; but = but->next) {
1162                 if (but->flag & UI_BUT_DRAG_MULTI) {
1163                         /* mbut_states for delta */
1164                         uiButMultiState *mbut_state = ui_multibut_lookup(data, but);
1165
1166                         if (mbut_state) {
1167                                 void *active_back;
1168
1169                                 ui_but_execute_begin(C, ar, but, &active_back);
1170
1171 #ifdef USE_ALLSELECT
1172                                 if (data->select_others.is_enabled) {
1173                                         /* init once! */
1174                                         if (mbut_state->select_others.elems_len == 0) {
1175                                                 ui_selectcontext_begin(C, but, &mbut_state->select_others);
1176                                         }
1177                                         if (mbut_state->select_others.elems_len == 0) {
1178                                                 mbut_state->select_others.elems_len = -1;
1179                                         }
1180                                 }
1181
1182                                 /* needed so we apply the right deltas */
1183                                 but->active->origvalue = mbut_state->origvalue;
1184                                 but->active->select_others = mbut_state->select_others;
1185                                 but->active->select_others.do_free = false;
1186 #endif
1187
1188                                 BLI_assert(active_back == NULL);
1189                                 /* no need to check 'data->state' here */
1190                                 if (data->str) {
1191                                         /* entering text (set all) */
1192                                         but->active->value = data->value;
1193                                         ui_but_string_set(C, but, data->str);
1194                                 }
1195                                 else {
1196                                         /* dragging (use delta) */
1197                                         if (data->multi_data.is_proportional) {
1198                                                 but->active->value = mbut_state->origvalue * value_scale;
1199                                         }
1200                                         else {
1201                                                 but->active->value = mbut_state->origvalue + value_delta;
1202                                         }
1203
1204                                         /* clamp based on soft limits, see: T40154 */
1205                                         CLAMP(but->active->value, (double)but->softmin, (double)but->softmax);
1206                                 }
1207                                 ui_but_execute_end(C, ar, but, active_back);
1208                         }
1209                         else {
1210                                 /* highly unlikely */
1211                                 printf("%s: cant find button\n", __func__);
1212                         }
1213                         /* end */
1214
1215                 }
1216         }
1217 }
1218
1219 #endif  /* USE_DRAG_MULTINUM */
1220
1221
1222 #ifdef USE_DRAG_TOGGLE
1223
1224 /* Helpers that wrap boolean functions, to support different kinds of buttons. */
1225
1226 static bool ui_drag_toggle_but_is_supported(const uiBut *but)
1227 {
1228         if (ui_but_is_bool(but)) {
1229                 return true;
1230         }
1231         else if (UI_but_is_decorator(but)) {
1232                 return ELEM(but->icon, ICON_DECORATE, ICON_DECORATE_KEYFRAME, ICON_DECORATE_ANIMATE, ICON_DECORATE_OVERRIDE);
1233         }
1234         else {
1235                 return false;
1236         }
1237 }
1238
1239 static bool ui_drag_toggle_but_is_pushed(uiBut *but)
1240 {
1241         if (ui_but_is_bool(but)) {
1242                 return ui_but_is_pushed(but);
1243         }
1244         else if (UI_but_is_decorator(but)) {
1245                 return (but->icon == ICON_DECORATE_KEYFRAME);
1246         }
1247         else {
1248                 return false;
1249         }
1250 }
1251
1252 typedef struct uiDragToggleHandle {
1253         /* init */
1254         bool is_set;
1255         float but_cent_start[2];
1256
1257         bool is_xy_lock_init;
1258         bool    xy_lock[2];
1259
1260         int  xy_init[2];
1261         int  xy_last[2];
1262 } uiDragToggleHandle;
1263
1264 static bool ui_drag_toggle_set_xy_xy(
1265         bContext *C, ARegion *ar, const bool is_set,
1266         const int xy_src[2], const int xy_dst[2])
1267 {
1268         /* popups such as layers won't re-evaluate on redraw */
1269         const bool do_check = (ar->regiontype == RGN_TYPE_TEMPORARY);
1270         bool changed = false;
1271         uiBlock *block;
1272
1273         for (block = ar->uiblocks.first; block; block = block->next) {
1274                 uiBut *but;
1275
1276                 float xy_a_block[2] = {UNPACK2(xy_src)};
1277                 float xy_b_block[2] = {UNPACK2(xy_dst)};
1278
1279                 ui_window_to_block_fl(ar, block, &xy_a_block[0], &xy_a_block[1]);
1280                 ui_window_to_block_fl(ar, block, &xy_b_block[0], &xy_b_block[1]);
1281
1282                 for (but = block->buttons.first; but; but = but->next) {
1283                         /* Note: ctrl is always true here because (at least for now) we always want to consider text control
1284                          *       in this case, even when not embossed. */
1285                         if (ui_but_is_interactive(but, true)) {
1286                                 if (BLI_rctf_isect_segment(&but->rect, xy_a_block, xy_b_block)) {
1287
1288                                         /* execute the button */
1289                                         if (ui_drag_toggle_but_is_supported(but)) {
1290                                                 /* is it pressed? */
1291                                                 bool is_set_but = ui_drag_toggle_but_is_pushed(but);
1292                                                 if (is_set_but != is_set) {
1293                                                         UI_but_execute(C, but);
1294                                                         if (do_check) {
1295                                                                 ui_but_update_edited(but);
1296                                                         }
1297                                                         changed = true;
1298                                                 }
1299                                         }
1300                                         /* done */
1301
1302                                 }
1303                         }
1304                 }
1305         }
1306         if (changed) {
1307                 /* apply now, not on release (or if handlers are canceled for whatever reason) */
1308                 ui_apply_but_funcs_after(C);
1309         }
1310
1311         return changed;
1312 }
1313
1314 static void ui_drag_toggle_set(bContext *C, uiDragToggleHandle *drag_info, const int xy_input[2])
1315 {
1316         ARegion *ar = CTX_wm_region(C);
1317         bool do_draw = false;
1318         int xy[2];
1319
1320         /**
1321          * Initialize Locking:
1322          *
1323          * Check if we need to initialize the lock axis by finding if the first
1324          * button we mouse over is X or Y aligned, then lock the mouse to that axis after.
1325          */
1326         if (drag_info->is_xy_lock_init == false) {
1327                 /* first store the buttons original coords */
1328                 uiBut *but = ui_but_find_mouse_over_ex(ar, xy_input[0], xy_input[1], true);
1329
1330                 if (but) {
1331                         if (but->flag & UI_BUT_DRAG_LOCK) {
1332                                 const float but_cent_new[2] = {
1333                                         BLI_rctf_cent_x(&but->rect),
1334                                         BLI_rctf_cent_y(&but->rect),
1335                                 };
1336
1337                                 /* check if this is a different button, chances are high the button wont move about :) */
1338                                 if (len_manhattan_v2v2(drag_info->but_cent_start, but_cent_new) > 1.0f) {
1339                                         if (fabsf(drag_info->but_cent_start[0] - but_cent_new[0]) <
1340                                             fabsf(drag_info->but_cent_start[1] - but_cent_new[1]))
1341                                         {
1342                                                 drag_info->xy_lock[0] = true;
1343                                         }
1344                                         else {
1345                                                 drag_info->xy_lock[1] = true;
1346                                         }
1347                                         drag_info->is_xy_lock_init = true;
1348                                 }
1349                         }
1350                         else {
1351                                 drag_info->is_xy_lock_init = true;
1352                         }
1353                 }
1354         }
1355         /* done with axis locking */
1356
1357
1358         xy[0] = (drag_info->xy_lock[0] == false) ? xy_input[0] : drag_info->xy_last[0];
1359         xy[1] = (drag_info->xy_lock[1] == false) ? xy_input[1] : drag_info->xy_last[1];
1360
1361
1362         /* touch all buttons between last mouse coord and this one */
1363         do_draw = ui_drag_toggle_set_xy_xy(C, ar, drag_info->is_set, drag_info->xy_last, xy);
1364
1365         if (do_draw) {
1366                 ED_region_tag_redraw(ar);
1367         }
1368
1369         copy_v2_v2_int(drag_info->xy_last, xy);
1370 }
1371
1372 static void ui_handler_region_drag_toggle_remove(bContext *UNUSED(C), void *userdata)
1373 {
1374         uiDragToggleHandle *drag_info = userdata;
1375         MEM_freeN(drag_info);
1376 }
1377
1378 static int ui_handler_region_drag_toggle(bContext *C, const wmEvent *event, void *userdata)
1379 {
1380         uiDragToggleHandle *drag_info = userdata;
1381         bool done = false;
1382
1383         switch (event->type) {
1384                 case LEFTMOUSE:
1385                 {
1386                         if (event->val == KM_RELEASE) {
1387                                 done = true;
1388                         }
1389                         break;
1390                 }
1391                 case MOUSEMOVE:
1392                 {
1393                         ui_drag_toggle_set(C, drag_info, &event->x);
1394                         break;
1395                 }
1396         }
1397
1398         if (done) {
1399                 wmWindow *win = CTX_wm_window(C);
1400                 ARegion *ar = CTX_wm_region(C);
1401                 uiBut *but = ui_but_find_mouse_over_ex(ar, drag_info->xy_init[0], drag_info->xy_init[1], true);
1402
1403                 if (but) {
1404                         ui_apply_but_undo(but);
1405                 }
1406
1407                 WM_event_remove_ui_handler(
1408                         &win->modalhandlers,
1409                         ui_handler_region_drag_toggle,
1410                         ui_handler_region_drag_toggle_remove,
1411                         drag_info, false);
1412                 ui_handler_region_drag_toggle_remove(C, drag_info);
1413
1414                 WM_event_add_mousemove(C);
1415                 return WM_UI_HANDLER_BREAK;
1416         }
1417         else {
1418                 return WM_UI_HANDLER_CONTINUE;
1419         }
1420 }
1421
1422 static bool ui_but_is_drag_toggle(const uiBut *but)
1423 {
1424         return ((ui_drag_toggle_but_is_supported(but) == true) &&
1425                 /* menu check is importnt so the button dragged over isn't removed instantly */
1426                 (ui_block_is_menu(but->block) == false));
1427 }
1428
1429 #endif  /* USE_DRAG_TOGGLE */
1430
1431
1432 #ifdef USE_ALLSELECT
1433
1434 static bool ui_selectcontext_begin(
1435         bContext *C, uiBut *but, uiSelectContextStore *selctx_data)
1436 {
1437         PointerRNA ptr, lptr, idptr;
1438         PropertyRNA *prop, *lprop;
1439         bool success = false;
1440         int index;
1441
1442         char *path = NULL;
1443         ListBase lb = {NULL};
1444
1445         ptr = but->rnapoin;
1446         prop = but->rnaprop;
1447         index = but->rnaindex;
1448
1449         /* for now don't support whole colors */
1450         if (index == -1)
1451                 return false;
1452
1453         /* if there is a valid property that is editable... */
1454         if (ptr.data && prop) {
1455                 CollectionPointerLink *link;
1456                 bool use_path_from_id;
1457                 int i;
1458
1459                 /* some facts we want to know */
1460                 const bool is_array = RNA_property_array_check(prop);
1461                 const int rna_type = RNA_property_type(prop);
1462
1463                 if (UI_context_copy_to_selected_list(C, &ptr, prop, &lb, &use_path_from_id, &path) &&
1464                     !BLI_listbase_is_empty(&lb))
1465                 {
1466                         selctx_data->elems_len = BLI_listbase_count(&lb);
1467                         selctx_data->elems = MEM_mallocN(sizeof(uiSelectContextElem) * selctx_data->elems_len, __func__);
1468
1469                         for (i = 0, link = lb.first; i < selctx_data->elems_len; i++, link = link->next) {
1470                                 uiSelectContextElem *other = &selctx_data->elems[i];
1471                                 /* TODO,. de-duplicate copy_to_selected_button */
1472                                 if (link->ptr.data != ptr.data) {
1473                                         if (use_path_from_id) {
1474                                                 /* Path relative to ID. */
1475                                                 lprop = NULL;
1476                                                 RNA_id_pointer_create(link->ptr.id.data, &idptr);
1477                                                 RNA_path_resolve_property(&idptr, path, &lptr, &lprop);
1478                                         }
1479                                         else if (path) {
1480                                                 /* Path relative to elements from list. */
1481                                                 lprop = NULL;
1482                                                 RNA_path_resolve_property(&link->ptr, path, &lptr, &lprop);
1483                                         }
1484                                         else {
1485                                                 lptr = link->ptr;
1486                                                 lprop = prop;
1487                                         }
1488
1489                                         /* lptr might not be the same as link->ptr! */
1490                                         if ((lptr.data != ptr.data) &&
1491                                             (lprop == prop) &&
1492                                             RNA_property_editable(&lptr, lprop))
1493                                         {
1494                                                 other->ptr = lptr;
1495                                                 if (is_array) {
1496                                                         if (rna_type == PROP_FLOAT) {
1497                                                                 other->val_f = RNA_property_float_get_index(&lptr, lprop, index);
1498                                                         }
1499                                                         else if (rna_type == PROP_INT) {
1500                                                                 other->val_i = RNA_property_int_get_index(&lptr, lprop, index);
1501                                                         }
1502                                                         /* ignored for now */
1503 #if 0
1504                                                         else if (rna_type == PROP_BOOLEAN) {
1505                                                                 other->val_b = RNA_property_boolean_get_index(&lptr, lprop, index);
1506                                                         }
1507 #endif
1508                                                 }
1509                                                 else {
1510                                                         if (rna_type == PROP_FLOAT) {
1511                                                                 other->val_f = RNA_property_float_get(&lptr, lprop);
1512                                                         }
1513                                                         else if (rna_type == PROP_INT) {
1514                                                                 other->val_i = RNA_property_int_get(&lptr, lprop);
1515                                                         }
1516                                                         /* ignored for now */
1517 #if 0
1518                                                         else if (rna_type == PROP_BOOLEAN) {
1519                                                                 other->val_b = RNA_property_boolean_get(&lptr, lprop);
1520                                                         }
1521                                                         else if (rna_type == PROP_ENUM) {
1522                                                                 other->val_i = RNA_property_enum_get(&lptr, lprop);
1523                                                         }
1524 #endif
1525                                                 }
1526
1527                                                 continue;
1528                                         }
1529                                 }
1530
1531                                 selctx_data->elems_len -= 1;
1532                                 i -= 1;
1533                         }
1534
1535                         success = (selctx_data->elems_len != 0);
1536                 }
1537         }
1538
1539         if (selctx_data->elems_len == 0) {
1540                 MEM_SAFE_FREE(selctx_data->elems);
1541         }
1542
1543         MEM_SAFE_FREE(path);
1544         BLI_freelistN(&lb);
1545
1546         /* caller can clear */
1547         selctx_data->do_free = true;
1548
1549         if (success) {
1550                 but->flag |= UI_BUT_IS_SELECT_CONTEXT;
1551         }
1552
1553         return success;
1554 }
1555
1556 static void ui_selectcontext_end(
1557         uiBut *but, uiSelectContextStore *selctx_data)
1558 {
1559         if (selctx_data->do_free) {
1560                 if (selctx_data->elems) {
1561                         MEM_freeN(selctx_data->elems);
1562                 }
1563         }
1564
1565         but->flag &= ~UI_BUT_IS_SELECT_CONTEXT;
1566 }
1567
1568 static void ui_selectcontext_apply(
1569         bContext *C, uiBut *but, uiSelectContextStore *selctx_data,
1570         const double value, const double value_orig)
1571 {
1572         if (selctx_data->elems) {
1573                 PropertyRNA *prop = but->rnaprop;
1574                 PropertyRNA *lprop = but->rnaprop;
1575                 int index = but->rnaindex;
1576                 int i;
1577                 const bool use_delta = (selctx_data->is_copy == false);
1578
1579                 union {
1580                         bool  b;
1581                         int   i;
1582                         float f;
1583                         PointerRNA p;
1584                 } delta, min, max;
1585
1586                 const bool is_array = RNA_property_array_check(prop);
1587                 const int rna_type = RNA_property_type(prop);
1588
1589                 if (rna_type == PROP_FLOAT) {
1590                         delta.f = use_delta ? (value - value_orig) : value;
1591                         RNA_property_float_range(&but->rnapoin, prop, &min.f, &max.f);
1592                 }
1593                 else if (rna_type == PROP_INT) {
1594                         delta.i = use_delta ? ((int)value - (int)value_orig) : (int)value;
1595                         RNA_property_int_range(&but->rnapoin, prop, &min.i, &max.i);
1596                 }
1597                 else if (rna_type == PROP_ENUM) {
1598                         delta.i = RNA_property_enum_get(&but->rnapoin, prop);  /* not a delta infact */
1599                 }
1600                 else if (rna_type == PROP_BOOLEAN) {
1601                         if (is_array) {
1602                                 delta.b = RNA_property_boolean_get_index(&but->rnapoin, prop, index);  /* not a delta infact */
1603                         }
1604                         else {
1605                                 delta.b = RNA_property_boolean_get(&but->rnapoin, prop);  /* not a delta infact */
1606                         }
1607                 }
1608                 else if (rna_type == PROP_POINTER) {
1609                         delta.p = RNA_property_pointer_get(&but->rnapoin, prop);  /* not a delta infact */
1610                 }
1611
1612 #ifdef USE_ALLSELECT_LAYER_HACK
1613                 /* make up for not having 'handle_layer_buttons' */
1614                 {
1615                         PropertySubType subtype = RNA_property_subtype(prop);
1616
1617                         if ((rna_type == PROP_BOOLEAN) &&
1618                             ELEM(subtype, PROP_LAYER, PROP_LAYER_MEMBER) &&
1619                             is_array &&
1620                             /* could check for 'handle_layer_buttons' */
1621                             but->func)
1622                         {
1623                                 wmWindow *win = CTX_wm_window(C);
1624                                 if (!win->eventstate->shift) {
1625                                         const int len = RNA_property_array_length(&but->rnapoin, prop);
1626                                         bool *tmparray = MEM_callocN(sizeof(bool) * len, __func__);
1627
1628                                         tmparray[index] = true;
1629
1630                                         for (i = 0; i < selctx_data->elems_len; i++) {
1631                                                 uiSelectContextElem *other = &selctx_data->elems[i];
1632                                                 PointerRNA lptr = other->ptr;
1633                                                 RNA_property_boolean_set_array(&lptr, lprop, tmparray);
1634                                                 RNA_property_update(C, &lptr, lprop);
1635                                         }
1636
1637                                         MEM_freeN(tmparray);
1638
1639                                         return;
1640                                 }
1641                         }
1642                 }
1643 #endif
1644
1645                 for (i = 0; i < selctx_data->elems_len; i++) {
1646                         uiSelectContextElem *other = &selctx_data->elems[i];
1647                         PointerRNA lptr = other->ptr;
1648
1649                         if (rna_type == PROP_FLOAT) {
1650                                 float other_value = use_delta ? (other->val_f + delta.f) : delta.f;
1651                                 CLAMP(other_value, min.f, max.f);
1652                                 if (is_array) {
1653                                         RNA_property_float_set_index(&lptr, lprop, index, other_value);
1654                                 }
1655                                 else {
1656                                         RNA_property_float_set(&lptr, lprop, other_value);
1657                                 }
1658                         }
1659                         else if (rna_type == PROP_INT) {
1660                                 int other_value = use_delta ? (other->val_i + delta.i) : delta.i;
1661                                 CLAMP(other_value, min.i, max.i);
1662                                 if (is_array) {
1663                                         RNA_property_int_set_index(&lptr, lprop, index, other_value);
1664                                 }
1665                                 else {
1666                                         RNA_property_int_set(&lptr, lprop, other_value);
1667                                 }
1668                         }
1669                         else if (rna_type == PROP_BOOLEAN) {
1670                                 const bool other_value = delta.b;
1671                                 if (is_array) {
1672                                         RNA_property_boolean_set_index(&lptr, lprop, index, other_value);
1673                                 }
1674                                 else {
1675                                         RNA_property_boolean_set(&lptr, lprop, delta.b);
1676                                 }
1677                         }
1678                         else if (rna_type == PROP_ENUM) {
1679                                 const int other_value = delta.i;
1680                                 BLI_assert(!is_array);
1681                                 RNA_property_enum_set(&lptr, lprop, other_value);
1682                         }
1683                         else if (rna_type == PROP_POINTER) {
1684                                 const PointerRNA other_value = delta.p;
1685                                 RNA_property_pointer_set(&lptr, lprop, other_value);
1686                         }
1687
1688                         RNA_property_update(C, &lptr, prop);
1689                 }
1690         }
1691 }
1692
1693 #endif  /* USE_ALLSELECT */
1694
1695
1696 static bool ui_but_contains_point_px_icon(uiBut *but, ARegion *ar, const wmEvent *event)
1697 {
1698         rcti rect;
1699         int x = event->x, y = event->y;
1700
1701         ui_window_to_block(ar, but->block, &x, &y);
1702
1703         BLI_rcti_rctf_copy(&rect, &but->rect);
1704
1705         if (but->imb || but->type == UI_BTYPE_COLOR) {
1706                 /* use button size itself */
1707         }
1708         else if (but->drawflag & UI_BUT_ICON_LEFT) {
1709                 rect.xmax = rect.xmin + (BLI_rcti_size_y(&rect));
1710         }
1711         else {
1712                 int delta = BLI_rcti_size_x(&rect) - BLI_rcti_size_y(&rect);
1713                 rect.xmin += delta / 2;
1714                 rect.xmax -= delta / 2;
1715         }
1716
1717         return BLI_rcti_isect_pt(&rect, x, y);
1718 }
1719
1720 static bool ui_but_drag_init(
1721         bContext *C, uiBut *but,
1722         uiHandleButtonData *data, const wmEvent *event)
1723 {
1724         /* prevent other WM gestures to start while we try to drag */
1725         WM_gestures_remove(C);
1726
1727         if (ABS(data->dragstartx - event->x) + ABS(data->dragstarty - event->y) > U.dragthreshold * U.dpi_fac) {
1728
1729                 button_activate_state(C, but, BUTTON_STATE_EXIT);
1730                 data->cancel = true;
1731 #ifdef USE_DRAG_TOGGLE
1732                 if (ui_drag_toggle_but_is_supported(but)) {
1733                         uiDragToggleHandle *drag_info = MEM_callocN(sizeof(*drag_info), __func__);
1734                         ARegion *ar_prev;
1735
1736                         /* call here because regular mouse-up event wont run,
1737                          * typically 'button_activate_exit()' handles this */
1738                         ui_apply_but_autokey(C, but);
1739
1740                         drag_info->is_set = ui_drag_toggle_but_is_pushed(but);
1741                         drag_info->but_cent_start[0] = BLI_rctf_cent_x(&but->rect);
1742                         drag_info->but_cent_start[1] = BLI_rctf_cent_y(&but->rect);
1743                         copy_v2_v2_int(drag_info->xy_init, &event->x);
1744                         copy_v2_v2_int(drag_info->xy_last, &event->x);
1745
1746                         /* needed for toggle drag on popups */
1747                         ar_prev = CTX_wm_region(C);
1748                         CTX_wm_region_set(C, data->region);
1749
1750                         WM_event_add_ui_handler(
1751                                 C, &data->window->modalhandlers,
1752                                 ui_handler_region_drag_toggle,
1753                                 ui_handler_region_drag_toggle_remove,
1754                                 drag_info, WM_HANDLER_BLOCKING);
1755
1756                         CTX_wm_region_set(C, ar_prev);
1757
1758                         /* Initialize alignment for single row/column regions,
1759                          * otherwise we use the relative position of the first other button dragged over. */
1760                         if (ELEM(data->region->regiontype, RGN_TYPE_NAV_BAR, RGN_TYPE_HEADER)) {
1761                                 int lock_axis = -1;
1762                                 if (ELEM(data->region->alignment, RGN_ALIGN_LEFT, RGN_ALIGN_RIGHT)) {
1763                                         lock_axis = 0;
1764                                 }
1765                                 else if (ELEM(data->region->alignment, RGN_ALIGN_TOP, RGN_ALIGN_BOTTOM)) {
1766                                         lock_axis = 1;
1767                                 }
1768                                 if (lock_axis != -1) {
1769                                         drag_info->xy_lock[lock_axis] = true;
1770                                         drag_info->is_xy_lock_init = true;
1771                                 }
1772                         }
1773                 }
1774                 else
1775 #endif
1776                 if (but->type == UI_BTYPE_COLOR) {
1777                         bool valid = false;
1778                         uiDragColorHandle *drag_info = MEM_callocN(sizeof(*drag_info), __func__);
1779
1780                         /* TODO support more button pointer types */
1781                         if (but->rnaprop && RNA_property_subtype(but->rnaprop) == PROP_COLOR_GAMMA) {
1782                                 ui_but_v3_get(but, drag_info->color);
1783                                 drag_info->gamma_corrected = true;
1784                                 valid = true;
1785                         }
1786                         else if (but->rnaprop && RNA_property_subtype(but->rnaprop) == PROP_COLOR) {
1787                                 ui_but_v3_get(but, drag_info->color);
1788                                 drag_info->gamma_corrected = false;
1789                                 valid = true;
1790                         }
1791                         else if (ELEM(but->pointype, UI_BUT_POIN_FLOAT, UI_BUT_POIN_CHAR)) {
1792                                 ui_but_v3_get(but, drag_info->color);
1793                                 copy_v3_v3(drag_info->color, (float *)but->poin);
1794                                 valid = true;
1795                         }
1796
1797                         if (valid) {
1798                                 WM_event_start_drag(C, ICON_COLOR, WM_DRAG_COLOR, drag_info, 0.0, WM_DRAG_FREE_DATA);
1799                         }
1800                         else {
1801                                 MEM_freeN(drag_info);
1802                                 return false;
1803                         }
1804                 }
1805                 else {
1806                         wmDrag *drag = WM_event_start_drag(
1807                                 C, but->icon, but->dragtype, but->dragpoin,
1808                                 ui_but_value_get(but), WM_DRAG_NOP);
1809
1810                         if (but->imb) {
1811                                 WM_event_drag_image(
1812                                         drag, but->imb, but->imb_scale,
1813                                         BLI_rctf_size_x(&but->rect),
1814                                         BLI_rctf_size_y(&but->rect));
1815                         }
1816                 }
1817                 return true;
1818         }
1819
1820         return false;
1821 }
1822
1823 /* ********************** linklines *********************** */
1824
1825 static void ui_apply_but_IMAGE(bContext *C, uiBut *but, uiHandleButtonData *data)
1826 {
1827         ui_apply_but_func(C, but);
1828         data->retval = but->retval;
1829         data->applied = true;
1830 }
1831
1832 static void ui_apply_but_HISTOGRAM(bContext *C, uiBut *but, uiHandleButtonData *data)
1833 {
1834         ui_apply_but_func(C, but);
1835         data->retval = but->retval;
1836         data->applied = true;
1837 }
1838
1839 static void ui_apply_but_WAVEFORM(bContext *C, uiBut *but, uiHandleButtonData *data)
1840 {
1841         ui_apply_but_func(C, but);
1842         data->retval = but->retval;
1843         data->applied = true;
1844 }
1845
1846 static void ui_apply_but_TRACKPREVIEW(bContext *C, uiBut *but, uiHandleButtonData *data)
1847 {
1848         ui_apply_but_func(C, but);
1849         data->retval = but->retval;
1850         data->applied = true;
1851 }
1852
1853
1854 static void ui_apply_but(bContext *C, uiBlock *block, uiBut *but, uiHandleButtonData *data, const bool interactive)
1855 {
1856         char *editstr;
1857         double *editval;
1858         float *editvec;
1859         ColorBand *editcoba;
1860         CurveMapping *editcumap;
1861
1862         data->retval = 0;
1863
1864         /* if we cancel and have not applied yet, there is nothing to do,
1865          * otherwise we have to restore the original value again */
1866         if (data->cancel) {
1867                 if (!data->applied)
1868                         return;
1869
1870                 if (data->str) MEM_freeN(data->str);
1871                 data->str = data->origstr;
1872                 data->origstr = NULL;
1873                 data->value = data->origvalue;
1874                 copy_v3_v3(data->vec, data->origvec);
1875                 /* postpone clearing origdata */
1876         }
1877         else {
1878                 /* we avoid applying interactive edits a second time
1879                  * at the end with the appliedinteractive flag */
1880                 if (interactive) {
1881                         data->applied_interactive = true;
1882                 }
1883                 else if (data->applied_interactive) {
1884                         return;
1885                 }
1886
1887 #ifdef USE_ALLSELECT
1888 #  ifdef USE_DRAG_MULTINUM
1889                 if (but->flag & UI_BUT_DRAG_MULTI) {
1890                         /* pass */
1891                 }
1892                 else
1893 #  endif
1894                 if (data->select_others.elems_len == 0) {
1895                         wmWindow *win = CTX_wm_window(C);
1896                         /* may have been enabled before activating */
1897                         if (data->select_others.is_enabled || IS_ALLSELECT_EVENT(win->eventstate)) {
1898                                 ui_selectcontext_begin(C, but, &data->select_others);
1899                                 data->select_others.is_enabled = true;
1900                         }
1901                 }
1902                 if (data->select_others.elems_len == 0) {
1903                         /* dont check again */
1904                         data->select_others.elems_len = -1;
1905                 }
1906 #endif
1907         }
1908
1909         /* ensures we are writing actual values */
1910         editstr = but->editstr;
1911         editval = but->editval;
1912         editvec = but->editvec;
1913         editcoba = but->editcoba;
1914         editcumap = but->editcumap;
1915         but->editstr = NULL;
1916         but->editval = NULL;
1917         but->editvec = NULL;
1918         but->editcoba = NULL;
1919         but->editcumap = NULL;
1920
1921         /* handle different types */
1922         switch (but->type) {
1923                 case UI_BTYPE_BUT:
1924                         ui_apply_but_BUT(C, but, data);
1925                         break;
1926                 case UI_BTYPE_TEXT:
1927                 case UI_BTYPE_SEARCH_MENU:
1928                         ui_apply_but_TEX(C, but, data);
1929                         break;
1930                 case UI_BTYPE_BUT_TOGGLE:
1931                 case UI_BTYPE_TOGGLE:
1932                 case UI_BTYPE_TOGGLE_N:
1933                 case UI_BTYPE_ICON_TOGGLE:
1934                 case UI_BTYPE_ICON_TOGGLE_N:
1935                 case UI_BTYPE_CHECKBOX:
1936                 case UI_BTYPE_CHECKBOX_N:
1937                         ui_apply_but_TOG(C, but, data);
1938                         break;
1939                 case UI_BTYPE_ROW:
1940                 case UI_BTYPE_LISTROW:
1941                         ui_apply_but_ROW(C, block, but, data);
1942                         break;
1943                 case UI_BTYPE_TAB:
1944                         ui_apply_but_TAB(C, but, data);
1945                         break;
1946                 case UI_BTYPE_SCROLL:
1947                 case UI_BTYPE_GRIP:
1948                 case UI_BTYPE_NUM:
1949                 case UI_BTYPE_NUM_SLIDER:
1950                         ui_apply_but_NUM(C, but, data);
1951                         break;
1952                 case UI_BTYPE_MENU:
1953                 case UI_BTYPE_BLOCK:
1954                 case UI_BTYPE_PULLDOWN:
1955                         ui_apply_but_BLOCK(C, but, data);
1956                         break;
1957                 case UI_BTYPE_COLOR:
1958                         if (data->cancel)
1959                                 ui_apply_but_VEC(C, but, data);
1960                         else
1961                                 ui_apply_but_BLOCK(C, but, data);
1962                         break;
1963                 case UI_BTYPE_BUT_MENU:
1964                         ui_apply_but_BUTM(C, but, data);
1965                         break;
1966                 case UI_BTYPE_UNITVEC:
1967                 case UI_BTYPE_HSVCUBE:
1968                 case UI_BTYPE_HSVCIRCLE:
1969                         ui_apply_but_VEC(C, but, data);
1970                         break;
1971                 case UI_BTYPE_COLORBAND:
1972                         ui_apply_but_COLORBAND(C, but, data);
1973                         break;
1974                 case UI_BTYPE_CURVE:
1975                         ui_apply_but_CURVE(C, but, data);
1976                         break;
1977                 case UI_BTYPE_KEY_EVENT:
1978                 case UI_BTYPE_HOTKEY_EVENT:
1979                         ui_apply_but_BUT(C, but, data);
1980                         break;
1981                 case UI_BTYPE_IMAGE:
1982                         ui_apply_but_IMAGE(C, but, data);
1983                         break;
1984                 case UI_BTYPE_HISTOGRAM:
1985                         ui_apply_but_HISTOGRAM(C, but, data);
1986                         break;
1987                 case UI_BTYPE_WAVEFORM:
1988                         ui_apply_but_WAVEFORM(C, but, data);
1989                         break;
1990                 case UI_BTYPE_TRACK_PREVIEW:
1991                         ui_apply_but_TRACKPREVIEW(C, but, data);
1992                         break;
1993                 default:
1994                         break;
1995         }
1996
1997 #ifdef USE_DRAG_MULTINUM
1998         if (data->multi_data.has_mbuts) {
1999                 if ((data->multi_data.init == BUTTON_MULTI_INIT_ENABLE) &&
2000                     (data->multi_data.skip == false))
2001                 {
2002                         if (data->cancel) {
2003                                 ui_multibut_restore(C, data, block);
2004                         }
2005                         else {
2006                                 ui_multibut_states_apply(C, data, block);
2007                         }
2008                 }
2009         }
2010 #endif
2011
2012 #ifdef USE_ALLSELECT
2013         ui_selectcontext_apply(C, but, &data->select_others, data->value, data->origvalue);
2014 #endif
2015
2016         if (data->cancel) {
2017                 data->origvalue = 0.0;
2018                 zero_v3(data->origvec);
2019         }
2020
2021         but->editstr = editstr;
2022         but->editval = editval;
2023         but->editvec = editvec;
2024         but->editcoba = editcoba;
2025         but->editcumap = editcumap;
2026 }
2027
2028 /* ******************* drop event ********************  */
2029
2030 /* only call if event type is EVT_DROP */
2031 static void ui_but_drop(bContext *C, const wmEvent *event, uiBut *but, uiHandleButtonData *data)
2032 {
2033         wmDrag *wmd;
2034         ListBase *drags = event->customdata; /* drop event type has listbase customdata by default */
2035
2036         for (wmd = drags->first; wmd; wmd = wmd->next) {
2037                 if (wmd->type == WM_DRAG_ID) {
2038                         /* align these types with UI_but_active_drop_name */
2039                         if (ELEM(but->type, UI_BTYPE_TEXT, UI_BTYPE_SEARCH_MENU)) {
2040                                 ID *id = WM_drag_ID(wmd, 0);
2041
2042                                 button_activate_state(C, but, BUTTON_STATE_TEXT_EDITING);
2043
2044                                 ui_textedit_string_set(but, data, id->name + 2);
2045
2046                                 if (ELEM(but->type, UI_BTYPE_SEARCH_MENU)) {
2047                                         but->changed = true;
2048                                         ui_searchbox_update(C, data->searchbox, but, true);
2049                                 }
2050
2051                                 button_activate_state(C, but, BUTTON_STATE_EXIT);
2052                         }
2053                 }
2054         }
2055
2056 }
2057
2058 /* ******************* copy and paste ********************  */
2059
2060 static bool ui_but_contains_password(uiBut *but)
2061 {
2062         return but->rnaprop && (RNA_property_subtype(but->rnaprop) == PROP_PASSWORD);
2063 }
2064
2065 static void ui_but_get_pasted_text_from_clipboard(char **buf_paste, int *buf_len)
2066 {
2067         char *text;
2068         int length;
2069         /* get only first line even if the clipboard contains multiple lines */
2070         text = WM_clipboard_text_get_firstline(false, &length);
2071
2072         if (text) {
2073                 *buf_paste = text;
2074                 *buf_len = length;
2075         }
2076         else {
2077                 *buf_paste = MEM_callocN(sizeof(char), __func__);
2078                 *buf_len = 0;
2079         }
2080 }
2081
2082 static int get_but_property_array_length(uiBut *but)
2083 {
2084         return RNA_property_array_length(&but->rnapoin, but->rnaprop);
2085 }
2086
2087 static void ui_but_set_float_array(bContext *C, uiBut *but, uiHandleButtonData *data, float *values, int array_length)
2088 {
2089         button_activate_state(C, but, BUTTON_STATE_NUM_EDITING);
2090
2091         for (int i = 0; i < array_length; i++) {
2092                 RNA_property_float_set_index(&but->rnapoin, but->rnaprop, i, values[i]);
2093         }
2094         if (data) data->value = values[but->rnaindex];
2095
2096         button_activate_state(C, but, BUTTON_STATE_EXIT);
2097 }
2098
2099 static void float_array_to_string(float *values, int array_length, char *output, int output_len_max)
2100 {
2101         /* to avoid buffer overflow attacks; numbers are quite arbitrary */
2102         BLI_assert(output_len_max > 15);
2103         output_len_max -= 10;
2104
2105         int current_index = 0;
2106         output[current_index] = '[';
2107         current_index++;
2108
2109         for (int i = 0; i < array_length; i++) {
2110                 int length = BLI_snprintf(output + current_index, output_len_max - current_index, "%f", values[i]);
2111                 current_index += length;
2112
2113                 if (i < array_length - 1) {
2114                         if (current_index < output_len_max) {
2115                                 output[current_index + 0] = ',';
2116                                 output[current_index + 1] = ' ';
2117                                 current_index += 2;
2118                         }
2119                 }
2120         }
2121
2122         output[current_index + 0] = ']';
2123         output[current_index + 1] = '\0';
2124 }
2125
2126 static void ui_but_copy_numeric_array(uiBut *but, char *output, int output_len_max)
2127 {
2128         int array_length = get_but_property_array_length(but);
2129         float *values = alloca(array_length * sizeof(float));
2130         RNA_property_float_get_array(&but->rnapoin, but->rnaprop, values);
2131         float_array_to_string(values, array_length, output, output_len_max);
2132 }
2133
2134 static bool parse_float_array(char *text, float *values, int expected_length)
2135 {
2136         /* can parse max 4 floats for now */
2137         BLI_assert(0 <= expected_length && expected_length <= 4);
2138
2139         float v[5];
2140         int actual_length = sscanf(text, "[%f, %f, %f, %f, %f]", &v[0], &v[1], &v[2], &v[3], &v[4]);
2141
2142         if (actual_length == expected_length) {
2143                 memcpy(values, v, sizeof(float) * expected_length);
2144                 return true;
2145         }
2146         else {
2147                 return false;
2148         }
2149 }
2150
2151 static void ui_but_paste_numeric_array(bContext *C, uiBut *but, uiHandleButtonData *data, char *buf_paste)
2152 {
2153         int array_length = get_but_property_array_length(but);
2154         if (array_length > 4) {
2155                 // not supported for now
2156                 return;
2157         }
2158
2159         float *values = alloca(sizeof(float) * array_length);
2160
2161         if (parse_float_array(buf_paste, values, array_length)) {
2162                 ui_but_set_float_array(C, but, data, values, array_length);
2163         }
2164         else {
2165                 WM_report(RPT_ERROR, "Expected an array of numbers: [n, n, ...]");
2166         }
2167 }
2168
2169 static void ui_but_copy_numeric_value(uiBut *but, char *output, int output_len_max)
2170 {
2171         /* Get many decimal places, then strip trailing zeros.
2172          * note: too high values start to give strange results */
2173         ui_but_string_get_ex(but, output, output_len_max, UI_PRECISION_FLOAT_MAX, false, NULL);
2174         BLI_str_rstrip_float_zero(output, '\0');
2175 }
2176
2177 static void ui_but_paste_numeric_value(bContext *C, uiBut *but, uiHandleButtonData *data, char *buf_paste)
2178 {
2179         double value;
2180
2181         if (ui_but_string_set_eval_num(C, but, buf_paste, &value)) {
2182                 button_activate_state(C, but, BUTTON_STATE_NUM_EDITING);
2183                 data->value = value;
2184                 ui_but_string_set(C, but, buf_paste);
2185                 button_activate_state(C, but, BUTTON_STATE_EXIT);
2186         }
2187         else {
2188                 WM_report(RPT_ERROR, "Expected a number");
2189         }
2190 }
2191
2192 static bool ui_but_has_array_value(uiBut *but)
2193 {
2194         return (but->rnapoin.data && but->rnaprop &&
2195                 ELEM(RNA_property_subtype(but->rnaprop), PROP_COLOR, PROP_TRANSLATION, PROP_DIRECTION,
2196                      PROP_VELOCITY, PROP_ACCELERATION, PROP_MATRIX, PROP_EULER, PROP_QUATERNION, PROP_AXISANGLE,
2197                      PROP_XYZ, PROP_XYZ_LENGTH, PROP_COLOR_GAMMA, PROP_COORDS));
2198 }
2199
2200 static void ui_but_paste_normalized_vector(bContext *C, uiBut *but, char *buf_paste)
2201 {
2202         float xyz[3];
2203         if (parse_float_array(buf_paste, xyz, 3)) {
2204                 if (normalize_v3(xyz) == 0.0f) {
2205                         /* better set Z up then have a zero vector */
2206                         xyz[2] = 1.0;
2207                 }
2208                 ui_but_set_float_array(C, but, NULL, xyz, 3);
2209         }
2210         else {
2211                 WM_report(RPT_ERROR, "Paste expected 3 numbers, formatted: '[n, n, n]'");
2212         }
2213 }
2214
2215 static void ui_but_copy_color(uiBut *but, char *output, int output_len_max)
2216 {
2217         float rgba[4];
2218
2219         if (but->rnaprop && get_but_property_array_length(but) == 4)
2220                 rgba[3] = RNA_property_float_get_index(&but->rnapoin, but->rnaprop, 3);
2221         else
2222                 rgba[3] = 1.0f;
2223
2224         ui_but_v3_get(but, rgba);
2225
2226         /* convert to linear color to do compatible copy between gamma and non-gamma */
2227         if (but->rnaprop && RNA_property_subtype(but->rnaprop) == PROP_COLOR_GAMMA)
2228                 srgb_to_linearrgb_v3_v3(rgba, rgba);
2229
2230         float_array_to_string(rgba, 4, output, output_len_max);
2231 }
2232
2233 static void ui_but_paste_color(bContext *C, uiBut *but, char *buf_paste)
2234 {
2235         float rgba[4];
2236         if (parse_float_array(buf_paste, rgba, 4)) {
2237                 if (but->rnaprop) {
2238                         /* Assume linear colors in buffer. */
2239                         if (RNA_property_subtype(but->rnaprop) == PROP_COLOR_GAMMA) {
2240                                 linearrgb_to_srgb_v3_v3(rgba, rgba);
2241                         }
2242
2243                         /* Some color properties are RGB, not RGBA. */
2244                         int array_len = get_but_property_array_length(but);
2245                         BLI_assert(ELEM(array_len, 3, 4));
2246                         ui_but_set_float_array(C, but, NULL, rgba, array_len);
2247                 }
2248         }
2249         else {
2250                 WM_report(RPT_ERROR, "Paste expected 4 numbers, formatted: '[n, n, n, n]'");
2251         }
2252 }
2253
2254 static void ui_but_copy_text(uiBut *but, char *output, int output_len_max)
2255 {
2256         ui_but_string_get(but, output, output_len_max);
2257 }
2258
2259 static void ui_but_paste_text(bContext *C, uiBut *but, uiHandleButtonData *data, char *buf_paste)
2260 {
2261         button_activate_state(C, but, BUTTON_STATE_TEXT_EDITING);
2262         ui_textedit_string_set(but, but->active, buf_paste);
2263
2264         if (but->type == UI_BTYPE_SEARCH_MENU) {
2265                 but->changed = true;
2266                 ui_searchbox_update(C, data->searchbox, but, true);
2267         }
2268
2269         button_activate_state(C, but, BUTTON_STATE_EXIT);
2270 }
2271
2272 static void ui_but_copy_colorband(uiBut *but)
2273 {
2274         if (but->poin != NULL) {
2275                 memcpy(&but_copypaste_coba, but->poin, sizeof(ColorBand));
2276         }
2277 }
2278
2279 static void ui_but_paste_colorband(bContext *C, uiBut *but, uiHandleButtonData *data)
2280 {
2281         if (but_copypaste_coba.tot != 0) {
2282                 if (!but->poin)
2283                         but->poin = MEM_callocN(sizeof(ColorBand), "colorband");
2284
2285                 button_activate_state(C, but, BUTTON_STATE_NUM_EDITING);
2286                 memcpy(data->coba, &but_copypaste_coba, sizeof(ColorBand));
2287                 button_activate_state(C, but, BUTTON_STATE_EXIT);
2288         }
2289 }
2290
2291 static void ui_but_copy_curvemapping(uiBut *but)
2292 {
2293         if (but->poin != NULL) {
2294                 but_copypaste_curve_alive = true;
2295                 curvemapping_free_data(&but_copypaste_curve);
2296                 curvemapping_copy_data(&but_copypaste_curve, (CurveMapping *) but->poin);
2297         }
2298 }
2299
2300 static void ui_but_paste_curvemapping(bContext *C, uiBut *but)
2301 {
2302         if (but_copypaste_curve_alive) {
2303                 if (!but->poin)
2304                         but->poin = MEM_callocN(sizeof(CurveMapping), "curvemapping");
2305
2306                 button_activate_state(C, but, BUTTON_STATE_NUM_EDITING);
2307                 curvemapping_free_data((CurveMapping *) but->poin);
2308                 curvemapping_copy_data((CurveMapping *) but->poin, &but_copypaste_curve);
2309                 button_activate_state(C, but, BUTTON_STATE_EXIT);
2310         }
2311 }
2312
2313 static void ui_but_copy_operator(bContext *C, uiBut *but, char *output, int output_len_max)
2314 {
2315         PointerRNA *opptr;
2316         opptr = UI_but_operator_ptr_get(but);
2317
2318         char *str;
2319         str = WM_operator_pystring_ex(C, NULL, false, true, but->optype, opptr);
2320         BLI_strncpy(output, str, output_len_max);
2321         MEM_freeN(str);
2322 }
2323
2324 static void ui_but_copy_menu(uiBut *but, char *output, int output_len_max)
2325 {
2326         MenuType *mt = UI_but_menutype_get(but);
2327         if (mt) {
2328                 BLI_snprintf(output, output_len_max, "bpy.ops.wm.call_menu(name=\"%s\")", mt->idname);
2329         }
2330 }
2331
2332 static void ui_but_copy(bContext *C, uiBut *but, const bool copy_array)
2333 {
2334         if (ui_but_contains_password(but)) {
2335                 return;
2336         }
2337
2338         /* Arbitrary large value (allow for paths: 'PATH_MAX') */
2339         char buf[4096] = {0};
2340         const int buf_max_len = sizeof(buf);
2341
2342         /* Left false for copying internal data (color-band for eg). */
2343         bool is_buf_set = false;
2344
2345         bool has_required_data = !(but->poin == NULL && but->rnapoin.data == NULL);
2346
2347         switch (but->type) {
2348                 case UI_BTYPE_NUM:
2349                 case UI_BTYPE_NUM_SLIDER:
2350                         if (!has_required_data) break;
2351                         if (copy_array && ui_but_has_array_value(but)) {
2352                                 ui_but_copy_numeric_array(but, buf, buf_max_len);
2353                         }
2354                         else {
2355                                 ui_but_copy_numeric_value(but, buf, buf_max_len);
2356                         }
2357                         is_buf_set = true;
2358                         break;
2359
2360                 case UI_BTYPE_UNITVEC:
2361                         if (!has_required_data) break;
2362                         ui_but_copy_numeric_array(but, buf, buf_max_len);
2363                         is_buf_set = true;
2364                         break;
2365
2366                 case UI_BTYPE_COLOR:
2367                         if (!has_required_data) break;
2368                         ui_but_copy_color(but, buf, buf_max_len);
2369                         is_buf_set = true;
2370                         break;
2371
2372                 case UI_BTYPE_TEXT:
2373                 case UI_BTYPE_SEARCH_MENU:
2374                         if (!has_required_data) break;
2375                         ui_but_copy_text(but, buf, buf_max_len);
2376                         is_buf_set = true;
2377                         break;
2378
2379                 case UI_BTYPE_COLORBAND:
2380                         ui_but_copy_colorband(but);
2381                         break;
2382
2383                 case UI_BTYPE_CURVE:
2384                         ui_but_copy_curvemapping(but);
2385                         break;
2386
2387                 case UI_BTYPE_BUT:
2388                         ui_but_copy_operator(C, but, buf, buf_max_len);
2389                         is_buf_set = true;
2390                         break;
2391
2392                 case UI_BTYPE_MENU:
2393                 case UI_BTYPE_PULLDOWN:
2394                         ui_but_copy_menu(but, buf, buf_max_len);
2395                         is_buf_set = true;
2396                         break;
2397
2398                 default:
2399                         break;
2400         }
2401
2402         if (is_buf_set) {
2403                 WM_clipboard_text_set(buf, 0);
2404         }
2405 }
2406
2407 static void ui_but_paste(bContext *C, uiBut *but, uiHandleButtonData *data, const bool paste_array)
2408 {
2409         BLI_assert((but->flag & UI_BUT_DISABLED) == 0); /* caller should check */
2410
2411         int buf_paste_len = 0;
2412         char *buf_paste;
2413         ui_but_get_pasted_text_from_clipboard(&buf_paste, &buf_paste_len);
2414
2415         bool has_required_data = !(but->poin == NULL && but->rnapoin.data == NULL);
2416
2417         switch (but->type) {
2418                 case UI_BTYPE_NUM:
2419                 case UI_BTYPE_NUM_SLIDER:
2420                         if (!has_required_data) break;
2421                         if (paste_array && ui_but_has_array_value(but)) {
2422                                 ui_but_paste_numeric_array(C, but, data, buf_paste);
2423                         }
2424                         else {
2425                                 ui_but_paste_numeric_value(C, but, data, buf_paste);
2426                         }
2427                         break;
2428
2429                 case UI_BTYPE_UNITVEC:
2430                         if (!has_required_data) break;
2431                         ui_but_paste_normalized_vector(C, but, buf_paste);
2432                         break;
2433
2434                 case UI_BTYPE_COLOR:
2435                         if (!has_required_data) break;
2436                         ui_but_paste_color(C, but, buf_paste);
2437                         break;
2438
2439                 case UI_BTYPE_TEXT:
2440                 case UI_BTYPE_SEARCH_MENU:
2441                         if (!has_required_data) break;
2442                         ui_but_paste_text(C, but, data, buf_paste);
2443                         break;
2444
2445                 case UI_BTYPE_COLORBAND:
2446                         ui_but_paste_colorband(C, but, data);
2447                         break;
2448
2449                 case UI_BTYPE_CURVE:
2450                         ui_but_paste_curvemapping(C, but);
2451                         break;
2452
2453                 default:
2454                         break;
2455         }
2456
2457         MEM_freeN((void *)buf_paste);
2458 }
2459
2460 /**
2461  * Password Text
2462  * =============
2463  *
2464  * Functions to convert password strings that should not be displayed
2465  * to asterisk representation (e.g. 'mysecretpasswd' -> '*************')
2466  *
2467  * It converts every UTF-8 character to an asterisk, and also remaps
2468  * the cursor position and selection start/end.
2469  *
2470  * \note: remapping is used, because password could contain UTF-8 characters.
2471  *
2472  */
2473
2474 static int ui_text_position_from_hidden(uiBut *but, int pos)
2475 {
2476         const char *strpos, *butstr;
2477         int i;
2478
2479         butstr = (but->editstr) ? but->editstr : but->drawstr;
2480
2481         for (i = 0, strpos = butstr; i < pos; i++)
2482                 strpos = BLI_str_find_next_char_utf8(strpos, NULL);
2483
2484         return (strpos - butstr);
2485 }
2486
2487 static int ui_text_position_to_hidden(uiBut *but, int pos)
2488 {
2489         const char *butstr = (but->editstr) ? but->editstr : but->drawstr;
2490         return BLI_strnlen_utf8(butstr, pos);
2491 }
2492
2493 void ui_but_text_password_hide(char password_str[UI_MAX_PASSWORD_STR], uiBut *but, const bool restore)
2494 {
2495         char *butstr;
2496
2497         if (!(but->rnaprop && RNA_property_subtype(but->rnaprop) == PROP_PASSWORD))
2498                 return;
2499
2500         butstr = (but->editstr) ? but->editstr : but->drawstr;
2501
2502         if (restore) {
2503                 /* restore original string */
2504                 BLI_strncpy(butstr, password_str, UI_MAX_PASSWORD_STR);
2505
2506                 /* remap cursor positions */
2507                 if (but->pos >= 0) {
2508                         but->pos = ui_text_position_from_hidden(but, but->pos);
2509                         but->selsta = ui_text_position_from_hidden(but, but->selsta);
2510                         but->selend = ui_text_position_from_hidden(but, but->selend);
2511                 }
2512         }
2513         else {
2514                 /* convert text to hidden text using asterisks (e.g. pass -> ****) */
2515                 const size_t len = BLI_strlen_utf8(butstr);
2516
2517                 /* remap cursor positions */
2518                 if (but->pos >= 0) {
2519                         but->pos = ui_text_position_to_hidden(but, but->pos);
2520                         but->selsta = ui_text_position_to_hidden(but, but->selsta);
2521                         but->selend = ui_text_position_to_hidden(but, but->selend);
2522                 }
2523
2524                 /* save original string */
2525                 BLI_strncpy(password_str, butstr, UI_MAX_PASSWORD_STR);
2526                 memset(butstr, '*', len);
2527                 butstr[len] = '\0';
2528         }
2529 }
2530
2531 static void ui_but_text_clear(bContext *C, uiBut *but, uiHandleButtonData *data)
2532 {
2533         /* most likely NULL, but let's check, and give it temp zero string */
2534         if (!data->str) {
2535                 data->str = MEM_callocN(1, "temp str");
2536         }
2537         data->str[0] = 0;
2538
2539         ui_apply_but_TEX(C, but, data);
2540         button_activate_state(C, but, BUTTON_STATE_EXIT);
2541 }
2542
2543
2544 /* ************* in-button text selection/editing ************* */
2545
2546 static void ui_textedit_string_ensure_max_length(uiBut *but, uiHandleButtonData *data, int maxlen)
2547 {
2548         BLI_assert(data->is_str_dynamic);
2549         BLI_assert(data->str == but->editstr);
2550
2551         if (maxlen > data->maxlen) {
2552                 data->str = but->editstr = MEM_reallocN(data->str, sizeof(char) * maxlen);
2553                 data->maxlen = maxlen;
2554         }
2555 }
2556
2557 static void ui_textedit_string_set(uiBut *but, uiHandleButtonData *data, const char *str)
2558 {
2559         if (data->is_str_dynamic) {
2560                 ui_textedit_string_ensure_max_length(but, data, strlen(str) + 1);
2561         }
2562
2563         if (ui_but_is_utf8(but)) {
2564                 BLI_strncpy_utf8(data->str, str, data->maxlen);
2565         }
2566         else {
2567                 BLI_strncpy(data->str, str, data->maxlen);
2568         }
2569 }
2570
2571
2572 static bool ui_textedit_delete_selection(uiBut *but, uiHandleButtonData *data)
2573 {
2574         char *str = data->str;
2575         const int len = strlen(str);
2576         bool changed = false;
2577         if (but->selsta != but->selend && len) {
2578                 memmove(str + but->selsta, str + but->selend, (len - but->selend) + 1);
2579                 changed = true;
2580         }
2581
2582         but->pos = but->selend = but->selsta;
2583         return changed;
2584 }
2585
2586 /**
2587  * \param x: Screen space cursor location - #wmEvent.x
2588  *
2589  * \note ``but->block->aspect`` is used here, so drawing button style is getting scaled too.
2590  */
2591 static void ui_textedit_set_cursor_pos(uiBut *but, uiHandleButtonData *data, const float x)
2592 {
2593         uiStyle *style = UI_style_get();  // XXX pass on as arg
2594         uiFontStyle *fstyle = &style->widget;
2595         const float aspect = but->block->aspect;
2596         const short fstyle_points_prev = fstyle->points;
2597
2598         float startx = but->rect.xmin;
2599         float starty_dummy = 0.0f;
2600         char password_str[UI_MAX_PASSWORD_STR];
2601         /* treat 'str_last' as null terminator for str, no need to modify in-place */
2602         const char *str = but->editstr, *str_last;
2603
2604         ui_block_to_window_fl(data->region, but->block, &startx, &starty_dummy);
2605
2606         ui_fontscale(&fstyle->points, aspect);
2607
2608         UI_fontstyle_set(fstyle);
2609
2610         if (fstyle->kerning == 1) /* for BLF_width */
2611                 BLF_enable(fstyle->uifont_id, BLF_KERNING_DEFAULT);
2612
2613         ui_but_text_password_hide(password_str, but, false);
2614
2615         if (ELEM(but->type, UI_BTYPE_TEXT, UI_BTYPE_SEARCH_MENU)) {
2616                 if (but->flag & UI_HAS_ICON) {
2617                         startx += UI_DPI_ICON_SIZE / aspect;
2618                 }
2619         }
2620         /* but this extra .05 makes clicks inbetween characters feel nicer */
2621         startx += ((UI_TEXT_MARGIN_X + 0.05f) * U.widget_unit) / aspect;
2622
2623         /* mouse dragged outside the widget to the left */
2624         if (x < startx) {
2625                 int i = but->ofs;
2626
2627                 str_last = &str[but->ofs];
2628
2629                 while (i > 0) {
2630                         if (BLI_str_cursor_step_prev_utf8(str, but->ofs, &i)) {
2631                                 /* 0.25 == scale factor for less sensitivity */
2632                                 if (BLF_width(fstyle->uifont_id, str + i, (str_last - str) - i) > (startx - x) * 0.25f) {
2633                                         break;
2634                                 }
2635                         }
2636                         else {
2637                                 break; /* unlikely but possible */
2638                         }
2639                 }
2640                 but->ofs = i;
2641                 but->pos = but->ofs;
2642         }
2643         /* mouse inside the widget, mouse coords mapped in widget space */
2644         else {  /* (x >= startx) */
2645                 int pos_i;
2646
2647                 /* keep track of previous distance from the cursor to the char */
2648                 float cdist, cdist_prev = 0.0f;
2649                 short pos_prev;
2650
2651                 str_last = &str[strlen(str)];
2652
2653                 but->pos = pos_prev = ((str_last - str) - but->ofs);
2654
2655                 while (true) {
2656                         cdist = startx + BLF_width(fstyle->uifont_id, str + but->ofs, (str_last - str) - but->ofs);
2657
2658                         /* check if position is found */
2659                         if (cdist < x) {
2660                                 /* check is previous location was in fact closer */
2661                                 if ((x - cdist) > (cdist_prev - x)) {
2662                                         but->pos = pos_prev;
2663                                 }
2664                                 break;
2665                         }
2666                         cdist_prev = cdist;
2667                         pos_prev   = but->pos;
2668                         /* done with tricky distance checks */
2669
2670                         pos_i = but->pos;
2671                         if (but->pos <= 0) break;
2672                         if (BLI_str_cursor_step_prev_utf8(str, but->ofs, &pos_i)) {
2673                                 but->pos = pos_i;
2674                                 str_last = &str[but->pos + but->ofs];
2675                         }
2676                         else {
2677                                 break; /* unlikely but possible */
2678                         }
2679                 }
2680                 but->pos += but->ofs;
2681                 if (but->pos < 0) but->pos = 0;
2682         }
2683
2684         if (fstyle->kerning == 1)
2685                 BLF_disable(fstyle->uifont_id, BLF_KERNING_DEFAULT);
2686
2687         ui_but_text_password_hide(password_str, but, true);
2688
2689         fstyle->points = fstyle_points_prev;
2690 }
2691
2692 static void ui_textedit_set_cursor_select(uiBut *but, uiHandleButtonData *data, const float x)
2693 {
2694         if      (x > data->selstartx) data->selextend = EXTEND_RIGHT;
2695         else if (x < data->selstartx) data->selextend = EXTEND_LEFT;
2696
2697         ui_textedit_set_cursor_pos(but, data, x);
2698
2699         if      (data->selextend == EXTEND_RIGHT) but->selend = but->pos;
2700         else if (data->selextend == EXTEND_LEFT)  but->selsta = but->pos;
2701
2702         ui_but_update(but);
2703 }
2704
2705 /**
2706  * This is used for both utf8 and ascii
2707  *
2708  * For unicode buttons, \a buf is treated as unicode.
2709  */
2710 static bool ui_textedit_insert_buf(
2711         uiBut *but, uiHandleButtonData *data,
2712         const char *buf, int buf_len)
2713 {
2714         int len = strlen(data->str);
2715         int len_new = len - (but->selend - but->selsta) + 1;
2716         bool changed = false;
2717
2718         if (data->is_str_dynamic) {
2719                 ui_textedit_string_ensure_max_length(but, data, len_new + buf_len);
2720         }
2721
2722         if (len_new <= data->maxlen) {
2723                 char *str = data->str;
2724                 size_t step = buf_len;
2725
2726                 /* type over the current selection */
2727                 if ((but->selend - but->selsta) > 0) {
2728                         changed = ui_textedit_delete_selection(but, data);
2729                         len = strlen(str);
2730                 }
2731
2732                 if ((len + step >= data->maxlen) && (data->maxlen - (len + 1) > 0)) {
2733                         if (ui_but_is_utf8(but)) {
2734                                 /* shorten 'step' to a utf8 aligned size that fits  */
2735                                 BLI_strnlen_utf8_ex(buf, data->maxlen - (len + 1), &step);
2736                         }
2737                         else {
2738                                 step = data->maxlen - (len + 1);
2739                         }
2740                 }
2741
2742                 if (step && (len + step < data->maxlen)) {
2743                         memmove(&str[but->pos + step], &str[but->pos], (len + 1) - but->pos);
2744                         memcpy(&str[but->pos], buf, step * sizeof(char));
2745                         but->pos += step;
2746                         changed = true;
2747                 }
2748         }
2749
2750         return changed;
2751 }
2752
2753 static bool ui_textedit_insert_ascii(uiBut *but, uiHandleButtonData *data, char ascii)
2754 {
2755         char buf[2] = {ascii, '\0'};
2756
2757         if (ui_but_is_utf8(but) && (BLI_str_utf8_size(buf) == -1)) {
2758                 printf("%s: entering invalid ascii char into an ascii key (%d)\n",
2759                        __func__, (int)(unsigned char)ascii);
2760
2761                 return false;
2762         }
2763
2764         /* in some cases we want to allow invalid utf8 chars */
2765         return ui_textedit_insert_buf(but, data, buf, 1);
2766 }
2767
2768 static void ui_textedit_move(
2769         uiBut *but, uiHandleButtonData *data, eStrCursorJumpDirection direction,
2770         const bool select, eStrCursorJumpType jump)
2771 {
2772         const char *str = data->str;
2773         const int len = strlen(str);
2774         const int pos_prev = but->pos;
2775         const bool has_sel = (but->selend - but->selsta) > 0;
2776
2777         ui_but_update(but);
2778
2779         /* special case, quit selection and set cursor */
2780         if (has_sel && !select) {
2781                 if (jump == STRCUR_JUMP_ALL) {
2782                         but->selsta = but->selend = but->pos = direction ? len : 0;
2783                 }
2784                 else {
2785                         if (direction) {
2786                                 but->selsta = but->pos = but->selend;
2787                         }
2788                         else {
2789                                 but->pos = but->selend = but->selsta;
2790                         }
2791                 }
2792                 data->selextend = EXTEND_NONE;
2793         }
2794         else {
2795                 int pos_i = but->pos;
2796                 BLI_str_cursor_step_utf8(str, len, &pos_i, direction, jump, true);
2797                 but->pos = pos_i;
2798
2799                 if (select) {
2800                         /* existing selection */
2801                         if (has_sel) {
2802
2803                                 if (data->selextend == EXTEND_NONE) {
2804                                         data->selextend = EXTEND_RIGHT;
2805                                 }
2806
2807                                 if (direction) {
2808                                         if (data->selextend == EXTEND_RIGHT) {
2809                                                 but->selend = but->pos;
2810                                         }
2811                                         else {
2812                                                 but->selsta = but->pos;
2813                                         }
2814                                 }
2815                                 else {
2816                                         if (data->selextend == EXTEND_LEFT) {
2817                                                 but->selsta = but->pos;
2818                                         }
2819                                         else {
2820                                                 but->selend = but->pos;
2821                                         }
2822                                 }
2823
2824                                 if (but->selend < but->selsta) {
2825                                         SWAP(short, but->selsta, but->selend);
2826                                         data->selextend = (data->selextend == EXTEND_RIGHT) ? EXTEND_LEFT : EXTEND_RIGHT;
2827                                 }
2828
2829                         } /* new selection */
2830                         else {
2831                                 if (direction) {
2832                                         data->selextend = EXTEND_RIGHT;
2833                                         but->selend = but->pos;
2834                                         but->selsta = pos_prev;
2835                                 }
2836                                 else {
2837                                         data->selextend = EXTEND_LEFT;
2838                                         but->selend = pos_prev;
2839                                         but->selsta = but->pos;
2840                                 }
2841                         }
2842                 }
2843         }
2844 }
2845
2846 static bool ui_textedit_delete(uiBut *but, uiHandleButtonData *data, int direction, eStrCursorJumpType jump)
2847 {
2848         char *str = data->str;
2849         const int len = strlen(str);
2850
2851         bool changed = false;
2852
2853         if (jump == STRCUR_JUMP_ALL) {
2854                 if (len) changed = true;
2855                 str[0] = '\0';
2856                 but->pos = 0;
2857         }
2858         else if (direction) { /* delete */
2859                 if ((but->selend - but->selsta) > 0) {
2860                         changed = ui_textedit_delete_selection(but, data);
2861                 }
2862                 else if (but->pos >= 0 && but->pos < len) {
2863                         int pos = but->pos;
2864                         int step;
2865                         BLI_str_cursor_step_utf8(str, len, &pos, direction, jump, true);
2866                         step = pos - but->pos;
2867                         memmove(&str[but->pos], &str[but->pos + step], (len + 1) - (but->pos + step));
2868                         changed = true;
2869                 }
2870         }
2871         else { /* backspace */
2872                 if (len != 0) {
2873                         if ((but->selend - but->selsta) > 0) {
2874                                 changed = ui_textedit_delete_selection(but, data);
2875                         }
2876                         else if (but->pos > 0) {
2877                                 int pos = but->pos;
2878                                 int step;
2879
2880                                 BLI_str_cursor_step_utf8(str, len, &pos, direction, jump, true);
2881                                 step = but->pos - pos;
2882                                 memmove(&str[but->pos - step], &str[but->pos], (len + 1) - but->pos);
2883                                 but->pos -= step;
2884                                 changed = true;
2885                         }
2886                 }
2887         }
2888
2889         return changed;
2890 }
2891
2892 static int ui_textedit_autocomplete(bContext *C, uiBut *but, uiHandleButtonData *data)
2893 {
2894         char *str;
2895         int changed;
2896
2897         str = data->str;
2898
2899         if (data->searchbox)
2900                 changed = ui_searchbox_autocomplete(C, data->searchbox, but, data->str);
2901         else
2902                 changed = but->autocomplete_func(C, str, but->autofunc_arg);
2903
2904         but->pos = strlen(str);
2905         but->selsta = but->selend = but->pos;
2906
2907         return changed;
2908 }
2909
2910 /* mode for ui_textedit_copypaste() */
2911 enum {
2912         UI_TEXTEDIT_PASTE = 1,
2913         UI_TEXTEDIT_COPY,
2914         UI_TEXTEDIT_CUT
2915 };
2916
2917 static bool ui_textedit_copypaste(uiBut *but, uiHandleButtonData *data, const int mode)
2918 {
2919         char *pbuf;
2920         bool changed = false;
2921         int buf_len;
2922
2923         /* paste */
2924         if (mode == UI_TEXTEDIT_PASTE) {
2925                 /* extract the first line from the clipboard */
2926                 pbuf = WM_clipboard_text_get_firstline(false, &buf_len);
2927
2928                 if (pbuf) {
2929                         if (ui_but_is_utf8(but)) {
2930                                 buf_len -= BLI_utf8_invalid_strip(pbuf, (size_t)buf_len);
2931                         }
2932
2933                         ui_textedit_insert_buf(but, data, pbuf, buf_len);
2934
2935                         changed = true;
2936
2937                         MEM_freeN(pbuf);
2938                 }
2939         }
2940         /* cut & copy */
2941         else if (ELEM(mode, UI_TEXTEDIT_COPY, UI_TEXTEDIT_CUT)) {
2942                 /* copy the contents to the copypaste buffer */
2943                 int sellen = but->selend - but->selsta;
2944                 char *buf = MEM_mallocN(sizeof(char) * (sellen + 1), "ui_textedit_copypaste");
2945
2946                 BLI_strncpy(buf, data->str + but->selsta, sellen + 1);
2947                 WM_clipboard_text_set(buf, 0);
2948                 MEM_freeN(buf);
2949
2950                 /* for cut only, delete the selection afterwards */
2951                 if (mode == UI_TEXTEDIT_CUT) {
2952                         if ((but->selend - but->selsta) > 0) {
2953                                 changed = ui_textedit_delete_selection(but, data);
2954                         }
2955                 }
2956         }
2957
2958         return changed;
2959 }
2960
2961 #ifdef WITH_INPUT_IME
2962 /* enable ime, and set up uibut ime data */
2963 static void ui_textedit_ime_begin(wmWindow *win, uiBut *UNUSED(but))
2964 {
2965         /* XXX Is this really needed? */
2966         int x, y;
2967
2968         BLI_assert(win->ime_data == NULL);
2969
2970         /* enable IME and position to cursor, it's a trick */
2971         x = win->eventstate->x;
2972         /* flip y and move down a bit, prevent the IME panel cover the edit button */
2973         y = win->eventstate->y - 12;
2974
2975         wm_window_IME_begin(win, x, y, 0, 0, true);
2976 }
2977
2978 /* disable ime, and clear uibut ime data */
2979 static void ui_textedit_ime_end(wmWindow *win, uiBut *UNUSED(but))
2980 {
2981         wm_window_IME_end(win);
2982 }
2983
2984 void ui_but_ime_reposition(uiBut *but, int x, int y, bool complete)
2985 {
2986         BLI_assert(but->active);
2987
2988         ui_region_to_window(but->active->region, &x, &y);
2989         wm_window_IME_begin(but->active->window, x, y - 4, 0, 0, complete);
2990 }
2991
2992 wmIMEData *ui_but_ime_data_get(uiBut *but)
2993 {
2994         if (but->active && but->active->window) {
2995                 return but->active->window->ime_data;
2996         }
2997         else {
2998                 return NULL;
2999         }
3000 }
3001 #endif  /* WITH_INPUT_IME */
3002
3003 static void ui_textedit_begin(bContext *C, uiBut *but, uiHandleButtonData *data)
3004 {
3005         wmWindow *win = CTX_wm_window(C);
3006         int len;
3007         const bool is_num_but = ELEM(but->type, UI_BTYPE_NUM, UI_BTYPE_NUM_SLIDER);
3008         bool no_zero_strip = false;
3009
3010         if (data->str) {
3011                 MEM_freeN(data->str);
3012                 data->str = NULL;
3013         }
3014
3015 #ifdef USE_DRAG_MULTINUM
3016         /* this can happen from multi-drag */
3017         if (data->applied_interactive) {
3018                 /* remove any small changes so canceling edit doesn't restore invalid value: T40538 */
3019                 data->cancel = true;
3020                 ui_apply_but(C, but->block, but, data, true);
3021                 data->cancel = false;
3022
3023                 data->applied_interactive = false;
3024         }
3025 #endif
3026
3027 #ifdef USE_ALLSELECT
3028         if (is_num_but) {
3029                 if (IS_ALLSELECT_EVENT(win->eventstate)) {
3030                         data->select_others.is_enabled = true;
3031                         data->select_others.is_copy = true;
3032
3033                 }
3034         }
3035 #endif
3036
3037         /* retrieve string */
3038         data->maxlen = ui_but_string_get_max_length(but);
3039         if (data->maxlen != 0) {
3040                 data->str = MEM_callocN(sizeof(char) * data->maxlen, "textedit str");
3041                 /* We do not want to truncate precision to default here, it's nice to show value,
3042                  * not to edit it - way too much precision is lost then. */
3043                 ui_but_string_get_ex(but, data->str, data->maxlen, UI_PRECISION_FLOAT_MAX, true, &no_zero_strip);
3044         }
3045         else {
3046                 data->is_str_dynamic = true;
3047                 data->str = ui_but_string_get_dynamic(but, &data->maxlen);
3048         }
3049
3050         if (ui_but_is_float(but) && !ui_but_is_unit(but) && !ui_but_anim_expression_get(but, NULL, 0) && !no_zero_strip) {
3051                 BLI_str_rstrip_float_zero(data->str, '\0');
3052         }
3053
3054         if (is_num_but) {
3055                 BLI_assert(data->is_str_dynamic == false);
3056                 ui_but_convert_to_unit_alt_name(but, data->str, data->maxlen);
3057         }
3058
3059         /* won't change from now on */
3060         len = strlen(data->str);
3061
3062         data->origstr = BLI_strdupn(data->str, len);
3063         data->selextend = EXTEND_NONE;
3064         data->selstartx = 0.0f;
3065
3066         /* set cursor pos to the end of the text */
3067         but->editstr = data->str;
3068         but->pos = len;
3069         but->selsta = 0;
3070         but->selend = len;
3071
3072         /* optional searchbox */
3073         if (but->type ==  UI_BTYPE_SEARCH_MENU) {
3074                 data->searchbox = but->search_create_func(C, data->region, but);
3075                 ui_searchbox_update(C, data->searchbox, but, true); /* true = reset */
3076         }
3077
3078         /* reset alert flag (avoid confusion, will refresh on exit) */
3079         but->flag &= ~UI_BUT_REDALERT;
3080
3081         ui_but_update(but);
3082
3083         WM_cursor_modal_set(win, BC_TEXTEDITCURSOR);
3084
3085 #ifdef WITH_INPUT_IME
3086         if (is_num_but == false && BLT_lang_is_ime_supported()) {
3087                 ui_textedit_ime_begin(win, but);
3088         }
3089 #endif
3090 }
3091
3092 static void ui_textedit_end(bContext *C, uiBut *but, uiHandleButtonData *data)
3093 {
3094         wmWindow *win = CTX_wm_window(C);
3095
3096         if (but) {
3097                 if (ui_but_is_utf8(but)) {
3098                         int strip = BLI_utf8_invalid_strip(but->editstr, strlen(but->editstr));
3099                         /* not a file?, strip non utf-8 chars */
3100                         if (strip) {
3101                                 /* wont happen often so isn't that annoying to keep it here for a while */
3102                                 printf("%s: invalid utf8 - stripped chars %d\n", __func__, strip);
3103                         }
3104                 }
3105
3106                 if (data->searchbox) {
3107                         if (data->cancel == false) {
3108                                 if ((ui_searchbox_apply(but, data->searchbox) == false) &&
3109                                     (ui_searchbox_find_index(data->searchbox, but->editstr) == -1))
3110                                 {
3111                                         data->cancel = true;
3112
3113                                         /* ensure menu (popup) too is closed! */
3114                                         data->escapecancel = true;
3115                                 }
3116                         }
3117
3118                         ui_searchbox_free(C, data->searchbox);
3119                         data->searchbox = NULL;
3120                         if (but->free_search_arg) {
3121                                 MEM_SAFE_FREE(but->search_arg);
3122                         }
3123                 }
3124
3125                 but->editstr = NULL;
3126                 but->pos = -1;
3127         }
3128
3129         WM_cursor_modal_restore(win);
3130
3131 #ifdef WITH_INPUT_IME
3132         if (win->ime_data) {
3133                 ui_textedit_ime_end(win, but);</