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