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