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_UI_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 /* Helpers that wrap boolean functions, to support different kinds of buttons. */
1271
1272 static bool ui_drag_toggle_but_is_supported(const uiBut *but)
1273 {
1274         if (ui_but_is_bool(but)) {
1275                 return true;
1276         }
1277         else {
1278                 return false;
1279         }
1280 }
1281
1282 static bool ui_drag_toggle_but_is_pushed(uiBut *but)
1283 {
1284         if (ui_but_is_bool(but)) {
1285                 return ui_but_is_pushed(but);
1286         }
1287         else {
1288                 return false;
1289         }
1290 }
1291
1292 typedef struct uiDragToggleHandle {
1293         /* init */
1294         bool is_init;
1295         bool is_set;
1296         float but_cent_start[2];
1297         eButType but_type_start;
1298
1299         bool xy_lock[2];
1300         int  xy_init[2];
1301         int  xy_last[2];
1302 } uiDragToggleHandle;
1303
1304 static bool ui_drag_toggle_set_xy_xy(
1305         bContext *C, ARegion *ar, const bool is_set, const eButType but_type_start,
1306         const int xy_src[2], const int xy_dst[2])
1307 {
1308         /* popups such as layers won't re-evaluate on redraw */
1309         const bool do_check = (ar->regiontype == RGN_TYPE_TEMPORARY);
1310         bool changed = false;
1311         uiBlock *block;
1312
1313         for (block = ar->uiblocks.first; block; block = block->next) {
1314                 uiBut *but;
1315
1316                 float xy_a_block[2] = {UNPACK2(xy_src)};
1317                 float xy_b_block[2] = {UNPACK2(xy_dst)};
1318
1319                 ui_window_to_block_fl(ar, block, &xy_a_block[0], &xy_a_block[1]);
1320                 ui_window_to_block_fl(ar, block, &xy_b_block[0], &xy_b_block[1]);
1321
1322                 for (but = block->buttons.first; but; but = but->next) {
1323                         /* Note: ctrl is always true here because (at least for now) we always want to consider text control
1324                          *       in this case, even when not embossed. */
1325                         if (ui_but_is_interactive(but, true)) {
1326                                 if (BLI_rctf_isect_segment(&but->rect, xy_a_block, xy_b_block)) {
1327
1328                                         /* execute the button */
1329                                         if (ui_drag_toggle_but_is_supported(but) && but->type == but_type_start) {
1330                                                 /* is it pressed? */
1331                                                 bool is_set_but = ui_drag_toggle_but_is_pushed(but);
1332                                                 if (is_set_but != is_set) {
1333                                                         UI_but_execute(C, but);
1334                                                         if (do_check) {
1335                                                                 ui_but_update_edited(but);
1336                                                         }
1337                                                         changed = true;
1338                                                 }
1339                                         }
1340                                         /* done */
1341
1342                                 }
1343                         }
1344                 }
1345         }
1346         if (changed) {
1347                 /* apply now, not on release (or if handlers are canceled for whatever reason) */
1348                 ui_apply_but_funcs_after(C);
1349         }
1350
1351         return changed;
1352 }
1353
1354 static void ui_drag_toggle_set(bContext *C, uiDragToggleHandle *drag_info, const int xy_input[2])
1355 {
1356         ARegion *ar = CTX_wm_region(C);
1357         bool do_draw = false;
1358         int xy[2];
1359
1360         /**
1361          * Initialize Locking:
1362          *
1363          * Check if we need to initialize the lock axis by finding if the first
1364          * button we mouse over is X or Y aligned, then lock the mouse to that axis after.
1365          */
1366         if (drag_info->is_init == false) {
1367                 /* first store the buttons original coords */
1368                 uiBut *but = ui_but_find_mouse_over_ex(ar, xy_input[0], xy_input[1], true);
1369
1370                 if (but) {
1371                         if (but->flag & UI_BUT_DRAG_LOCK) {
1372                                 const float but_cent_new[2] = {BLI_rctf_cent_x(&but->rect),
1373                                                                BLI_rctf_cent_y(&but->rect)};
1374
1375                                 /* check if this is a different button, chances are high the button wont move about :) */
1376                                 if (len_manhattan_v2v2(drag_info->but_cent_start, but_cent_new) > 1.0f) {
1377                                         if (fabsf(drag_info->but_cent_start[0] - but_cent_new[0]) <
1378                                             fabsf(drag_info->but_cent_start[1] - but_cent_new[1]))
1379                                         {
1380                                                 drag_info->xy_lock[0] = true;
1381                                         }
1382                                         else {
1383                                                 drag_info->xy_lock[1] = true;
1384                                         }
1385                                         drag_info->is_init = true;
1386                                 }
1387                         }
1388                         else {
1389                                 drag_info->is_init = true;
1390                         }
1391                 }
1392         }
1393         /* done with axis locking */
1394
1395
1396         xy[0] = (drag_info->xy_lock[0] == false) ? xy_input[0] : drag_info->xy_last[0];
1397         xy[1] = (drag_info->xy_lock[1] == false) ? xy_input[1] : drag_info->xy_last[1];
1398
1399
1400         /* touch all buttons between last mouse coord and this one */
1401         do_draw = ui_drag_toggle_set_xy_xy(C, ar, drag_info->is_set, drag_info->but_type_start, drag_info->xy_last, xy);
1402
1403         if (do_draw) {
1404                 ED_region_tag_redraw(ar);
1405         }
1406
1407         copy_v2_v2_int(drag_info->xy_last, xy);
1408 }
1409
1410 static void ui_handler_region_drag_toggle_remove(bContext *UNUSED(C), void *userdata)
1411 {
1412         uiDragToggleHandle *drag_info = userdata;
1413         MEM_freeN(drag_info);
1414 }
1415
1416 static int ui_handler_region_drag_toggle(bContext *C, const wmEvent *event, void *userdata)
1417 {
1418         uiDragToggleHandle *drag_info = userdata;
1419         bool done = false;
1420
1421         switch (event->type) {
1422                 case LEFTMOUSE:
1423                 {
1424                         if (event->val == KM_RELEASE) {
1425                                 done = true;
1426                         }
1427                         break;
1428                 }
1429                 case MOUSEMOVE:
1430                 {
1431                         ui_drag_toggle_set(C, drag_info, &event->x);
1432                         break;
1433                 }
1434         }
1435
1436         if (done) {
1437                 wmWindow *win = CTX_wm_window(C);
1438                 ARegion *ar = CTX_wm_region(C);
1439                 uiBut *but = ui_but_find_mouse_over_ex(ar, drag_info->xy_init[0], drag_info->xy_init[1], true);
1440
1441                 if (but) {
1442                         ui_apply_but_undo(but);
1443                 }
1444
1445                 WM_event_remove_ui_handler(&win->modalhandlers,
1446                                            ui_handler_region_drag_toggle,
1447                                            ui_handler_region_drag_toggle_remove,
1448                                            drag_info, false);
1449                 ui_handler_region_drag_toggle_remove(C, drag_info);
1450
1451                 WM_event_add_mousemove(C);
1452                 return WM_UI_HANDLER_BREAK;
1453         }
1454         else {
1455                 return WM_UI_HANDLER_CONTINUE;
1456         }
1457 }
1458
1459 static bool ui_but_is_drag_toggle(const uiBut *but)
1460 {
1461         return ((ui_drag_toggle_but_is_supported(but) == true) &&
1462                 /* menu check is importnt so the button dragged over isn't removed instantly */
1463                 (ui_block_is_menu(but->block) == false));
1464 }
1465
1466 #endif  /* USE_DRAG_TOGGLE */
1467
1468
1469 #ifdef USE_ALLSELECT
1470
1471 static bool ui_selectcontext_begin(
1472         bContext *C, uiBut *but, uiSelectContextStore *selctx_data)
1473 {
1474         PointerRNA ptr, lptr, idptr;
1475         PropertyRNA *prop, *lprop;
1476         bool success = false;
1477         int index;
1478
1479         char *path = NULL;
1480         ListBase lb = {NULL};
1481
1482         ptr = but->rnapoin;
1483         prop = but->rnaprop;
1484         index = but->rnaindex;
1485
1486         /* for now don't support whole colors */
1487         if (index == -1)
1488                 return false;
1489
1490         /* if there is a valid property that is editable... */
1491         if (ptr.data && prop) {
1492                 CollectionPointerLink *link;
1493                 bool use_path_from_id;
1494                 int i;
1495
1496                 /* some facts we want to know */
1497                 const bool is_array = RNA_property_array_check(prop);
1498                 const int rna_type = RNA_property_type(prop);
1499
1500                 if (UI_context_copy_to_selected_list(C, &ptr, prop, &lb, &use_path_from_id, &path) &&
1501                     !BLI_listbase_is_empty(&lb))
1502                 {
1503                         selctx_data->elems_len = BLI_listbase_count(&lb);
1504                         selctx_data->elems = MEM_mallocN(sizeof(uiSelectContextElem) * selctx_data->elems_len, __func__);
1505
1506                         for (i = 0, link = lb.first; i < selctx_data->elems_len; i++, link = link->next) {
1507                                 uiSelectContextElem *other = &selctx_data->elems[i];
1508                                 /* TODO,. de-duplicate copy_to_selected_button */
1509                                 if (link->ptr.data != ptr.data) {
1510                                         if (use_path_from_id) {
1511                                                 /* Path relative to ID. */
1512                                                 lprop = NULL;
1513                                                 RNA_id_pointer_create(link->ptr.id.data, &idptr);
1514                                                 RNA_path_resolve_property(&idptr, path, &lptr, &lprop);
1515                                         }
1516                                         else if (path) {
1517                                                 /* Path relative to elements from list. */
1518                                                 lprop = NULL;
1519                                                 RNA_path_resolve_property(&link->ptr, path, &lptr, &lprop);
1520                                         }
1521                                         else {
1522                                                 lptr = link->ptr;
1523                                                 lprop = prop;
1524                                         }
1525
1526                                         /* lptr might not be the same as link->ptr! */
1527                                         if ((lptr.data != ptr.data) &&
1528                                             (lprop == prop) &&
1529                                             RNA_property_editable(&lptr, lprop))
1530                                         {
1531                                                 other->ptr = lptr;
1532                                                 if (is_array) {
1533                                                         if (rna_type == PROP_FLOAT) {
1534                                                                 other->val_f = RNA_property_float_get_index(&lptr, lprop, index);
1535                                                         }
1536                                                         else if (rna_type == PROP_INT) {
1537                                                                 other->val_i = RNA_property_int_get_index(&lptr, lprop, index);
1538                                                         }
1539                                                         /* ignored for now */
1540 #if 0
1541                                                         else if (rna_type == PROP_BOOLEAN) {
1542                                                                 other->val_b = RNA_property_boolean_get_index(&lptr, lprop, index);
1543                                                         }
1544 #endif
1545                                                 }
1546                                                 else {
1547                                                         if (rna_type == PROP_FLOAT) {
1548                                                                 other->val_f = RNA_property_float_get(&lptr, lprop);
1549                                                         }
1550                                                         else if (rna_type == PROP_INT) {
1551                                                                 other->val_i = RNA_property_int_get(&lptr, lprop);
1552                                                         }
1553                                                         /* ignored for now */
1554 #if 0
1555                                                         else if (rna_type == PROP_BOOLEAN) {
1556                                                                 other->val_b = RNA_property_boolean_get(&lptr, lprop);
1557                                                         }
1558                                                         else if (rna_type == PROP_ENUM) {
1559                                                                 other->val_i = RNA_property_enum_get(&lptr, lprop);
1560                                                         }
1561 #endif
1562                                                 }
1563
1564                                                 continue;
1565                                         }
1566                                 }
1567
1568                                 selctx_data->elems_len -= 1;
1569                                 i -= 1;
1570                         }
1571
1572                         success = (selctx_data->elems_len != 0);
1573                 }
1574         }
1575
1576         if (selctx_data->elems_len == 0) {
1577                 MEM_SAFE_FREE(selctx_data->elems);
1578         }
1579
1580         MEM_SAFE_FREE(path);
1581         BLI_freelistN(&lb);
1582
1583         /* caller can clear */
1584         selctx_data->do_free = true;
1585
1586         if (success) {
1587                 but->flag |= UI_BUT_IS_SELECT_CONTEXT;
1588         }
1589
1590         return success;
1591 }
1592
1593 static void ui_selectcontext_end(
1594         uiBut *but, uiSelectContextStore *selctx_data)
1595 {
1596         if (selctx_data->do_free) {
1597                 if (selctx_data->elems) {
1598                         MEM_freeN(selctx_data->elems);
1599                 }
1600         }
1601
1602         but->flag &= ~UI_BUT_IS_SELECT_CONTEXT;
1603 }
1604
1605 static void ui_selectcontext_apply(
1606         bContext *C, uiBut *but, uiSelectContextStore *selctx_data,
1607         const double value, const double value_orig)
1608 {
1609         if (selctx_data->elems) {
1610                 PropertyRNA *prop = but->rnaprop;
1611                 PropertyRNA *lprop = but->rnaprop;
1612                 int index = but->rnaindex;
1613                 int i;
1614                 const bool use_delta = (selctx_data->is_copy == false);
1615
1616                 union {
1617                         bool  b;
1618                         int   i;
1619                         float f;
1620                         PointerRNA p;
1621                 } delta, min, max;
1622
1623                 const bool is_array = RNA_property_array_check(prop);
1624                 const int rna_type = RNA_property_type(prop);
1625
1626                 if (rna_type == PROP_FLOAT) {
1627                         delta.f = use_delta ? (value - value_orig) : value;
1628                         RNA_property_float_range(&but->rnapoin, prop, &min.f, &max.f);
1629                 }
1630                 else if (rna_type == PROP_INT) {
1631                         delta.i = use_delta ? ((int)value - (int)value_orig) : (int)value;
1632                         RNA_property_int_range(&but->rnapoin, prop, &min.i, &max.i);
1633                 }
1634                 else if (rna_type == PROP_ENUM) {
1635                         delta.i = RNA_property_enum_get(&but->rnapoin, prop);  /* not a delta infact */
1636                 }
1637                 else if (rna_type == PROP_BOOLEAN) {
1638                         if (is_array) {
1639                                 delta.b = RNA_property_boolean_get_index(&but->rnapoin, prop, index);  /* not a delta infact */
1640                         }
1641                         else {
1642                                 delta.b = RNA_property_boolean_get(&but->rnapoin, prop);  /* not a delta infact */
1643                         }
1644                 }
1645                 else if (rna_type == PROP_POINTER) {
1646                         delta.p = RNA_property_pointer_get(&but->rnapoin, prop);  /* not a delta infact */
1647                 }
1648
1649 #ifdef USE_ALLSELECT_LAYER_HACK
1650                 /* make up for not having 'handle_layer_buttons' */
1651                 {
1652                         PropertySubType subtype = RNA_property_subtype(prop);
1653
1654                         if ((rna_type == PROP_BOOLEAN) &&
1655                             ELEM(subtype, PROP_LAYER, PROP_LAYER_MEMBER) &&
1656                             is_array &&
1657                             /* could check for 'handle_layer_buttons' */
1658                             but->func)
1659                         {
1660                                 wmWindow *win = CTX_wm_window(C);
1661                                 if (!win->eventstate->shift) {
1662                                         const int len = RNA_property_array_length(&but->rnapoin, prop);
1663                                         int *tmparray = MEM_callocN(sizeof(int) * len, __func__);
1664
1665                                         tmparray[index] = true;
1666
1667                                         for (i = 0; i < selctx_data->elems_len; i++) {
1668                                                 uiSelectContextElem *other = &selctx_data->elems[i];
1669                                                 PointerRNA lptr = other->ptr;
1670                                                 RNA_property_boolean_set_array(&lptr, lprop, tmparray);
1671                                                 RNA_property_update(C, &lptr, lprop);
1672                                         }
1673
1674                                         MEM_freeN(tmparray);
1675
1676                                         return;
1677                                 }
1678                         }
1679                 }
1680 #endif
1681
1682                 for (i = 0; i < selctx_data->elems_len; i++) {
1683                         uiSelectContextElem *other = &selctx_data->elems[i];
1684                         PointerRNA lptr = other->ptr;
1685
1686                         if (rna_type == PROP_FLOAT) {
1687                                 float other_value = use_delta ? (other->val_f + delta.f) : delta.f;
1688                                 CLAMP(other_value, min.f, max.f);
1689                                 if (is_array) {
1690                                         RNA_property_float_set_index(&lptr, lprop, index, other_value);
1691                                 }
1692                                 else {
1693                                         RNA_property_float_set(&lptr, lprop, other_value);
1694                                 }
1695                         }
1696                         else if (rna_type == PROP_INT) {
1697                                 int other_value = use_delta ? (other->val_i + delta.i) : delta.i;
1698                                 CLAMP(other_value, min.i, max.i);
1699                                 if (is_array) {
1700                                         RNA_property_int_set_index(&lptr, lprop, index, other_value);
1701                                 }
1702                                 else {
1703                                         RNA_property_int_set(&lptr, lprop, other_value);
1704                                 }
1705                         }
1706                         else if (rna_type == PROP_BOOLEAN) {
1707                                 const bool other_value = delta.b;
1708                                 if (is_array) {
1709                                         RNA_property_boolean_set_index(&lptr, lprop, index, other_value);
1710                                 }
1711                                 else {
1712                                         RNA_property_boolean_set(&lptr, lprop, delta.b);
1713                                 }
1714                         }
1715                         else if (rna_type == PROP_ENUM) {
1716                                 const int other_value = delta.i;
1717                                 BLI_assert(!is_array);
1718                                 RNA_property_enum_set(&lptr, lprop, other_value);
1719                         }
1720                         else if (rna_type == PROP_POINTER) {
1721                                 const PointerRNA other_value = delta.p;
1722                                 RNA_property_pointer_set(&lptr, lprop, other_value);
1723                         }
1724
1725                         RNA_property_update(C, &lptr, prop);
1726                 }
1727         }
1728 }
1729
1730 #endif  /* USE_ALLSELECT */
1731
1732
1733 static bool ui_but_contains_point_px_icon(uiBut *but, ARegion *ar, const wmEvent *event)
1734 {
1735         rcti rect;
1736         int x = event->x, y = event->y;
1737
1738         ui_window_to_block(ar, but->block, &x, &y);
1739
1740         BLI_rcti_rctf_copy(&rect, &but->rect);
1741
1742         if (but->imb || but->type == UI_BTYPE_COLOR) {
1743                 /* use button size itself */
1744         }
1745         else if (but->drawflag & UI_BUT_ICON_LEFT) {
1746                 rect.xmax = rect.xmin + (BLI_rcti_size_y(&rect));
1747         }
1748         else {
1749                 int delta = BLI_rcti_size_x(&rect) - BLI_rcti_size_y(&rect);
1750                 rect.xmin += delta / 2;
1751                 rect.xmax -= delta / 2;
1752         }
1753
1754         return BLI_rcti_isect_pt(&rect, x, y);
1755 }
1756
1757 static bool ui_but_drag_init(
1758         bContext *C, uiBut *but,
1759         uiHandleButtonData *data, const wmEvent *event)
1760 {
1761         /* prevent other WM gestures to start while we try to drag */
1762         WM_gestures_remove(C);
1763
1764         if (ABS(data->dragstartx - event->x) + ABS(data->dragstarty - event->y) > U.dragthreshold) {
1765
1766                 button_activate_state(C, but, BUTTON_STATE_EXIT);
1767                 data->cancel = true;
1768 #ifdef USE_DRAG_TOGGLE
1769                 if (ui_drag_toggle_but_is_supported(but)) {
1770                         uiDragToggleHandle *drag_info = MEM_callocN(sizeof(*drag_info), __func__);
1771                         ARegion *ar_prev;
1772
1773                         /* call here because regular mouse-up event wont run,
1774                          * typically 'button_activate_exit()' handles this */
1775                         ui_apply_but_autokey(C, but);
1776
1777                         drag_info->is_set = ui_drag_toggle_but_is_pushed(but);
1778                         drag_info->but_cent_start[0] = BLI_rctf_cent_x(&but->rect);
1779                         drag_info->but_cent_start[1] = BLI_rctf_cent_y(&but->rect);
1780                         drag_info->but_type_start = but->type;
1781                         copy_v2_v2_int(drag_info->xy_init, &event->x);
1782                         copy_v2_v2_int(drag_info->xy_last, &event->x);
1783
1784                         /* needed for toggle drag on popups */
1785                         ar_prev = CTX_wm_region(C);
1786                         CTX_wm_region_set(C, data->region);
1787
1788                         WM_event_add_ui_handler(
1789                                 C, &data->window->modalhandlers,
1790                                 ui_handler_region_drag_toggle,
1791                                 ui_handler_region_drag_toggle_remove,
1792                                 drag_info, WM_HANDLER_BLOCKING);
1793
1794                         CTX_wm_region_set(C, ar_prev);
1795                 }
1796                 else
1797 #endif
1798                 if (but->type == UI_BTYPE_COLOR) {
1799                         bool valid = false;
1800                         uiDragColorHandle *drag_info = MEM_callocN(sizeof(*drag_info), __func__);
1801
1802                         /* TODO support more button pointer types */
1803                         if (but->rnaprop && RNA_property_subtype(but->rnaprop) == PROP_COLOR_GAMMA) {
1804                                 ui_but_v3_get(but, drag_info->color);
1805                                 drag_info->gamma_corrected = true;
1806                                 valid = true;
1807                         }
1808                         else if (but->rnaprop && RNA_property_subtype(but->rnaprop) == PROP_COLOR) {
1809                                 ui_but_v3_get(but, drag_info->color);
1810                                 drag_info->gamma_corrected = false;
1811                                 valid = true;
1812                         }
1813                         else if (ELEM(but->pointype, UI_BUT_POIN_FLOAT, UI_BUT_POIN_CHAR)) {
1814                                 ui_but_v3_get(but, drag_info->color);
1815                                 copy_v3_v3(drag_info->color, (float *)but->poin);
1816                                 valid = true;
1817                         }
1818
1819                         if (valid) {
1820                                 WM_event_start_drag(C, ICON_COLOR, WM_DRAG_COLOR, drag_info, 0.0, WM_DRAG_FREE_DATA);
1821                         }
1822                         else {
1823                                 MEM_freeN(drag_info);
1824                                 return false;
1825                         }
1826                 }
1827                 else {
1828                         wmDrag *drag = WM_event_start_drag(
1829                                 C, but->icon, but->dragtype, but->dragpoin,
1830                                 ui_but_value_get(but), WM_DRAG_NOP);
1831
1832                         if (but->imb) {
1833                                 WM_event_drag_image(
1834                                         drag, but->imb, but->imb_scale,
1835                                         BLI_rctf_size_x(&but->rect),
1836                                         BLI_rctf_size_y(&but->rect));
1837                         }
1838                 }
1839                 return true;
1840         }
1841
1842         return false;
1843 }
1844
1845 /* ********************** linklines *********************** */
1846
1847 static void ui_apply_but_IMAGE(bContext *C, uiBut *but, uiHandleButtonData *data)
1848 {
1849         ui_apply_but_func(C, but);
1850         data->retval = but->retval;
1851         data->applied = true;
1852 }
1853
1854 static void ui_apply_but_HISTOGRAM(bContext *C, uiBut *but, uiHandleButtonData *data)
1855 {
1856         ui_apply_but_func(C, but);
1857         data->retval = but->retval;
1858         data->applied = true;
1859 }
1860
1861 static void ui_apply_but_WAVEFORM(bContext *C, uiBut *but, uiHandleButtonData *data)
1862 {
1863         ui_apply_but_func(C, but);
1864         data->retval = but->retval;
1865         data->applied = true;
1866 }
1867
1868 static void ui_apply_but_TRACKPREVIEW(bContext *C, uiBut *but, uiHandleButtonData *data)
1869 {
1870         ui_apply_but_func(C, but);
1871         data->retval = but->retval;
1872         data->applied = true;
1873 }
1874
1875
1876 static void ui_apply_but(bContext *C, uiBlock *block, uiBut *but, uiHandleButtonData *data, const bool interactive)
1877 {
1878         char *editstr;
1879         double *editval;
1880         float *editvec;
1881         ColorBand *editcoba;
1882         CurveMapping *editcumap;
1883
1884         data->retval = 0;
1885
1886         /* if we cancel and have not applied yet, there is nothing to do,
1887          * otherwise we have to restore the original value again */
1888         if (data->cancel) {
1889                 if (!data->applied)
1890                         return;
1891
1892                 if (data->str) MEM_freeN(data->str);
1893                 data->str = data->origstr;
1894                 data->origstr = NULL;
1895                 data->value = data->origvalue;
1896                 copy_v3_v3(data->vec, data->origvec);
1897                 /* postpone clearing origdata */
1898         }
1899         else {
1900                 /* we avoid applying interactive edits a second time
1901                  * at the end with the appliedinteractive flag */
1902                 if (interactive) {
1903                         data->applied_interactive = true;
1904                 }
1905                 else if (data->applied_interactive) {
1906                         return;
1907                 }
1908
1909 #ifdef USE_ALLSELECT
1910 #  ifdef USE_DRAG_MULTINUM
1911                 if (but->flag & UI_BUT_DRAG_MULTI) {
1912                         /* pass */
1913                 }
1914                 else
1915 #  endif
1916                 if (data->select_others.elems_len == 0) {
1917                         wmWindow *win = CTX_wm_window(C);
1918                         /* may have been enabled before activating */
1919                         if (data->select_others.is_enabled || IS_ALLSELECT_EVENT(win->eventstate)) {
1920                                 ui_selectcontext_begin(C, but, &data->select_others);
1921                                 data->select_others.is_enabled = true;
1922                         }
1923                 }
1924                 if (data->select_others.elems_len == 0) {
1925                         /* dont check again */
1926                         data->select_others.elems_len = -1;
1927                 }
1928 #endif
1929         }
1930
1931         /* ensures we are writing actual values */
1932         editstr = but->editstr;
1933         editval = but->editval;
1934         editvec = but->editvec;
1935         editcoba = but->editcoba;
1936         editcumap = but->editcumap;
1937         but->editstr = NULL;
1938         but->editval = NULL;
1939         but->editvec = NULL;
1940         but->editcoba = NULL;
1941         but->editcumap = NULL;
1942
1943         /* handle different types */
1944         switch (but->type) {
1945                 case UI_BTYPE_BUT:
1946                         ui_apply_but_BUT(C, but, data);
1947                         break;
1948                 case UI_BTYPE_TEXT:
1949                 case UI_BTYPE_SEARCH_MENU:
1950                         ui_apply_but_TEX(C, but, data);
1951                         break;
1952                 case UI_BTYPE_BUT_TOGGLE:
1953                 case UI_BTYPE_TOGGLE:
1954                 case UI_BTYPE_TOGGLE_N:
1955                 case UI_BTYPE_ICON_TOGGLE:
1956                 case UI_BTYPE_ICON_TOGGLE_N:
1957                 case UI_BTYPE_CHECKBOX:
1958                 case UI_BTYPE_CHECKBOX_N:
1959                         ui_apply_but_TOG(C, but, data);
1960                         break;
1961                 case UI_BTYPE_ROW:
1962                 case UI_BTYPE_LISTROW:
1963                         ui_apply_but_ROW(C, block, but, data);
1964                         break;
1965                 case UI_BTYPE_TAB:
1966                         ui_apply_but_TAB(C, but, data);
1967                         break;
1968                 case UI_BTYPE_SCROLL:
1969                 case UI_BTYPE_GRIP:
1970                 case UI_BTYPE_NUM:
1971                 case UI_BTYPE_NUM_SLIDER:
1972                         ui_apply_but_NUM(C, but, data);
1973                         break;
1974                 case UI_BTYPE_MENU:
1975                 case UI_BTYPE_BLOCK:
1976                 case UI_BTYPE_PULLDOWN:
1977                         ui_apply_but_BLOCK(C, but, data);
1978                         break;
1979                 case UI_BTYPE_COLOR:
1980                         if (data->cancel)
1981                                 ui_apply_but_VEC(C, but, data);
1982                         else
1983                                 ui_apply_but_BLOCK(C, but, data);
1984                         break;
1985                 case UI_BTYPE_BUT_MENU:
1986                         ui_apply_but_BUTM(C, but, data);
1987                         break;
1988                 case UI_BTYPE_UNITVEC:
1989                 case UI_BTYPE_HSVCUBE:
1990                 case UI_BTYPE_HSVCIRCLE:
1991                         ui_apply_but_VEC(C, but, data);
1992                         break;
1993                 case UI_BTYPE_COLORBAND:
1994                         ui_apply_but_COLORBAND(C, but, data);
1995                         break;
1996                 case UI_BTYPE_CURVE:
1997                         ui_apply_but_CURVE(C, but, data);
1998                         break;
1999                 case UI_BTYPE_KEY_EVENT:
2000                 case UI_BTYPE_HOTKEY_EVENT:
2001                         ui_apply_but_BUT(C, but, data);
2002                         break;
2003                 case UI_BTYPE_IMAGE:
2004                         ui_apply_but_IMAGE(C, but, data);
2005                         break;
2006                 case UI_BTYPE_HISTOGRAM:
2007                         ui_apply_but_HISTOGRAM(C, but, data);
2008                         break;
2009                 case UI_BTYPE_WAVEFORM:
2010                         ui_apply_but_WAVEFORM(C, but, data);
2011                         break;
2012                 case UI_BTYPE_TRACK_PREVIEW:
2013                         ui_apply_but_TRACKPREVIEW(C, but, data);
2014                         break;
2015                 default:
2016                         break;
2017         }
2018
2019 #ifdef USE_DRAG_MULTINUM
2020         if (data->multi_data.has_mbuts) {
2021                 if ((data->multi_data.init == BUTTON_MULTI_INIT_ENABLE) &&
2022                     (data->multi_data.skip == false))
2023                 {
2024                         if (data->cancel) {
2025                                 ui_multibut_restore(C, data, block);
2026                         }
2027                         else {
2028                                 ui_multibut_states_apply(C, data, block);
2029                         }
2030                 }
2031         }
2032 #endif
2033
2034 #ifdef USE_ALLSELECT
2035         ui_selectcontext_apply(C, but, &data->select_others, data->value, data->origvalue);
2036 #endif
2037
2038         if (data->cancel) {
2039                 data->origvalue = 0.0;
2040                 zero_v3(data->origvec);
2041         }
2042
2043         but->editstr = editstr;
2044         but->editval = editval;
2045         but->editvec = editvec;
2046         but->editcoba = editcoba;
2047         but->editcumap = editcumap;
2048 }
2049
2050 /* ******************* drop event ********************  */
2051
2052 /* only call if event type is EVT_DROP */
2053 static void ui_but_drop(bContext *C, const wmEvent *event, uiBut *but, uiHandleButtonData *data)
2054 {
2055         wmDrag *wmd;
2056         ListBase *drags = event->customdata; /* drop event type has listbase customdata by default */
2057
2058         for (wmd = drags->first; wmd; wmd = wmd->next) {
2059                 if (wmd->type == WM_DRAG_ID) {
2060                         /* align these types with UI_but_active_drop_name */
2061                         if (ELEM(but->type, UI_BTYPE_TEXT, UI_BTYPE_SEARCH_MENU)) {
2062                                 ID *id = (ID *)wmd->poin;
2063
2064                                 button_activate_state(C, but, BUTTON_STATE_TEXT_EDITING);
2065
2066                                 ui_textedit_string_set(but, data, id->name + 2);
2067
2068                                 if (ELEM(but->type, UI_BTYPE_SEARCH_MENU)) {
2069                                         but->changed = true;
2070                                         ui_searchbox_update(C, data->searchbox, but, true);
2071                                 }
2072
2073                                 button_activate_state(C, but, BUTTON_STATE_EXIT);
2074                         }
2075                 }
2076         }
2077
2078 }
2079
2080 /* ******************* copy and paste ********************  */
2081
2082 /* c = copy, v = paste */
2083 static void ui_but_copy_paste(bContext *C, uiBut *but, uiHandleButtonData *data, const char mode, const bool copy_array)
2084 {
2085         int buf_paste_len = 0;
2086         const char *buf_paste = "";
2087         bool buf_paste_alloc = false;
2088         bool show_report = false;  /* use to display errors parsing paste input */
2089
2090         BLI_assert((but->flag & UI_BUT_DISABLED) == 0); /* caller should check */
2091
2092         if (mode == 'c') {
2093                 /* disallow copying from any passwords */
2094                 if (but->rnaprop && (RNA_property_subtype(but->rnaprop) == PROP_PASSWORD)) {
2095                         return;
2096                 }
2097         }
2098
2099         if (mode == 'v') {
2100                 /* extract first line from clipboard in case of multi-line copies */
2101                 const char *buf_paste_test;
2102
2103                 buf_paste_test = WM_clipboard_text_get_firstline(false, &buf_paste_len);
2104                 if (buf_paste_test) {
2105                         buf_paste = buf_paste_test;
2106                         buf_paste_alloc = true;
2107                 }
2108         }
2109
2110         /* No return from here down */
2111
2112
2113         /* numeric value */
2114         if (ELEM(but->type, UI_BTYPE_NUM, UI_BTYPE_NUM_SLIDER)) {
2115
2116                 if (but->poin == NULL && but->rnapoin.data == NULL) {
2117                         /* pass */
2118                 }
2119                 else if (copy_array && but->rnapoin.data && but->rnaprop &&
2120                          ELEM(RNA_property_subtype(but->rnaprop), PROP_COLOR, PROP_TRANSLATION, PROP_DIRECTION,
2121                               PROP_VELOCITY, PROP_ACCELERATION, PROP_MATRIX, PROP_EULER, PROP_QUATERNION, PROP_AXISANGLE,
2122                               PROP_XYZ, PROP_XYZ_LENGTH, PROP_COLOR_GAMMA, PROP_COORDS))
2123                 {
2124                         float values[4];
2125                         int array_length = RNA_property_array_length(&but->rnapoin, but->rnaprop);
2126
2127                         if (mode == 'c') {
2128                                 char buf_copy[UI_MAX_DRAW_STR];
2129
2130                                 if (array_length == 4) {
2131                                         values[3] = RNA_property_float_get_index(&but->rnapoin, but->rnaprop, 3);
2132                                 }
2133                                 else {
2134                                         values[3] = 0.0f;
2135                                 }
2136                                 ui_but_v3_get(but, values);
2137
2138                                 BLI_snprintf(buf_copy, sizeof(buf_copy), "[%f, %f, %f, %f]", values[0], values[1], values[2], values[3]);
2139                                 WM_clipboard_text_set(buf_copy, 0);
2140                         }
2141                         else {
2142                                 if (sscanf(buf_paste, "[%f, %f, %f, %f]", &values[0], &values[1], &values[2], &values[3]) >= array_length) {
2143                                         button_activate_state(C, but, BUTTON_STATE_NUM_EDITING);
2144
2145                                         ui_but_v3_set(but, values);
2146                                         if (but->rnaprop && array_length == 4) {
2147                                                 RNA_property_float_set_index(&but->rnapoin, but->rnaprop, 3, values[3]);
2148                                         }
2149                                         data->value = values[but->rnaindex];
2150
2151                                         button_activate_state(C, but, BUTTON_STATE_EXIT);
2152                                 }
2153                                 else {
2154                                         WM_report(RPT_ERROR, "Paste expected 4 numbers, formatted: '[n, n, n, n]'");
2155                                         show_report = true;
2156                                 }
2157                         }
2158                 }
2159                 else if (mode == 'c') {
2160                         /* Get many decimal places, then strip trailing zeros.
2161                          * note: too high values start to give strange results */
2162                         char buf_copy[UI_MAX_DRAW_STR];
2163                         ui_but_string_get_ex(but, buf_copy, sizeof(buf_copy), UI_PRECISION_FLOAT_MAX, false, NULL);
2164                         BLI_str_rstrip_float_zero(buf_copy, '\0');
2165
2166                         WM_clipboard_text_set(buf_copy, 0);
2167                 }
2168                 else {
2169                         double val;
2170
2171                         if (ui_but_string_set_eval_num(C, but, buf_paste, &val)) {
2172                                 button_activate_state(C, but, BUTTON_STATE_NUM_EDITING);
2173                                 data->value = val;
2174                                 ui_but_string_set(C, but, buf_paste);
2175                                 button_activate_state(C, but, BUTTON_STATE_EXIT);
2176                         }
2177                         else {
2178                                 /* evaluating will report errors */
2179                                 show_report = true;
2180                         }
2181                 }
2182         }
2183
2184         /* NORMAL button */
2185         else if (but->type == UI_BTYPE_UNITVEC) {
2186                 float xyz[3];
2187
2188                 if (but->poin == NULL && but->rnapoin.data == NULL) {
2189                         /* pass */
2190                 }
2191                 else if (mode == 'c') {
2192                         char buf_copy[UI_MAX_DRAW_STR];
2193                         ui_but_v3_get(but, xyz);
2194                         BLI_snprintf(buf_copy, sizeof(buf_copy), "[%f, %f, %f]", xyz[0], xyz[1], xyz[2]);
2195                         WM_clipboard_text_set(buf_copy, 0);
2196                 }
2197                 else {
2198                         if (sscanf(buf_paste, "[%f, %f, %f]", &xyz[0], &xyz[1], &xyz[2]) == 3) {
2199                                 if (normalize_v3(xyz) == 0.0f) {
2200                                         /* better set Z up then have a zero vector */
2201                                         xyz[2] = 1.0;
2202                                 }
2203                                 button_activate_state(C, but, BUTTON_STATE_NUM_EDITING);
2204                                 ui_but_v3_set(but, xyz);
2205                                 button_activate_state(C, but, BUTTON_STATE_EXIT);
2206                         }
2207                         else {
2208                                 WM_report(RPT_ERROR, "Paste expected 3 numbers, formatted: '[n, n, n]'");
2209                                 show_report = true;
2210                         }
2211                 }
2212         }
2213
2214
2215         /* RGB triple */
2216         else if (but->type == UI_BTYPE_COLOR) {
2217                 float rgba[4];
2218
2219                 if (but->poin == NULL && but->rnapoin.data == NULL) {
2220                         /* pass */
2221                 }
2222                 else if (mode == 'c') {
2223                         char buf_copy[UI_MAX_DRAW_STR];
2224
2225                         if (but->rnaprop && RNA_property_array_length(&but->rnapoin, but->rnaprop) == 4)
2226                                 rgba[3] = RNA_property_float_get_index(&but->rnapoin, but->rnaprop, 3);
2227                         else
2228                                 rgba[3] = 1.0f;
2229
2230                         ui_but_v3_get(but, rgba);
2231                         /* convert to linear color to do compatible copy between gamma and non-gamma */
2232                         if (but->rnaprop && RNA_property_subtype(but->rnaprop) == PROP_COLOR_GAMMA)
2233                                 srgb_to_linearrgb_v3_v3(rgba, rgba);
2234
2235                         BLI_snprintf(buf_copy, sizeof(buf_copy), "[%f, %f, %f, %f]", rgba[0], rgba[1], rgba[2], rgba[3]);
2236                         WM_clipboard_text_set(buf_copy, 0);
2237
2238                 }
2239                 else {
2240                         if (sscanf(buf_paste, "[%f, %f, %f, %f]", &rgba[0], &rgba[1], &rgba[2], &rgba[3]) == 4) {
2241                                 /* assume linear colors in buffer */
2242                                 if (but->rnaprop && RNA_property_subtype(but->rnaprop) == PROP_COLOR_GAMMA)
2243                                         linearrgb_to_srgb_v3_v3(rgba, rgba);
2244
2245                                 button_activate_state(C, but, BUTTON_STATE_NUM_EDITING);
2246                                 ui_but_v3_set(but, rgba);
2247                                 if (but->rnaprop && RNA_property_array_length(&but->rnapoin, but->rnaprop) == 4)
2248                                         RNA_property_float_set_index(&but->rnapoin, but->rnaprop, 3, rgba[3]);
2249
2250                                 button_activate_state(C, but, BUTTON_STATE_EXIT);
2251                         }
2252                         else {
2253                                 WM_report(RPT_ERROR, "Paste expected 4 numbers, formatted: '[n, n, n, n]'");
2254                                 show_report = true;
2255                         }
2256                 }
2257         }
2258
2259         /* text/string and ID data */
2260         else if (ELEM(but->type, UI_BTYPE_TEXT, UI_BTYPE_SEARCH_MENU)) {
2261                 uiHandleButtonData *active_data = but->active;
2262
2263                 if (but->poin == NULL && but->rnapoin.data == NULL) {
2264                         /* pass */
2265                 }
2266                 else if (mode == 'c') {
2267                         button_activate_state(C, but, BUTTON_STATE_TEXT_EDITING);
2268                         WM_clipboard_text_set(active_data->str, 0);
2269                         active_data->cancel = true;
2270                         button_activate_state(C, but, BUTTON_STATE_EXIT);
2271                 }
2272                 else {
2273                         button_activate_state(C, but, BUTTON_STATE_TEXT_EDITING);
2274
2275                         ui_textedit_string_set(but, active_data, buf_paste);
2276
2277                         if (but->type == UI_BTYPE_SEARCH_MENU) {
2278                                 /* else uiSearchboxData.active member is not updated [#26856] */
2279                                 but->changed = true;
2280                                 ui_searchbox_update(C, data->searchbox, but, true);
2281                         }
2282                         button_activate_state(C, but, BUTTON_STATE_EXIT);
2283                 }
2284         }
2285         /* colorband (not supported by system clipboard) */
2286         else if (but->type == UI_BTYPE_COLORBAND) {
2287                 if (mode == 'c') {
2288                         if (but->poin != NULL) {
2289                                 memcpy(&but_copypaste_coba, but->poin, sizeof(ColorBand));
2290                         }
2291                 }
2292                 else {
2293                         if (but_copypaste_coba.tot != 0) {
2294                                 if (!but->poin)
2295                                         but->poin = MEM_callocN(sizeof(ColorBand), "colorband");
2296
2297                                 button_activate_state(C, but, BUTTON_STATE_NUM_EDITING);
2298                                 memcpy(data->coba, &but_copypaste_coba, sizeof(ColorBand));
2299                                 button_activate_state(C, but, BUTTON_STATE_EXIT);
2300                         }
2301                 }
2302         }
2303         else if (but->type == UI_BTYPE_CURVE) {
2304                 if (mode == 'c') {
2305                         if (but->poin != NULL) {
2306                                 but_copypaste_curve_alive = true;
2307                                 curvemapping_free_data(&but_copypaste_curve);
2308                                 curvemapping_copy_data(&but_copypaste_curve, (CurveMapping *) but->poin);
2309                         }
2310                 }
2311                 else {
2312                         if (but_copypaste_curve_alive) {
2313                                 if (!but->poin)
2314                                         but->poin = MEM_callocN(sizeof(CurveMapping), "curvemapping");
2315
2316                                 button_activate_state(C, but, BUTTON_STATE_NUM_EDITING);
2317                                 curvemapping_free_data((CurveMapping *) but->poin);
2318                                 curvemapping_copy_data((CurveMapping *) but->poin, &but_copypaste_curve);
2319                                 button_activate_state(C, but, BUTTON_STATE_EXIT);
2320                         }
2321                 }
2322         }
2323         /* operator button (any type) */
2324         else if (but->optype) {
2325                 if (mode == 'c') {
2326                         PointerRNA *opptr;
2327                         char *str;
2328                         opptr = UI_but_operator_ptr_get(but); /* allocated when needed, the button owns it */
2329
2330                         str = WM_operator_pystring_ex(C, NULL, false, true, but->optype, opptr);
2331
2332                         WM_clipboard_text_set(str, 0);
2333
2334                         MEM_freeN(str);
2335                 }
2336         }
2337         /* menu (any type) */
2338         else if (ELEM(but->type, UI_BTYPE_MENU, UI_BTYPE_PULLDOWN)) {
2339                 MenuType *mt = UI_but_menutype_get(but);
2340                 if (mt) {
2341                         char str[32 + sizeof(mt->idname)];
2342                         BLI_snprintf(str, sizeof(str), "bpy.ops.wm.call_menu(name=\"%s\")", mt->idname);
2343                         WM_clipboard_text_set(str, 0);
2344                 }
2345         }
2346
2347         if (buf_paste_alloc) {
2348                 MEM_freeN((void *)buf_paste);
2349         }
2350
2351         if (show_report) {
2352                 WM_report_banner_show();
2353         }
2354 }
2355
2356 /**
2357  * Password Text
2358  * =============
2359  *
2360  * Functions to convert password strings that should not be displayed
2361  * to asterisk representation (e.g. 'mysecretpasswd' -> '*************')
2362  *
2363  * It converts every UTF-8 character to an asterisk, and also remaps
2364  * the cursor position and selection start/end.
2365  *
2366  * \note: remaping is used, because password could contain UTF-8 characters.
2367  *
2368  */
2369
2370 static int ui_text_position_from_hidden(uiBut *but, int pos)
2371 {
2372         const char *strpos, *butstr;
2373         int i;
2374
2375         butstr = (but->editstr) ? but->editstr : but->drawstr;
2376
2377         for (i = 0, strpos = butstr; i < pos; i++)
2378                 strpos = BLI_str_find_next_char_utf8(strpos, NULL);
2379
2380         return (strpos - butstr);
2381 }
2382
2383 static int ui_text_position_to_hidden(uiBut *but, int pos)
2384 {
2385         const char *butstr = (but->editstr) ? but->editstr : but->drawstr;
2386         return BLI_strnlen_utf8(butstr, pos);
2387 }
2388
2389 void ui_but_text_password_hide(char password_str[UI_MAX_PASSWORD_STR], uiBut *but, const bool restore)
2390 {
2391         char *butstr;
2392
2393         if (!(but->rnaprop && RNA_property_subtype(but->rnaprop) == PROP_PASSWORD))
2394                 return;
2395
2396         butstr = (but->editstr) ? but->editstr : but->drawstr;
2397
2398         if (restore) {
2399                 /* restore original string */
2400                 BLI_strncpy(butstr, password_str, UI_MAX_PASSWORD_STR);
2401
2402                 /* remap cursor positions */
2403                 if (but->pos >= 0) {
2404                         but->pos = ui_text_position_from_hidden(but, but->pos);
2405                         but->selsta = ui_text_position_from_hidden(but, but->selsta);
2406                         but->selend = ui_text_position_from_hidden(but, but->selend);
2407                 }
2408         }
2409         else {
2410                 /* convert text to hidden text using asterisks (e.g. pass -> ****) */
2411                 const size_t len = BLI_strlen_utf8(butstr);
2412
2413                 /* remap cursor positions */
2414                 if (but->pos >= 0) {
2415                         but->pos = ui_text_position_to_hidden(but, but->pos);
2416                         but->selsta = ui_text_position_to_hidden(but, but->selsta);
2417                         but->selend = ui_text_position_to_hidden(but, but->selend);
2418                 }
2419
2420                 /* save original string */
2421                 BLI_strncpy(password_str, butstr, UI_MAX_PASSWORD_STR);
2422                 memset(butstr, '*', len);
2423                 butstr[len] = '\0';
2424         }
2425 }
2426
2427 static void ui_but_text_clear(bContext *C, uiBut *but, uiHandleButtonData *data)
2428 {
2429         /* most likely NULL, but let's check, and give it temp zero string */
2430         if (!data->str) {
2431                 data->str = MEM_callocN(1, "temp str");
2432         }
2433         data->str[0] = 0;
2434
2435         ui_apply_but_TEX(C, but, data);
2436         button_activate_state(C, but, BUTTON_STATE_EXIT);
2437 }
2438
2439
2440 /* ************* in-button text selection/editing ************* */
2441
2442 static void ui_textedit_string_ensure_max_length(uiBut *but, uiHandleButtonData *data, int maxlen)
2443 {
2444         BLI_assert(data->is_str_dynamic);
2445         BLI_assert(data->str == but->editstr);
2446
2447         if (maxlen > data->maxlen) {
2448                 data->str = but->editstr = MEM_reallocN(data->str, sizeof(char) * maxlen);
2449                 data->maxlen = maxlen;
2450         }
2451 }
2452
2453 static void ui_textedit_string_set(uiBut *but, uiHandleButtonData *data, const char *str)
2454 {
2455         if (data->is_str_dynamic) {
2456                 ui_textedit_string_ensure_max_length(but, data, strlen(str) + 1);
2457         }
2458
2459         if (ui_but_is_utf8(but)) {
2460                 BLI_strncpy_utf8(data->str, str, data->maxlen);
2461         }
2462         else {
2463                 BLI_strncpy(data->str, str, data->maxlen);
2464         }
2465 }
2466
2467
2468 static bool ui_textedit_delete_selection(uiBut *but, uiHandleButtonData *data)
2469 {
2470         char *str = data->str;
2471         const int len = strlen(str);
2472         bool changed = false;
2473         if (but->selsta != but->selend && len) {
2474                 memmove(str + but->selsta, str + but->selend, (len - but->selend) + 1);
2475                 changed = true;
2476         }
2477
2478         but->pos = but->selend = but->selsta;
2479         return changed;
2480 }
2481
2482 /**
2483  * \param x  Screen space cursor location - #wmEvent.x
2484  *
2485  * \note ``but->block->aspect`` is used here, so drawing button style is getting scaled too.
2486  */
2487 static void ui_textedit_set_cursor_pos(uiBut *but, uiHandleButtonData *data, const float x)
2488 {
2489         uiStyle *style = UI_style_get();  // XXX pass on as arg
2490         uiFontStyle *fstyle = &style->widget;
2491         const float aspect = but->block->aspect;
2492         const short fstyle_points_prev = fstyle->points;
2493
2494         float startx = but->rect.xmin;
2495         float starty_dummy = 0.0f;
2496         char password_str[UI_MAX_PASSWORD_STR];
2497         /* treat 'str_last' as null terminator for str, no need to modify in-place */
2498         const char *str = but->editstr, *str_last;
2499
2500         ui_block_to_window_fl(data->region, but->block, &startx, &starty_dummy);
2501
2502         ui_fontscale(&fstyle->points, aspect);
2503
2504         UI_fontstyle_set(fstyle);
2505
2506         if (fstyle->kerning == 1) /* for BLF_width */
2507                 BLF_enable(fstyle->uifont_id, BLF_KERNING_DEFAULT);
2508
2509         ui_but_text_password_hide(password_str, but, false);
2510
2511         if (ELEM(but->type, UI_BTYPE_TEXT, UI_BTYPE_SEARCH_MENU)) {
2512                 if (but->flag & UI_HAS_ICON) {
2513                         startx += UI_DPI_ICON_SIZE / aspect;
2514                 }
2515         }
2516         /* but this extra .05 makes clicks inbetween characters feel nicer */
2517         startx += ((UI_TEXT_MARGIN_X + 0.05f) * U.widget_unit) / aspect;
2518
2519         /* mouse dragged outside the widget to the left */
2520         if (x < startx) {
2521                 int i = but->ofs;
2522
2523                 str_last = &str[but->ofs];
2524
2525                 while (i > 0) {
2526                         if (BLI_str_cursor_step_prev_utf8(str, but->ofs, &i)) {
2527                                 /* 0.25 == scale factor for less sensitivity */
2528                                 if (BLF_width(fstyle->uifont_id, str + i, (str_last - str) - i) > (startx - x) * 0.25f) {
2529                                         break;
2530                                 }
2531                         }
2532                         else {
2533                                 break; /* unlikely but possible */
2534                         }
2535                 }
2536                 but->ofs = i;
2537                 but->pos = but->ofs;
2538         }
2539         /* mouse inside the widget, mouse coords mapped in widget space */
2540         else {  /* (x >= startx) */
2541                 int pos_i;
2542
2543                 /* keep track of previous distance from the cursor to the char */
2544                 float cdist, cdist_prev = 0.0f;
2545                 short pos_prev;
2546
2547                 str_last = &str[strlen(str)];
2548
2549                 but->pos = pos_prev = ((str_last - str) - but->ofs);
2550
2551                 while (true) {
2552                         cdist = startx + BLF_width(fstyle->uifont_id, str + but->ofs, (str_last - str) - but->ofs);
2553
2554                         /* check if position is found */
2555                         if (cdist < x) {
2556                                 /* check is previous location was in fact closer */
2557                                 if ((x - cdist) > (cdist_prev - x)) {
2558                                         but->pos = pos_prev;
2559                                 }
2560                                 break;
2561                         }
2562                         cdist_prev = cdist;
2563                         pos_prev   = but->pos;
2564                         /* done with tricky distance checks */
2565
2566                         pos_i = but->pos;
2567                         if (but->pos <= 0) break;
2568                         if (BLI_str_cursor_step_prev_utf8(str, but->ofs, &pos_i)) {
2569                                 but->pos = pos_i;
2570                                 str_last = &str[but->pos + but->ofs];
2571                         }
2572                         else {
2573                                 break; /* unlikely but possible */
2574                         }
2575                 }
2576                 but->pos += but->ofs;
2577                 if (but->pos < 0) but->pos = 0;
2578         }
2579
2580         if (fstyle->kerning == 1)
2581                 BLF_disable(fstyle->uifont_id, BLF_KERNING_DEFAULT);
2582
2583         ui_but_text_password_hide(password_str, but, true);
2584
2585         fstyle->points = fstyle_points_prev;
2586 }
2587
2588 static void ui_textedit_set_cursor_select(uiBut *but, uiHandleButtonData *data, const float x)
2589 {
2590         if      (x > data->selstartx) data->selextend = EXTEND_RIGHT;
2591         else if (x < data->selstartx) data->selextend = EXTEND_LEFT;
2592
2593         ui_textedit_set_cursor_pos(but, data, x);
2594
2595         if      (data->selextend == EXTEND_RIGHT) but->selend = but->pos;
2596         else if (data->selextend == EXTEND_LEFT)  but->selsta = but->pos;
2597
2598         ui_but_update(but);
2599 }
2600
2601 /**
2602  * This is used for both utf8 and ascii
2603  *
2604  * For unicode buttons, \a buf is treated as unicode.
2605  */
2606 static bool ui_textedit_insert_buf(
2607         uiBut *but, uiHandleButtonData *data,
2608         const char *buf, int buf_len)
2609 {
2610         int len = strlen(data->str);
2611         int len_new = len - (but->selend - but->selsta) + 1;
2612         bool changed = false;
2613
2614         if (data->is_str_dynamic) {
2615                 ui_textedit_string_ensure_max_length(but, data, len_new + buf_len);
2616         }
2617
2618         if (len_new <= data->maxlen) {
2619                 char *str = data->str;
2620                 size_t step = buf_len;
2621
2622                 /* type over the current selection */
2623                 if ((but->selend - but->selsta) > 0) {
2624                         changed = ui_textedit_delete_selection(but, data);
2625                         len = strlen(str);
2626                 }
2627
2628                 if ((len + step >= data->maxlen) && (data->maxlen - (len + 1) > 0)) {
2629                         if (ui_but_is_utf8(but)) {
2630                                 /* shorten 'step' to a utf8 algined size that fits  */
2631                                 BLI_strnlen_utf8_ex(buf, data->maxlen - (len + 1), &step);
2632                         }
2633                         else {
2634                                 step = data->maxlen - (len + 1);
2635                         }
2636                 }
2637
2638                 if (step && (len + step < data->maxlen)) {
2639                         memmove(&str[but->pos + step], &str[but->pos], (len + 1) - but->pos);
2640                         memcpy(&str[but->pos], buf, step * sizeof(char));
2641                         but->pos += step;
2642                         changed = true;
2643                 }
2644         }
2645
2646         return changed;
2647 }
2648
2649 static bool ui_textedit_insert_ascii(uiBut *but, uiHandleButtonData *data, char ascii)
2650 {
2651         char buf[2] = {ascii, '\0'};
2652
2653         if (ui_but_is_utf8(but) && (BLI_str_utf8_size(buf) == -1)) {
2654                 printf("%s: entering invalid ascii char into an ascii key (%d)\n",
2655                        __func__, (int)(unsigned char)ascii);
2656
2657                 return false;
2658         }
2659
2660         /* in some cases we want to allow invalid utf8 chars */
2661         return ui_textedit_insert_buf(but, data, buf, 1);
2662 }
2663
2664 static void ui_textedit_move(
2665         uiBut *but, uiHandleButtonData *data, eStrCursorJumpDirection direction,
2666         const bool select, eStrCursorJumpType jump)
2667 {
2668         const char *str = data->str;
2669         const int len = strlen(str);
2670         const int pos_prev = but->pos;
2671         const bool has_sel = (but->selend - but->selsta) > 0;
2672
2673         ui_but_update(but);
2674
2675         /* special case, quit selection and set cursor */
2676         if (has_sel && !select) {
2677                 if (jump == STRCUR_JUMP_ALL) {
2678                         but->selsta = but->selend = but->pos = direction ? len : 0;
2679                 }
2680                 else {
2681                         if (direction) {
2682                                 but->selsta = but->pos = but->selend;
2683                         }
2684                         else {
2685                                 but->pos = but->selend = but->selsta;
2686                         }
2687                 }
2688                 data->selextend = EXTEND_NONE;
2689         }
2690         else {
2691                 int pos_i = but->pos;
2692                 BLI_str_cursor_step_utf8(str, len, &pos_i, direction, jump, true);
2693                 but->pos = pos_i;
2694
2695                 if (select) {
2696                         /* existing selection */
2697                         if (has_sel) {
2698
2699                                 if (data->selextend == EXTEND_NONE) {
2700                                         data->selextend = EXTEND_RIGHT;
2701                                 }
2702
2703                                 if (direction) {
2704                                         if (data->selextend == EXTEND_RIGHT) {
2705                                                 but->selend = but->pos;
2706                                         }
2707                                         else {
2708                                                 but->selsta = but->pos;
2709                                         }
2710                                 }
2711                                 else {
2712                                         if (data->selextend == EXTEND_LEFT) {
2713                                                 but->selsta = but->pos;
2714                                         }
2715                                         else {
2716                                                 but->selend = but->pos;
2717                                         }
2718                                 }
2719
2720                                 if (but->selend < but->selsta) {
2721                                         SWAP(short, but->selsta, but->selend);
2722                                         data->selextend = (data->selextend == EXTEND_RIGHT) ? EXTEND_LEFT : EXTEND_RIGHT;
2723                                 }
2724
2725                         } /* new selection */
2726                         else {
2727                                 if (direction) {
2728                                         data->selextend = EXTEND_RIGHT;
2729                                         but->selend = but->pos;
2730                                         but->selsta = pos_prev;
2731                                 }
2732                                 else {
2733                                         data->selextend = EXTEND_LEFT;
2734                                         but->selend = pos_prev;
2735                                         but->selsta = but->pos;
2736                                 }
2737                         }
2738                 }
2739         }
2740 }
2741
2742 static bool ui_textedit_delete(uiBut *but, uiHandleButtonData *data, int direction, eStrCursorJumpType jump)
2743 {
2744         char *str = data->str;
2745         const int len = strlen(str);
2746
2747         bool changed = false;
2748
2749         if (jump == STRCUR_JUMP_ALL) {
2750                 if (len) changed = true;
2751                 str[0] = '\0';
2752                 but->pos = 0;
2753         }
2754         else if (direction) { /* delete */
2755                 if ((but->selend - but->selsta) > 0) {
2756                         changed = ui_textedit_delete_selection(but, data);
2757                 }
2758                 else if (but->pos >= 0 && but->pos < len) {
2759                         int pos = but->pos;
2760                         int step;
2761                         BLI_str_cursor_step_utf8(str, len, &pos, direction, jump, true);
2762                         step = pos - but->pos;
2763                         memmove(&str[but->pos], &str[but->pos + step], (len + 1) - (but->pos + step));
2764                         changed = true;
2765                 }
2766         }
2767         else { /* backspace */
2768                 if (len != 0) {
2769                         if ((but->selend - but->selsta) > 0) {
2770                                 changed = ui_textedit_delete_selection(but, data);
2771                         }
2772                         else if (but->pos > 0) {
2773                                 int pos = but->pos;
2774                                 int step;
2775
2776                                 BLI_str_cursor_step_utf8(str, len, &pos, direction, jump, true);
2777                                 step = but->pos - pos;
2778                                 memmove(&str[but->pos - step], &str[but->pos], (len + 1) - but->pos);
2779                                 but->pos -= step;
2780                                 changed = true;
2781                         }
2782                 }
2783         }
2784
2785         return changed;
2786 }
2787
2788 static int ui_textedit_autocomplete(bContext *C, uiBut *but, uiHandleButtonData *data)
2789 {
2790         char *str;
2791         int changed;
2792
2793         str = data->str;
2794
2795         if (data->searchbox)
2796                 changed = ui_searchbox_autocomplete(C, data->searchbox, but, data->str);
2797         else
2798                 changed = but->autocomplete_func(C, str, but->autofunc_arg);
2799
2800         but->pos = strlen(str);
2801         but->selsta = but->selend = but->pos;
2802
2803         return changed;
2804 }
2805
2806 /* mode for ui_textedit_copypaste() */
2807 enum {
2808         UI_TEXTEDIT_PASTE = 1,
2809         UI_TEXTEDIT_COPY,
2810         UI_TEXTEDIT_CUT
2811 };
2812
2813 static bool ui_textedit_copypaste(uiBut *but, uiHandleButtonData *data, const int mode)
2814 {
2815         char *pbuf;
2816         bool changed = false;
2817         int buf_len;
2818
2819         /* paste */
2820         if (mode == UI_TEXTEDIT_PASTE) {
2821                 /* extract the first line from the clipboard */
2822                 pbuf = WM_clipboard_text_get_firstline(false, &buf_len);
2823
2824                 if (pbuf) {
2825                         if (ui_but_is_utf8(but)) {
2826                                 buf_len -= BLI_utf8_invalid_strip(pbuf, (size_t)buf_len);
2827                         }
2828
2829                         ui_textedit_insert_buf(but, data, pbuf, buf_len);
2830
2831                         changed = true;
2832
2833                         MEM_freeN(pbuf);
2834                 }
2835         }
2836         /* cut & copy */
2837         else if (ELEM(mode, UI_TEXTEDIT_COPY, UI_TEXTEDIT_CUT)) {
2838                 /* copy the contents to the copypaste buffer */
2839                 int sellen = but->selend - but->selsta;
2840                 char *buf = MEM_mallocN(sizeof(char) * (sellen + 1), "ui_textedit_copypaste");
2841
2842                 BLI_strncpy(buf, data->str + but->selsta, sellen + 1);
2843                 WM_clipboard_text_set(buf, 0);
2844                 MEM_freeN(buf);
2845
2846                 /* for cut only, delete the selection afterwards */
2847                 if (mode == UI_TEXTEDIT_CUT) {
2848                         if ((but->selend - but->selsta) > 0) {
2849                                 changed = ui_textedit_delete_selection(but, data);
2850                         }
2851                 }
2852         }
2853
2854         return changed;
2855 }
2856
2857 #ifdef WITH_INPUT_IME
2858 /* enable ime, and set up uibut ime data */
2859 static void ui_textedit_ime_begin(wmWindow *win, uiBut *UNUSED(but))
2860 {
2861         /* XXX Is this really needed? */
2862         int x, y;
2863
2864         BLI_assert(win->ime_data == NULL);
2865
2866         /* enable IME and position to cursor, it's a trick */
2867         x = win->eventstate->x;
2868         /* flip y and move down a bit, prevent the IME panel cover the edit button */
2869         y = win->eventstate->y - 12;
2870
2871         wm_window_IME_begin(win, x, y, 0, 0, true);
2872 }
2873
2874 /* disable ime, and clear uibut ime data */
2875 static void ui_textedit_ime_end(wmWindow *win, uiBut *UNUSED(but))
2876 {
2877         wm_window_IME_end(win);
2878 }
2879
2880 void ui_but_ime_reposition(uiBut *but, int x, int y, bool complete)
2881 {
2882         BLI_assert(but->active);
2883
2884         ui_region_to_window(but->active->region, &x, &y);
2885         wm_window_IME_begin(but->active->window, x, y - 4, 0, 0, complete);
2886 }
2887
2888 wmIMEData *ui_but_ime_data_get(uiBut *but)
2889 {
2890         if (but->active && but->active->window) {
2891                 return but->active->window->ime_data;
2892         }
2893         else {
2894                 return NULL;
2895         }
2896 }
2897 #endif  /* WITH_INPUT_IME */
2898
2899 static void ui_textedit_begin(bContext *C, uiBut *but, uiHandleButtonData *data)
2900 {
2901         wmWindow *win = CTX_wm_window(C);
2902         int len;
2903         const bool is_num_but = ELEM(but->type, UI_BTYPE_NUM, UI_BTYPE_NUM_SLIDER);
2904         bool no_zero_strip = false;
2905
2906         if (data->str) {
2907                 MEM_freeN(data->str);
2908                 data->str = NULL;
2909         }
2910
2911 #ifdef USE_DRAG_MULTINUM
2912         /* this can happen from multi-drag */
2913         if (data->applied_interactive) {
2914                 /* remove any small changes so canceling edit doesn't restore invalid value: T40538 */
2915                 data->cancel = true;
2916                 ui_apply_but(C, but->block, but, data, true);
2917                 data->cancel = false;
2918
2919                 data->applied_interactive = false;
2920         }
2921 #endif
2922
2923 #ifdef USE_ALLSELECT
2924         if (is_num_but) {
2925                 if (IS_ALLSELECT_EVENT(win->eventstate)) {
2926                         data->select_others.is_enabled = true;
2927                         data->select_others.is_copy = true;
2928
2929                 }
2930         }
2931 #endif
2932
2933         /* retrieve string */
2934         data->maxlen = ui_but_string_get_max_length(but);
2935         if (data->maxlen != 0) {
2936                 data->str = MEM_callocN(sizeof(char) * data->maxlen, "textedit str");
2937                 /* We do not want to truncate precision to default here, it's nice to show value,
2938                  * not to edit it - way too much precision is lost then. */
2939                 ui_but_string_get_ex(but, data->str, data->maxlen, UI_PRECISION_FLOAT_MAX, true, &no_zero_strip);
2940         }
2941         else {
2942                 data->is_str_dynamic = true;
2943                 data->str = ui_but_string_get_dynamic(but, &data->maxlen);
2944         }
2945
2946         if (ui_but_is_float(but) && !ui_but_is_unit(but) && !ui_but_anim_expression_get(but, NULL, 0) && !no_zero_strip) {
2947                 BLI_str_rstrip_float_zero(data->str, '\0');
2948         }
2949
2950         if (is_num_but) {
2951                 BLI_assert(data->is_str_dynamic == false);
2952                 ui_but_convert_to_unit_alt_name(but, data->str, data->maxlen);
2953         }
2954
2955         /* won't change from now on */
2956         len = strlen(data->str);
2957
2958         data->origstr = BLI_strdupn(data->str, len);
2959         data->selextend = EXTEND_NONE;
2960         data->selstartx = 0.0f;
2961
2962         /* set cursor pos to the end of the text */
2963         but->editstr = data->str;
2964         but->pos = len;
2965         but->selsta = 0;
2966         but->selend = len;
2967
2968         /* optional searchbox */
2969         if (but->type ==  UI_BTYPE_SEARCH_MENU) {
2970                 data->searchbox = but->search_create_func(C, data->region, but);
2971                 ui_searchbox_update(C, data->searchbox, but, true); /* true = reset */
2972         }
2973
2974         /* reset alert flag (avoid confusion, will refresh on exit) */
2975         but->flag &= ~UI_BUT_REDALERT;
2976
2977         ui_but_update(but);
2978
2979         WM_cursor_modal_set(win, BC_TEXTEDITCURSOR);
2980
2981 #ifdef WITH_INPUT_IME
2982         if (is_num_but == false && BLT_lang_is_ime_supported()) {
2983                 ui_textedit_ime_begin(win, but);
2984         }
2985 #endif
2986 }
2987
2988 static void ui_textedit_end(bContext *C, uiBut *but, uiHandleButtonData *data)
2989 {
2990         wmWindow *win = CTX_wm_window(C);
2991
2992         if (but) {
2993                 if (ui_but_is_utf8(but)) {
2994                         int strip = BLI_utf8_invalid_strip(but->editstr, strlen(but->editstr));
2995                         /* not a file?, strip non utf-8 chars */
2996                         if (strip) {
2997                                 /* wont happen often so isn't that annoying to keep it here for a while */
2998                                 printf("%s: invalid utf8 - stripped chars %d\n", __func__, strip);
2999                         }
3000                 }
3001
3002                 if (data->searchbox) {
3003                         if (data->cancel == false) {
3004                                 if ((ui_searchbox_apply(but, data->searchbox) == false) &&
3005                                     (ui_searchbox_find_index(data->searchbox, but->editstr) == -1))
3006                                 {
3007                                         data->cancel = true;
3008
3009                                         /* ensure menu (popup) too is closed! */
3010                                         data->escapecancel = true;
3011                                 }
3012                         }
3013
3014                         ui_searchbox_free(C, data->searchbox);
3015                         data->searchbox = NULL;
3016                         if (but->free_search_arg) {
3017                                 MEM_SAFE_FREE(but->search_arg);
3018                         }
3019                 }
3020
3021                 but->editstr = NULL;
3022                 but->pos = -1;
3023         }
3024
3025         WM_cursor_modal_restore(win);
3026
3027 #ifdef WITH_INPUT_IME
3028         if (win->ime_data) {
3029                 ui_textedit_ime_end(win, but);
3030         }
3031 #endif
3032 }
3033
3034 static void ui_textedit_next_but(uiBlock *block, uiBut *actbut, uiHandleButtonData *data)
3035 {
3036         uiBut *but;
3037
3038         /* label and roundbox can overlap real buttons (backdrops...) */
3039         if (ELEM(actbut->type, UI_BTYPE_LABEL, UI_BTYPE_SEPR, UI_BTYPE_SEPR_LINE, UI_BTYPE_ROUNDBOX, UI_BTYPE_LISTBOX))
3040                 return;
3041
3042         for (but = actbut->next; but; but = but->next) {
3043                 if (ui_but_is_editable_as_text(but)) {
3044                         if (!(but->flag & UI_BUT_DISABLED)) {
3045                                 data->postbut = but;
3046                                 data->posttype = BUTTON_ACTIVATE_TEXT_EDITING;
3047                                 return;
3048                         }
3049                 }
3050         }
3051         for (but = block->buttons.first; but != actbut; but = but->next) {
3052                 if (ui_but_is_editable_as_text(but)) {
3053                         if (!(but->flag & UI_BUT_DISABLED)) {
3054                                 data->postbut = but;
3055                                 data->posttype = BUTTON_ACTIVATE_TEXT_EDITING;
3056                                 return;
3057                         }
3058                 }
3059         }
3060 }
3061
3062 static void ui_textedit_prev_but(uiBlock *block, uiBut *actbut, uiHandleButtonData *data)
3063 {
3064         uiBut *but;
3065
3066         /* label and roundbox can overlap real buttons (backdrops...) */
3067         if (ELEM(actbut->type, UI_BTYPE_LABEL, UI_BTYPE_SEPR, UI_BTYPE_SEPR_LINE, UI_BTYPE_ROUNDBOX, UI_BTYPE_LISTBOX))
3068                 return;
3069
3070         for (but = actbut->prev; but; but = but->prev) {
3071                 if (ui_but_is_editable_as_text(but)) {
3072                         if (!(but->flag & UI_BUT_DISABLED)) {
3073                                 data->postbut = but;
3074                                 data->posttype = BUTTON_ACTIVATE_TEXT_EDITING;
3075                                 return;
3076                         }
3077                 }
3078         }
3079         for (but = block->buttons.last; but != actbut; but = but->prev) {
3080                 if (ui_but_is_editable_as_text(but)) {
3081                         if (!(but->flag & UI_BUT_DISABLED)) {
3082                                 data->postbut = but;
3083                                 data->posttype = BUTTON_ACTIVATE_TEXT_EDITING;
3084                                 return;
3085          &nbs