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