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