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