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