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