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